DEV Community

Azizul Haque Ananto
Azizul Haque Ananto

Posted on

Deploy Django or Flask in 3 easy steps (in production)

No intro, let's jump to the steps.

1. Write a Dockerfile 😐 (why not)

This is my directory structure -

├── app/
│     .....
├── requirements.txt
├── Dockerfile
Enter fullscreen mode Exit fullscreen mode

This is the Dockerfile -

FROM python:3.7.3-slim

WORKDIR /user/src

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

COPY ./app ./app
COPY ./ ./

Enter fullscreen mode Exit fullscreen mode

Things to remember -

  1. Use small docker images like -slim or -alpine. -alpine is the lightest but in my case -alpine haven't got the gcc so I used -slim. (I could've install gcc manually in alpine)
  2. Import requirements and install them before importing codes. Why? If we change our code, we won't need to install requirements in every build. Simple and easy way to reduce build times 🤗

2. Gunicorn server

Why Gunicorn? 🧐 -> Django or Flask is a framework, not server. So we need a server to serve our application built with the framework. Gunicorn is a WSGI supported server that can communicate with other application that supports WSGI like Flask or Django. WSGI is a gateway interface that matches the URI defined in the python application.

Now install gunicorn and add to the requirements.txt

pip install gunicorn
pip freeze > requirements.txt
Enter fullscreen mode Exit fullscreen mode

This is the file we have seen earlier -

gunicorn --chdir app wsgi:app -w 2 --threads 2 -b
Enter fullscreen mode Exit fullscreen mode

We show gunicorn our project directory with --chdir app. wsgi:app for Django apps and for Flask, we need the file name where we did app = Flask(), like this - <file_contains_app>:app. Change worker and thread as per your need. Too much workers actually makes a system slow, why? Because workers are processes, and they shares same CPU core. And we should know our threads right? 😅

3. Build & Deploy (Seek & Destroy ☠️)

Build the docker image -

docker build -t <your_tag> .
Enter fullscreen mode Exit fullscreen mode

This image is production ready! Beleive it or not 😐

Run it 🤘 -

docker run --name <image_name> -p 8003:8003 -e DB_URI=<your_db_uri> <your_tag>
Enter fullscreen mode Exit fullscreen mode

-e DB_URI=<your_db_uri> here -e sets the environment variable. I set my DB with URI, so I passed this environment variable DB_URI while running my image.

This is it! 🥳 If you have any questions or face any problem, comment below 👇

Top comments (0)