问题陈述
我在 Docker 容器中运行基于 Flask 的 API,该容器暴露在端口 5000 上,但是甚至没有请求到达 API。
重现
- 获取 jupyter/all-spark-notebook docker 镜像
- 在 Docker 容器中,获取任何基于 Flask 的 API,为了重现性,请尝试 https://github.com/miguelgrinberg/oreilly-flask-apis-video (为了理解一个非常简单的基于 Python 的 API 在版本中切换到 v0.1)
- 使用此处描述的标准命令运行 Docker (https://github.com/jupyter/docker-stacks/tree/master/all-spark-notebook)。忘记笔记本部分,只使用
-p 5000:5000
获取要运行的 API 首选端口。不要使用 HTTPS,但要在容器上安装 ssh。 (所以除非你像我一样使用自定义 Dockerfile,否则你需要启用 SUDO) - 尝试向 API 发出任何请求(例如
http GET http://localhost:5000/customers/1
)--> 这失败了 并根据不同得到不同的错误消息- 是否是
Python based urlib request (IOError: ('http protocol error', 0, 'got a bad status line', None))
- 或基于 HTTPie (
http: error: ConnectionError: HTTPConnectionPool(host='localhost', port=5000): Max retries exceeded with url: /filterReplies/aaaaa/aaaa (Caused by <class 'http.client.RemoteDisconnected'>: Remote end closed connection without response)
)
- 是否是
- 查看日志,没有任何API请求的记录
注意事项
- 我在 Linux 机器上运行,因此不需要 VM。
- 制作
wget http://localhost:5000
有区别(获取Connecting to localhost (localhost)|127.0.0.1|:5000... connected. HTTP request sent, awaiting response... No data received. Retrying.
)和wget http://localhost:1234
(得到Resolving localhost (localhost)... 127.0.0.1 Connecting to localhost (localhost)|127.0.0.1|:8888... failed: Connection refused.
)所以端口在某种程度上是开放的,但似乎没有任何东西在另一边等待? - 图像的最初用途仍然有效——即如果我指定要转发的两个端口,我仍然可以基于浏览器访问 docker 容器中的 Jupyter notebooks。所以这台机器上的一些端口转发是有效的。
最佳答案
绑定(bind)到 0.0.0.0
将在任何可用接口(interface)中绑定(bind)您的应用程序,localhost 不会。有一篇文章描述了 localhost
和 0.0.0.0
之间的区别,如果我发现我会更新这篇文章。
关于linux - Docker 为 Flask API 公开端口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34922698/