18

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.

SGT Grumpy Pants
  • 4,118
  • 4
  • 42
  • 64

1 Answers1

47

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.

Erdi Aker
  • 786
  • 7
  • 9
  • 5
    I have the same issue, but `host='0.0.0.0'` is not working. Even if I do `app.run(host='0.0.0.0', port=1234)` and do `docker-compose up`, it says: `Running on http://127.0.0.1:5000/` why is it not running on host and port i am specifying. – Arnold Parge Jul 06 '18 at 11:06
  • 10
    Thanks so much, spent two evenings trying to figure this one out. Seems that for the newer versions of Flask you need to add it to the python command: CMD ["python3", "-m", "flask", "run", "--host=0.0.0.0"] – xeonman9000 Feb 22 '19 at 01:02