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
Code language: plaintext (plaintext)

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)
Code language: Python (python)

requirements.txt

Flask==2.1.1
Code language: plaintext (plaintext)

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"]
Code language: Dockerfile (dockerfile)

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"]
Code language: Dockerfile (dockerfile)

Step 3 – Build your Docker image

Build your Docker image:

docker build -t ourflaskapp:latest .
Code language: Bash (bash)

Step 4 – Run your Docker container

Run your new Docker container:

sudo docker run -p 5000:5000 ourflaskapp
Code language: CSS (css)
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments