Dockerize a flask application

In this article you'll learn how to run a small flask application in a docker container.

Let's start by creating the python application

./app.py

#!/usr/bin/env python

import os
from flask import Flask, render_template

app = Flask(__name__)


@app.route("/")
def homepage():
    return render_template('layout.html', background=os.getenv('BACKGROUND', '#fcf1ca'))


@app.route("/healthz")
def health():
    return "OK"


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

Then create the template file

./templates/layout.html

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>My first flask application</title>
</head>
<body style="background: {{ background }};">

<h1>Hello from Flask framework</h1>

</body>
</html>

And finaly create the docker file for our application

./docker/flask/Dockerfile

FROM python:3.9

COPY . /app/

WORKDIR /app

RUN cp /usr/share/zoneinfo/Europe/Berlin /etc/localtime \
    && pip install flask gunicorn

EXPOSE 5000

# run without gunicorn in development mode
#ENTRYPOINT ["python"]
#CMD ["/app/app.py"]

# Run the container with gunicorn
CMD ["gunicorn", "--workers=2", "--chdir=/app", "--bind", "0.0.0.0:5000", "--access-logfile=-", "--error-logfile=-", "app:app"]

To build the container, run the following command:

docker build -f docker/flask/Dockerfile -t my-flask-app .

Run the container

docker run --rm -e BACKGROUND="#fce2ca" -p 5000:5000 -t my-flask-app

Then open the url in your browser: http://localhost:5000

Enjoy!