Connect a postgres database to a django app in fly.io

https://images.fmacedo.com/postgres_fly_io_cover.png

The problem

Lately I've been using Fly.io to deploy some of my Django apps. It's easy to deploy, cheap and simple to manage (I'm not sponsored in any way, I just like it). Usually, when you launch a new Django app, Fly.io automatically creates a postgres cluster, a postgres database within it and automatically connects it to your Django app using the DATABASE_URL environment variable. Both the Django app and the postgres cluster are two independent fly.io apps and the DATABASE_URL defines an internal connection that looks something like this:

postgres://django_app_name:AP3jq&oU*p@6KA@postgres_cluster_app_name.flycast:5432/django_app_name

Recently, when creating a Django app, I found that Fly.io didn't create the corresponding postgres cluster, although I explicitly chose to do so. I have no idea why, and instead of trying to figure it out, I decided to create a postgres cluster manually and connect it to the Django app. I found the docs not very straightforward so here are the simple steps required.

The solution

1 - Create a postgres cluster app

To create a postgres cluster, simply run this command and choose a name for it:

  fly postgres create

It will print a connection string. You might be tempted to use this connection string as the DATABASE_URL environment variable in your Django app (I know I was) but it won't work: this is the connection string to your cluster, not to any database. You actually don't have a database yet - just the cluster.

2 - Create the database and connect it to the Django app

The quickest way to create the database and automatically connect it to the Django app is by running the following command:

fly postgres attach postgres_cluster_app_name -a django_app_name

this commands does mostly 2 things:

  1. creates a postgres database (with the same name as your django app, so in this case django_app_name. The user name is also the same.)
  2. creates and populates the DATABASE_URL environment variable in your Django app

3 - Deploy your app

Now, if you run fly deploy everything should work smoothly.

Thank you for reading. Feel free to contact me if you have any questions!


Click here to share this article with your friends on X if you liked it.