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:

1
2
3
4
└── flaskapp
        ├── Dockerfile
        ├── app.py
        └── requirements.txt

Step 1 – Create your Flask app

In a new directory, create the following files:

app.py

1
2
3
4
5
6
7
8
9
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

1
Flask==2.1.1

Step 2 – Create your Docker file

In the same directory, create a Dockerfile:

Dockerfile

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
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:

1
docker build -t ourflaskapp:latest .

Step 4 – Run your Docker container

Run your new Docker container:

1
sudo docker run -p 5000:5000 ourflaskapp