10GritSandpaper 10GritSandpaper - 1 year ago 117
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


from flask import Flask
app = Flask(__name__)

def hello():
return "Hello World!"

if __name__ == "__main__":

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

cd /temp
pip install Flask
python HelloFlask.py &

I validated that the server was accessible within the container

[root@de8b6996b540:/temp# curl localhost:5000 - - [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
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 Source

Try app.run(host='').

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='' parameter makes the server accessible from external IPs. It's described in Flask documentation in detail.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download