使用Docker簡單部署Gradio項目
創(chuàng)建 main.py 文件,在此文件中編輯gradio內(nèi)容
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,否則會導(dǎo)致地址訪問錯誤
# 默認端口為7860,如需更改可在launch()中設(shè)置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部署后導(dǎo)致外部無法訪問
這是因為打包成鏡像之后127.0.0.1只表示本機本容器中的一個虛擬網(wǎng)卡,只接受本容器中的應(yīng)用相互通訊。雖然說服務(wù)已經(jīng)成功啟動了,但是外部卻不能訪問。所以將項目地址修改為0.0.0.0就可以正常運行了