Cover image for Running Docker Container With Gunicorn and Flask

Running Docker Container With Gunicorn and Flask

marounmaroun profile image Maroun Maroun ・1 min read

In this post, I'll show how to serve a simple Flask application with Gunicorn, running inside a Docker container.

Let's begin from creating a minimal Flask application:

from flask import Flask

app = Flask(__name__)

def index():
    return 'Hello world!'

Next, let's write the command that will run the Gunicorn server:


gunicorn --chdir app main:app -w 2 --threads 2 -b

The parameters are pretty much self-explanatory: We are telling Gunicorn to spawn 2 worker processes, running 2 threads each. We are also accepting connections from outside, and overriding Gunicorn's default port (8000).

Our basic Dockerfile:

FROM python:3.7.3-slim

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

COPY . /app

ENTRYPOINT ["./gunicorn_starter.sh"]

Let's build our image:

docker build -t flask/hello-world .

and run:

docker run -p 8003:8003 flask/hello-world

Now we should be able to access our endpoint:

$ curl localhost:8003
Hello world!

Bonus - Makefile

Let's create a simple Makefile that allows us to build, run and kill our image/container:

app_name = gunicorn_flask

    @docker build -t $(app_name) .

    docker run --detach -p 8003:8003 $(app_name)

    @echo 'Killing container...'
    @docker ps | grep $(app_name) | awk '{print $$1}' | xargs docker

Now we should be able to run:

# build Docker image
make build
# run the container
make run
# destroy it
make kill

Posted on by:

marounmaroun profile

Maroun Maroun


Nice to meet you 🍻 My name is Maroun. I'm a dad, musician, programmer, Stackoverflower and astronaut wannabe.


Editor guide