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


#!/usr/bin/env python

import os
from flask import Flask, render_template

app = Flask(__name__)

def homepage():
    return render_template('layout.html', background=os.getenv('BACKGROUND', '#fcf1ca'))

def health():
    return "OK"

if __name__ == '__main__':, host="", port="5000")

Then create the template file


<!doctype html>
<html lang="en">
    <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>
<body style="background: {{ background }};">

<h1>Hello from Flask framework</h1>


And finaly create the docker file for our application


FROM python:3.9

COPY . /app/


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


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

# Run the container with gunicorn
CMD ["gunicorn", "--workers=2", "--chdir=/app", "--bind", "", "--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