Docker部署Gradio项目

使用Docker简单部署Gradio项目

创建 main.py 文件,在此文件中编辑gradio内容

import gradio as gr
  
def greet(name):
    return "Hello " + name + "!!"

demo = gr.Interface(fn=greet, inputs="text", outputs="text")

if __name__ == "__main__":
    demo.launch(server_name="0.0.0.0")  
    # 注意:gradio启动项目后默认地址为127.0.0.1;使用docker部署需要将地址修改为0.0.0.0,否则会导致地址访问错误
    # 默认端口为7860,如需更改可在launch()中设置server_port=7000
~                                      

编辑 requirements.txt 文件,将项目所有需要的包添加到此文件

gradio==2.9.4

编辑 Dockerfile 文件

# Use an official Python runtime as a parent image
FROM python:3.7.4-slim

# Set the working directory to /app
WORKDIR /app

# Copy the current directory contents into the container at /app
COPY . /app

# Install any needed packages specified in requirements.txt
RUN pip3 install --trusted-host pypi.python.org -r requirements.txt

# Define environment variable
ENV NAME gradio

# The default gradio port is 7860
EXPOSE 7860

# Run main.py when the container launches
CMD ["python", "main.py"]
~                            

其中涉及到的问题:
gradio项目启动后默认使用的地址为127.0.0.1,使用docker部署后导致外部无法访问
这是因为打包成镜像之后127.0.0.1只表示本机本容器中的一个虚拟网卡,只接受本容器中的应用相互通讯。虽然说服务已经成功启动了,但是外部却不能访问。所以将项目地址修改为0.0.0.0就可以正常运行了

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容