10GritSandpaper 10GritSandpaper - 2 months ago 10
Python Question

How to run Python Flask within a Docker container

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.

What I've done:

I created

/temp/HelloFlask.py


from flask import Flask
app = Flask(__name__)

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

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


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


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!


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.

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.

Answer

Try app.run(host='0.0.0.0').

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.