How to deploy Django project to fly.io?

Published 18 May, 2022

Reading time: 2 Mins


Deploying django application into fly.io paas server.

I like fly.io because it’s easy to deploy webserver application. I was a big fan of render.com and before that I was using Heroku. But the thing about fly.io is that the free plan doesn’t let sleep the server. Meaning it always awake. And I can see the website returns a response whenever I make the call. And for that reason I am fond to use fly.io for my existing and upcoming projects.

But the hard problem is to deploy the application into fly.io. I know that fly.io dev team works very hard to makes this process easier. But sometimes you need to have an external eye to shed some light into it. I hope that this document will help you to launch your application into fly.io

Preparing Django application

To prepare for the fly.io you don’t normally need anything. The fly.io cli will take care of everything. From creating the docker file to fly configuration file.

I assume that you have integrated Django-environ into it. If not please do because it’s the best way to create the environment variable for you project and that makes your app 12factor app.

And after that you can run fly launch that will ask you few question regarding your application and then it will generate below configuration files.

Note: If you already have a docker file then it will use that else fly will generate one for you.

ARG PYTHON_VERSION=3.9

FROM python:${PYTHON_VERSION}

RUN apt-get update && apt-get install -y \
    python3-pip \
    python3-venv \
    python3-dev \
    python3-setuptools \
    python3-wheel

RUN mkdir -p /app
WORKDIR /app

COPY requirements.txt .
RUN pip install -r requirements.txt

COPY . .

RUN python manage.py collectstatic --noinput

EXPOSE 8080

# replace APP_NAME with module name
CMD ["gunicorn", "--bind", ":8080", "--workers", "2", "demo.wsgi"]

And the generated toml file looks like this.

app = "demo"

kill_signal = "SIGINT"
kill_timeout = 5
processes = []

[deploy]
  release_command = "python manage.py migrate"
--- rest of configuration

So what’s going on here. When you run the fly launch it will create the environment in fly.io and one docker builder instance in your account. When you run fly deploy application it will build the application using that builder instance and deploy your application into launch environment that it created already.

So for the deployment steps all we need to do is put our .env files into fly instance and then issue a deploy command.

flyctl secrets import < .env

flyctl deploy

These two comments enough to deploy the application into fly.io. In my next blog I will talk about how to automate the deployment process once we push our code to GitHub.

This article published under development on django tags. If you wish to receive email from me when I post a new blog post then please subscribe to my newsletter.


You might also like