如何在Docker容器中运行Python Flask [英] How to run Python Flask within a Docker container

查看:377
本文介绍了如何在Docker容器中运行Python Flask的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在docker容器中运行Python Flask网络服务器,但无法从外部连接到Flask服务器。

I'm trying to run a Python Flask webserver within a docker container, but I can't connect to the Flask server from the outside.

我做了什么:

我创建了 /temp/HelloFlask.py

from flask import Flask
app = Flask(__name__)

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

if __name__ == "__main__":
    app.run()

我启动了Docker容器,将容器端口5000映射到主机端口5000并将〜/ temp安装到/ temp

I started the docker container with container port 5000 mapped to host port 5000 and with ~/temp mounted to /temp

docker run -it -p 5000:5000 -v ~/temp:/temp --name tf gcr.io/tensorflow/tensorflow:latest-devel

在运行的Docker容器中,我安装了Flask并运行 HelloFlask.py

Inside the running docker container, I installed Flask and ran HelloFlask.py

cd /temp
pip install Flask
python HelloFlask.py &

我确认服务器可以在容器中访问

I validated that the server was accessible within the container

[root@de8b6996b540:/temp# curl localhost:5000
127.0.0.1 - - [22/Sep/2016 17:41:48] "GET / HTTP/1.1" 200 -
Hello World!

我正在使用Docker 1.12.1版(内部版本:12133),该容器暴露了以下容器端口localhost,因此我应该能够在Mac上的容器外部访问 localhost:5000 ,但无法连接。

I'm using Docker Version 1.12.1 (build: 12133), which exposes the container ports on localhost, so I should be able to access localhost:5000 on my Mac, outside the container, but I can't connect.

我进行了测试,以确保Docker通过运行nginx容器(如用于Mac快速入门的docker ,我可以通过本地主机从容器访问端口。

I tested to make sure that Docker was correctly binding container ports to localhost by running an nginx container as described in the docker for mac quickstart, and I can access ports from the container via localhost just fine.

推荐答案

尝试 app.run(host ='0.0.0.0')

默认情况下,Flask服务器仅可从本地主机访问。在您的情况下,容器是本地主机,并且您的请求是从容器外部发出的。 host ='0.0.0.0'参数使服务器可以从外部IP访问。 Flask文档中有详细描述。

By default, Flask server is only accessible from the localhost. In your case, the container is the localhost, and your requests are originating from outside the container. host='0.0.0.0' parameter makes the server accessible from external IPs. It's described in Flask documentation in detail.

这篇关于如何在Docker容器中运行Python Flask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆