Skip to content
Advertisement

Minimal Flask app unreachable from Docker container

I have a very simple flask service that I’m trying to run inside a docker container.
I used python to implement a minimal application that is working fine on my Windows, but isn’t reachable when inside a Docker container.
I tried the common fix of setting –host=0.0.0.0 (tried multiple ways), but it did not solve my problem.

Project structure:
├── application/
│ ├── Dockerfile
│ ├── requirements.txt
│ ├── service.py

Dockerfile:

# syntax=docker/dockerfile:1

FROM python:3.6.5-alpine

RUN apk --update add bash nano

COPY requirements.txt /tmp/
RUN pip3 install -r /tmp/requirements.txt

COPY . .

ENV FLASK_ENV=development
CMD ["python", "service.py"]  

service.py:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def greetings():
    return "Welcome my service!"

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

Finally, here’s the log when I start the Docker image in interactive mode:

[...]/.venv/Scripts/Activate.ps1"
 * Serving Flask app 'service' (lazy loading)
 * Environment: development
 * Debug mode: on
 * Running on all addresses.
   WARNING: This is a development server. Do not use it in a production deployment.
 * Running on http://172.17.0.2:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 277-473-905

So there appears to be no problems, however when I use a browser (Google Chrome) to visit the address shown in the console, it just loads forever then displays that the site is unreachable (ERR_CONNECTION_TIMED_OUT).
Also, I can run the flask with no problem from my native OS by typing the following commands from a bash terminal:

export FLASK_APP=service
export FLASK_ENV=development
flask run

Can anybody help me understand why it’s not working inside a Docker container? It’s working from outside, and I thought adding host='0.0.0.0' was supposed to make the container accessible from outside.

Edit: docker command tested:

docker run --rm -it  scone:latest
docker run --rm -p 5000:5000 scone:latest

RESOLVED
The trick, as mentioned by u/OneCricketeer, is to use -p 5000:5000 argument in docker run, and now you can use reach the container BUT you have to ignore the address given in the docker terminal. Use this instead : http://localhost:5000 (the ip it would give you if you ran flask from outside the docker container.)

Advertisement

Answer

The issue that you are likely seeing is that your windows host cannot get to the docker container. The networking is not exposed to your host so you’ll need to include the -p 5000:5000 option on the docker command line to tell docker to forward host port 5000 to the docker container port 5000.

In short:

docker run --rm -it -p 5000:5000  scone:latest

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement