繁体   English   中英

对 Flask 应用程序的请求无法通过 Docker 容器

[英]Request to Flask Application Does Not Get Through to Docker Container

我使用 Python (3.7.4) 和 Flask ( hello.py ) 编写了一个 «Hello World» 应用程序:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'

if __name__ == '__main__':
    app.run(host='0.0.0.0')

我使用以下版本的 Flask 和 gunicorn ( requirements.txt ):

Flask==1.1.1
gunicorn==19.9.0

我安装如下:

$ sudo pip install -r requirements.txt

由于我在 Arch Linux 上运行示例, pip实际上是pip3

当我启动应用程序时:

$ gunicorn hello:app

该应用程序按预期工作:

$ curl localhost:8000
Hello, World!

现在我想使用 Docker(版本 19.03.3-ce)运行它,为此我写了这个Dockerfile

FROM python:3.7.4

RUN mkdir /app
WORKDIR /app

COPY requirements.txt /app/
RUN pip install -r requirements.txt

COPY hello.py /app

EXPOSE 8000

CMD ["gunicorn", "hello:app", "--log-file=-"]

我构建映像并使用 shell 脚本 ( run.sh ) 运行容器:

#!/bin/sh

docker build . -t flaskdemo
docker run -it --rm --name flaskdemoapp -p 8000:8000 flaskdemo

哪个按预期工作:

$ ./run.sh
Sending build context to Docker daemon  66.05kB
Step 1/8 : FROM python:3.7.4
 ---> 9fa56d0addae
Step 2/8 : RUN mkdir /app
 ---> Using cache
 ---> 81a38303aabd
Step 3/8 : WORKDIR /app
 ---> Using cache
 ---> a73abfac4cdf
Step 4/8 : COPY requirements.txt /app/
 ---> Using cache
 ---> e7507f42bbae
Step 5/8 : RUN pip install -r requirements.txt
 ---> Using cache
 ---> 06c4adb1310b
Step 6/8 : COPY hello.py /app
 ---> Using cache
 ---> fa5d374f6c93
Step 7/8 : EXPOSE 8000
 ---> Using cache
 ---> df5e0d5ada7d
Step 8/8 : CMD ["gunicorn", "hello:app", "--log-file=-"]
 ---> Using cache
 ---> 08babb3f604a
Successfully built 08babb3f604a
Successfully tagged flaskdemo:latest
[2019-10-19 13:09:43 +0000] [1] [INFO] Starting gunicorn 19.9.0
[2019-10-19 13:09:43 +0000] [1] [INFO] Listening at: http://127.0.0.1:8000 (1)
[2019-10-19 13:09:43 +0000] [1] [INFO] Using worker: sync
[2019-10-19 13:09:43 +0000] [8] [INFO] Booting worker with pid: 8

不幸的是,请求没有通过容器:

$ curl localhost:8000
curl: (56) Recv failure: Connection reset by peer

容器中没有额外的日志行。

Docker 通常在我的机器上工作正常。 例如,当我运行httpd时:

$ docker run -p 8080:80 httpd

我收到了对我的请求的回复:

$ curl localhost:8080
<html><body><h1>It works!</h1></body></html>

所以我想我的Dockerfile或者我运行容器的方式一定有问题。

PS:随意从我的 GitHub repo克隆代码

我认为您的 Dockerfile 应该如下所示:

FROM python:3.7.4
ADD . /app
WORKDIR /app
COPY requirements.txt /app/
RUN pip install -r requirements.txt
EXPOSE 8000
CMD ["gunicorn", "-b", "0.0.0.0:8000", "app"]

然后运行:

docker build --tag flask_gunicorn_app .
docker run --detach -p 80:8000 flask_gunicorn_app

暂无
暂无

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

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