繁体   English   中英

Docker 容器中的 Gunicorn Flask 应用程序未暴露

[英]Gunicorn Flask application in Docker Container not getting Exposed

容器内的应用程序无法从外部访问,即如果我执行到 docker 容器并执行

curl localhost:5000 

它工作正常,但不能在我电脑的浏览器上运行我收到错误:无法访问此站点

我的 Dockerfile:

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

# Set the working directory to /app
WORKDIR /web-engine

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

# Install Gunicorn3
RUN apt-get update && apt-get install default-libmysqlclient-dev gcc -y

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

# Make port 5000 available to the world outside this container
EXPOSE 5000

# Define environment variable
ENV username root

# Run app.py when the container launches
CMD gunicorn --workers 4 --bind 127.0.0.1:5000 application:app --threads 1

UPON 以这种方式执行 docker:

sudo docker run -e password=$password -p 5000:5000 $reg/web-engine:ve0.0.2

我得到以下输出:

[2019-09-08 11:53:36 +0000] [6] [INFO] Starting gunicorn 19.9.0
[2019-09-08 11:53:36 +0000] [6] [INFO] Listening at: http://127.0.0.1:5000 (6)
[2019-09-08 11:53:36 +0000] [6] [INFO] Using worker: sync
[2019-09-08 11:53:36 +0000] [9] [INFO] Booting worker with pid: 9
[2019-09-08 11:53:36 +0000] [10] [INFO] Booting worker with pid: 10
[2019-09-08 11:53:36 +0000] [11] [INFO] Booting worker with pid: 11
[2019-09-08 11:53:36 +0000] [12] [INFO] Booting worker with pid: 12

如您所见,我将容器的端口 5000 映射到计算机的端口 5000,但 localhost:5000 不起作用

因此,我尝试了相同的方法,但使用 Flask 的开发服务器,在我的 dockerfile 中进行了以下更改

CMD gunicorn --workers 4 --bind 127.0.0.1:5000 application:app --threads 1

CMD python3.7 application.py

它奏效了; 我转到 localhost:5000 并看到应用程序正在运行

应用程序没有任何问题。 我想 gunicorn 服务器有错误

requirements.txt 文件:

Flask
Flask-SQLAlchemy
mysqlclient
gunicorn
bs4
html5lib

请帮帮我

我还尝试了不同形式的 gunicorn 和 docker run 命令组合,例如

CMD gunicorn -application:app && sudo docker run -e password=$password -p 5000:8000 $reg/web-engine:ve0.0.2

它没有与开发服务器一起工作的容器的终端图像

我希望有一个解决方案,不涉及这里提到的任何内容,如 nginx、主管等某人请见鬼去吧……😢

默认情况下,127.0.0.1 意味着容器内部与外部不同。 使用0.0.0.0:5000代替。

扩展另一个答案:Docker 端口转发的工作方式是从主机上的 IP 转发到容器中的一个地址。 具体来说,是与将容器连接到主机网络的 Docker 桥接网络通信的外部地址。 它无法与容器上的127.0.0.1 ,因为这是一个私有127.0.0.1主机有自己的127.0.0.1

因此,您需要绑定到该 Docker 桥接网络,或者通过绑定到0.0.0.0来绑定到所有接口,这是最简单的解决方案。

用散文解释这个有点棘手,但我有更长的版本,其中还包括图表,因此可能更容易理解: https : //pythonspeed.com/articles/docker-connection-refused/

在你的 Dockerfile 中试试这个命令:

CMD ["flask", "run", "--host=0.0.0.0"]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM