gpt4 book ai didi

docker - 简单的 flask 服务在 docker 容器外不响应

转载 作者:行者123 更新时间:2023-12-03 16:02:32 26 4
gpt4 key购买 nike

嗨,提前感谢,我是 docker 新手,我被困在一个简单的 docker 示例上,该示例将 flask 服务暴露在容器外。

我有一个名为 rest_example 的文件夹在 dockerfile 和 .py 文件中。
这是我的 docker 文件:

FROM ubuntu:16.04
LABEL maintainer="Lorem Ipsum"
RUN apt-get update && \
apt-get install -y python && \
apt-get install -y python-pip && \
pip install Flask && \
apt-get install -y curl && \
mkdir files
COPY flask_example.py /files
ENV FLASK_APP /files/flask_example.py
EXPOSE 5000
CMD flask run

这是flask_example.py:
from flask import Flask

app = Flask(__name__)

@app.route("/hello")
def hello():
return "Hello World!"

我正在创建这样的图像:
docker run rest_example -t -p 5000:5000 --name=rest_example --rm

当我点击 curl localhost:5000/hello在容器内这是响应: Hello World! , 表示 flask 在容器内,但是在我的本地浏览器中没有对该 url 的响应。

最佳答案

如果您查看 documentation , 你会找到:

Externally Visible Server

If you run the server you will notice that the server is only accessible from your own computer, not from any other in the network. This is the default because in debugging mode a user of the application can execute arbitrary Python code on your computer.

If you have the debugger disabled or trust the users on your network, you can make the server publicly available simply by adding --host=0.0.0.0 to the command line:

flask run --host=0.0.0.0

This tells your operating system to listen on all public IPs.



您在启动容器时确实发布了端口 5000,但没有指示 Flask 实际监听“外部”接口(interface)。

您确实启动了容器以将容器的“外部”链接到本地​​计算机,但是那里没有任何监听。

像这样尝试你的 dockerfile,添加上面显示的文档中提到的参数:
FROM ubuntu:16.04
LABEL maintainer="Lorem Ipsum"
RUN apt-get update && \
apt-get install -y python && \
apt-get install -y python-pip && \
pip install Flask && \
apt-get install -y curl && \
mkdir files
COPY flask_example.py /files
ENV FLASK_APP /files/flask_example.py
EXPOSE 5000
CMD flask run --host=0.0.0.0

关于docker - 简单的 flask 服务在 docker 容器外不响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50728202/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com