Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The flask host adress in docker run

I want to run a flask application in Docker, with the flask simple http server. (Not gunicorn)

I got a host setting problem.

In the flask app.py, it should be work as the official tutorial, but it doesn't work:

if __name__ == '__main__':
    app.run(host='0.0.0.0')

So I did it after an answer of a similar post, it suddenly works!:

https://stackoverflow.com/a/43015007/3279996

$> flask run --host=0.0.0.0

My question is why this first method doesn't work, but second works?

like image 732
xirururu Avatar asked Nov 03 '18 16:11

xirururu


People also ask

What is hostname in docker run?

This flag, --hostname is used to change the host name of you container, its used when you run your container. This does not change the container's DNS outside docker and it also does not provide any network isolation, so you cannot connect to the container using the hostname.

How do I connect to docker host?

Accessing the Host With the Default Bridge Mode You just need to reference it by its Docker network IP, instead of localhost or 127.0. 0.1 . Your host's Docker IP will be shown on the inet line. Connect to this IP address from within your containers to successfully access the services running on your host.

What is the hostname of a container?

The hostname of a Container is the name of the Pod in which the Container is running.


1 Answers

In the first solution, when you run the code with the python3 app.py command, it runs on 0.0.0.0 on the host. But the flask run command executes the flask app directly from the code and does not include the condition if name == 'main':. On the other hand, when you run the code with python3 app.py, name equals 'main'. But when you run the code with flask run, name is equal to the FLASK_APP variable that becomes an app in your code, and the FLASK_APP variable must be the same as the file name that flask app contains.

app.py

print("__name__ is :", __name__)

python3 app.py

__name__ is : __main__

app.py

$> export FLASK_APP=app.py
$> flask run

...
__name__ is : app
...
like image 101
Mohammadreza Avatar answered Sep 25 '22 01:09

Mohammadreza