# How To Configure Database Connection in ACC?

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

## <mark style="color:red;">Recap: The</mark> <mark style="color:red;"></mark><mark style="color:red;">`akinon.json`</mark> <mark style="color:red;"></mark><mark style="color:red;">File</mark>

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": []
}
```

## <mark style="color:red;">Configuring Addons</mark> <a href="#configuring-addons" id="configuring-addons"></a>

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](https://docs.akinon.com/tutorials/how-to-configure-your-acc-application-with-akinon.json-and-procfile#healthcheck).

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
            // }
        }
    ]
}
```

{% hint style="info" %}
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](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Concepts.DBInstanceClass.html).
{% endhint %}

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"
        }
    ]
}
```

## <mark style="color:red;">Using Environment Variables for Configuration</mark> <a href="#using-environment-variables-for-configuration" id="using-environment-variables-for-configuration"></a>

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
```

## <mark style="color:red;">Automating of Database Migrations</mark> <a href="#automating-of-database-migrations" id="automating-of-database-migrations"></a>

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"
  },
  // ...
}
```

## <mark style="color:red;">Ensuring the Database Connection with Health-Check</mark> <a href="#ensuring-the-database-connection-with-health-check" id="ensuring-the-database-connection-with-health-check"></a>

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:

<figure><img src="https://3333414532-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbwGN7KwvYi0iLbjtnXz%2Fuploads%2F60lT7oBKewBjgydyIu7Y%2Fimage.png?alt=media&#x26;token=b84491cd-5909-4815-b4f4-2aa280649883" alt=""><figcaption></figcaption></figure>

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

<figure><img src="https://3333414532-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbwGN7KwvYi0iLbjtnXz%2Fuploads%2F7PpQPliXOE2X1KKTMfuk%2Fimage.png?alt=media&#x26;token=e61af3aa-b822-4d10-b470-b03818126957" alt=""><figcaption></figcaption></figure>

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/"
    }
  },
  
  // ...
}
```

{% hint style="info" %}
For more detailed information, refer to the tutorial [here](https://docs.akinon.com/tutorials/how-to-configure-your-acc-application-with-akinon.json-and-procfile#healthcheck).
{% endhint %}

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.

<figure><img src="https://3333414532-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbwGN7KwvYi0iLbjtnXz%2Fuploads%2F93FDg7VcJVKRt95n5LAt%2Fimage.png?alt=media&#x26;token=54d8a756-8896-42df-ba4a-d515d6993e56" alt=""><figcaption></figcaption></figure>
