How to assign an IP to Flask application running in a Docker container

Viewed 1460

I have a simple Flask application that just outputs "Hello world". If I do something like flask run --host=127.0.0.23 --port=5001 on my host machine, I can ping the app on my browser on the given hostname and port.

However, if I do the same thing when running this app inside a Docker container i.e. I have CMD flask run --host=127.0.0.23 --port=5001 inside my Dockerfile, I cannot ping the application on my host machines browser.

I understand that having app.run(host='0.0.0.0') inside the Flask app makes it accessible at localhost:5000 on my host machine. But I want to know if I can access the app using a hostname I assign myself.

Code for Flask application:

from flask import Flask
app = Flask(__name__)

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

if __name__ == "__main__":
    app.run(host="0.0.0.0")
1 Answers

You don't "assign an ip" to your application. You publish the port on your host. That is, if your application listens on port 5000 inside the container, you might run:

docker run -p 5000:5000 myimage ...

This will expose the service on port 5000 of your host, which means that a browser running on your host could access the service at either localhost:5000 or <any_address_of_your_host>:5000, and a browser elsewhere on your network could access the service at <any_routeable_address_of_your_host>:5000 as well.

There doesn't need to be any correlation between the port on which your application is listening and the port on which you publish it. E.g., for the above you could instead run:

docker run -p 80:5000 myimage ...

This would expose your application on port 80 on your host.

Read the Container Networking documentation for more information.

Related