DEV Community

Cover image for Running Docker Container With Gunicorn and Flask
Maroun Maroun
Maroun Maroun

Posted on

Running Docker Container With Gunicorn and Flask

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__)


@app.route('/')
@app.route('/index')
def index():
    return 'Hello world!'
Enter fullscreen mode Exit fullscreen mode

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

#!/bin/sh

gunicorn --chdir app main:app -w 2 --threads 2 -b 0.0.0.0:8003
Enter fullscreen mode Exit fullscreen mode

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
WORKDIR /app

ENTRYPOINT ["./gunicorn_starter.sh"]
Enter fullscreen mode Exit fullscreen mode

Let's build our image:

docker build -t flask/hello-world .
Enter fullscreen mode Exit fullscreen mode

and run:

docker run -p 8003:8003 flask/hello-world
Enter fullscreen mode Exit fullscreen mode

Now we should be able to access our endpoint:

$ curl localhost:8003
Hello world!
Enter fullscreen mode Exit fullscreen mode

Bonus - Makefile

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

app_name = gunicorn_flask

build:
    @docker build -t $(app_name) .

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

kill:
    @echo 'Killing container...'
    @docker ps | grep $(app_name) | awk '{print $$1}' | xargs docker
Enter fullscreen mode Exit fullscreen mode

Now we should be able to run:

# build Docker image
make build
# run the container
make run
# destroy it
make kill
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
arnabsen1729 profile image
Arnab Sen

If there is a .env file in the project will the gunicorn service read those variables?

Collapse
 
phlaange profile image
Sean S

Where's contents of requirements.txt?

Is it similar to:

gunicorn
Flask