Skip to main content

Django database connection error — step-by-step fix

TL;DR

How to diagnose and resolve Django OperationalError database connection failures in production.

Key facts

Topic
Production error triage
Stack
Django / PostgreSQL / Linux

TL;DR

Django's OperationalError: could not connect to server or connection refused means the application cannot reach its database. This typically causes every request to return a 500 error, making it one of the most impactful failures in a Django stack.

Common causes

  • PostgreSQL or MySQL service is stopped or crashed
  • Database credentials changed but the application .env was not updated
  • Connection pool exhaustion — all connections are in use and new requests cannot obtain one
  • Network issue — firewall rule change, security group update, or DNS failure
  • pg_hba.conf (PostgreSQL) or bind-address (MySQL) rejecting the connection source

Diagnosis workflow

Test database connectivity from the application server:

psql -h db-host -U myuser -d mydb -c "SELECT 1;"

Check if the database service is running:

systemctl status postgresql

Verify Django can connect:

cd /var/www/myapp && source venv/bin/activate
python manage.py dbshell

Check connection count on the database:

SELECT count(*) FROM pg_stat_activity;
SHOW max_connections;

Fixes

If the database service is down:

sudo systemctl start postgresql
sudo systemctl enable postgresql

If connections are exhausted, configure connection pooling in Django:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'mydb',
        'CONN_MAX_AGE': 600,
        'CONN_HEALTH_CHECKS': True,
    }
}

For high-traffic applications, add PgBouncer as a connection pooler between Django and PostgreSQL:

[databases]
mydb = host=127.0.0.1 port=5432 dbname=mydb

[pgbouncer]
pool_mode = transaction
max_client_conn = 200
default_pool_size = 25

Where Reflex helps

Reflex monitors database connectivity from your application layer. When a connection failure occurs, it checks the database service state, restarts it if needed, verifies connection recovery, and correlates the outage with recent infrastructure changes for root-cause analysis. See How it works.