How To Configure Database Connection in ACC?

This tutorial explains how to configure a database connection for your application in ACC.

Recap: The akinon.json File

Earlier, we created a basic akinon.json configuration file:

{
  "name": "Quickstart Project",
  "description": "Quickstart Project",
  "scripts": {
    "release": "",
    "build": "sh build.sh"
  },
  "env": {},
  "formation": {
    "web": {
      "min": 1,
      "max": "auto"
    }
  },
  "runtime": "python:3.8-alpine", 
  "addons": []
}

Configuring Addons

The needs of the application can be met by adding various components such as database, cache, CDN, and more into the addons field. For detailed information about addons, please refer to this link.

Below is the method to specify the addons required for the application within the akinon.json file:

{
    "...": "...",
    "addons": [
        {
            "plan": "postgresql",
            // "options": {
            //     "instance_type": "db.r5.large",
            //     "instance_count": 1
            // }
        }
    ]
}

To specify addons, simply fill out the plan area in the akinon.json file. Optional configurations can be made using the options field, as demonstrated above. For instance, users can configure the type and amount of the database instance. The available instance types are aligned with the database instance names on AWS.

After completing the configuration, the akinon.json file will resemble the following:

{
  "name": "Quickstart Project",
  "description": "Quickstart Project",
  "scripts": {
    "release": "",
    "build": "sh build.sh"
  },
  "env": {},
  "formation": {
    "web": {
      "min": 1,
      "max": "auto"
    }
  },
  "runtime": "python:3.8-alpine", 
  "addons": [
        {
            "plan": "postgresql"
        }
    ]
}

Using Environment Variables for Configuration

When a database addon is added, the following environment variables become available to your app:

  • DB_HOST

  • DB_PORT

  • DB_NAME

  • DB_USER

  • DB_PASSWORD

Update your settings.py to use these variables:

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.postgresql",
        "HOST": env("DB_HOST"),
        "USER": env("DB_USER"),
        "PASSWORD": env("DB_PASSWORD"),
        "NAME": env("DB_NAME"),
        "PORT": env("DB_PORT", cast=int),
    }
}

To run the app locally, you’ll need to simulate these environment variables:

.env

# postgres
DB_NAME=quickstart
DB_USER=postgres_user
DB_PASSWORD='postgres_password'
DB_HOST=127.0.0.1
DB_PORT=5432

To enable the application to communicate with PostgreSQL, users must incorporate the postgresql-dev library into the build.sh file.

Below is the modified version of the build.sh file:

set -euo pipefail

apk add python3-dev postgresql-dev g++ jpeg-dev zlib-dev libffi-dev --no-cache
pip install -U --force-reinstall pip
pip install -r requirements.txt

apk del g++ python3-dev

Automating of Database Migrations

To ensure database migrations run automatically during deployment, add the migration command to the release script in akinon.json:

Below is the addition to be made in the akinon.json file:

{
  //... ,
  "scripts": {
    "release": "python manage.py migrate --noinput",
    "build": "sh build.sh"
  },
  // ...
}

Ensuring the Database Connection with Health-Check

To control the database connection and ensure that the application is running smoothly, users can create a healthcheck page. This page will serve as a status indicator, providing information about the application's proper configuration and functionality.

If everything is functioning well, the server will return an HTTP 200 OK status code. Otherwise, if there's an issue, it will handle the error and respond with an appropriate error status code (e.g., 500 Internal Server Error).

Let's add a new view to the application that will respond to the /healthz path and implement the health-check functionality:

views.py

import django
from django.http import HttpResponse
from django.views import View

class HomeView(View):
    def get(self, request):
        return HttpResponse(content='Quickstart App Home Page', status=200)

class HealthCheckView(View):
    def get(self, request):
        try:
            django.db.connection.ensure_connection()
        except Exception as exc:
            return HttpResponse(content='Database connection could not be established.', status=500)

        return HttpResponse(content='OK', status=200)

urls.py

from django.contrib import admin
from django.urls import path

from quickstart.views import HealthCheckView, HomeView

urlpatterns = [
    path('', HomeView.as_view(), name='home'),
    path('admin/', admin.site.urls),
    path('healthz/', HealthCheckView.as_view(), name='healthcheck')
]

Test the healthcheck page in the local environment:

Everything seems to be running smoothly! Let's try pausing the PostgreSQL service locally:

If the application is unable to connect to the database, the health check page will notify users of the issue.

By defining the health check path in the akinon.json file, ACC can automatically and periodically verify the application's health once it's deployed.

To enable this, simply add the healthcheck key under the formation > web section, specifying the path to the health check endpoint.

{
  //... 
  
  "env": {},
  "formation": {
    "web": {
      "min": 1,
      "max": "auto",
      "healthcheck": "/healthz/"
    }
  },
  
  // ...
}

For more detailed information, refer to the tutorial here.

To test the changes in the ACC environment, push the updates to your application’s repository and trigger a new version build. Once the build is complete, proceed with the deployment.

After deployment, navigate to the health check endpoint. If everything is configured correctly, the page will confirm a successful database connection—indicating that your application is running smoothly.

Last updated

Was this helpful?