How to Dockerize a Flask App


If you have a Flask app that you would like packaged in a Docker container, then you can do the following. The steps outlined below will help you create the following directory tree:

└── flaskapp
        ├── Dockerfile
        ├── app.py
        └── requirements.txt

Step 1 – Create your Flask app

In a new directory, create the following files:

app.py

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_geek():
  return '<h1>Hello world!</h2>'

if __name__ == "__main__":
  app.run(debug=True)

requirements.txt

Flask==2.1.1

Step 2 – Create your Docker file

In the same directory, create a Dockerfile:

Dockerfile

FROM python:3.8-slim-buster

WORKDIR /python-docker

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

COPY . .

CMD [ "python3", "-m" , "flask", "run", "--host=0.0.0.0"]

If you want to pass environment variables to your running docker container, then potentially use the following instead:

FROM python:3.8-slim-buster

WORKDIR /python-docker

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

COPY . .

ENTRYPOINT ["python3"]

CMD ["app.py"]

Step 3 – Build your Docker image

Build your Docker image:

docker build -t ourflaskapp:latest .

Step 4 – Run your Docker container

Run your new Docker container:

sudo docker run -p 5000:5000 ourflaskapp