Trouble connecting my database to Django server on deployment machine

I'm deploying to AWS Linux 2023 and my postgresql database in on aws RDS. I've installed psql and checked if db is accessible in my instance. I've also checked that the environmental variables are fetching exactly as expected in my settings.py. and I even ssh and applied the migrations myself. but I keep getting the following issue:

[stderr] raise dj_exc_value.with_traceback(traceback) from exc_value
[stderr] File "/home/ec2-user/.local/share/virtualenvs/app-UPB06Em1/lib/python3.13/site-packages/django/db/backends/base/base.py", line 279, in ensure_connection
[stderr] self.connect()
[stderr] ~~~~~~~~~~~~^^
[stderr] File "/home/ec2-user/.local/share/virtualenvs/app-UPB06Em1/lib/python3.13/site-packages/django/utils/asyncio.py", line 26, in inner
[stderr] return func(*args, **kwargs)
[stderr] File "/home/ec2-user/.local/share/virtualenvs/app-UPB06Em1/lib/python3.13/site-packages/django/db/backends/base/base.py", line 256, in connect
[stderr] self.connection = self.get_new_connection(conn_params)
[stderr] ~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^
[stderr] File "/home/ec2-user/.local/share/virtualenvs/app-UPB06Em1/lib/python3.13/site-packages/django/utils/asyncio.py", line 26, in inner
[stderr] return func(*args, **kwargs)
[stderr] File "/home/ec2-user/.local/share/virtualenvs/app-UPB06Em1/lib/python3.13/site-packages/django/db/backends/postgresql/base.py", line 332, in get_new_connection
[stderr] connection = self.Database.connect(**conn_params)
[stderr] File "/home/ec2-user/.local/share/virtualenvs/app-UPB06Em1/lib64/python3.13/site-packages/psycopg2/__init__.py", line 122, in connect
[stderr] conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
[stderr]django.db.utils.OperationalError: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory
[stderr] Is the server running locally and accepting connections on that socket?
[stderr]
[stderr]2025-10-19 04:29:22,032 INFO Starting server at tcp:port=8000:interface=127.0.0.1
[stderr]2025-10-19 04:29:22,032 INFO HTTP/2 support not enabled (install the http2 and tls Twisted extras)
[stderr]2025-10-19 04:29:22,033 INFO Configuring endpoint tcp:port=8000:interface=127.0.0.1
[stderr]2025-10-19 04:29:22,033 INFO Listening on TCP address 127.0.0.1:8000

settings.py:

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

any possible ideas why this issue is happening?

Edit: I'm using daphne to run the app and codedeploy to deploy the app. also note that the migration didn't get applied when code deploy run my start_app.sh

  • python3.13
  • pipenv

my start_app.sh:

cd /home/ec2-user/app


if [ ! -f /etc/ssl/private/privkey.pem ]; then
    sudo mkdir -p /etc/ssl/private /etc/ssl/certs
    sudo openssl req -x509 -nodes -days 365 \
        -newkey rsa:2048 \
        -keyout /etc/ssl/private/privkey.pem \
        -out /etc/ssl/certs/fullchain.pem \
        -subj "/C=US/ST=State/L=City/O=MyOrg/OU=MyDept/CN=localhost"
    sudo chmod 600 /etc/ssl/private/privkey.pem
    sudo chmod 644 /etc/ssl/certs/fullchain.pem
fi

python3.13 -m pipenv install --deploy --ignore-pipfile
python3.13 -m pipenv run python manage.py migrate

pkill -f daphne || true

python3.13 -m pipenv run daphne -b 127.0.0.1 -p 8000 core.asgi:application &

DAPHNE_PID=$!

# Check if the process is still running
sleep 10
if ! kill -0 "$DAPHNE_PID" 2>/dev/null; then
    echo "Daphne failed to start — exiting."
    exit 1
fi

sudo systemctl restart nginx

The error occurs because Django is trying to connect to the local PostgreSQL socket (/var/run/postgresql/.s.PGSQL.5432), which means it's looking for the database as if it were on the same machine. This usually happens when the database host is set as localhost or the database host environment variable is missing or not properly loaded.

Check the DB_HOST value inside your Django settings during server startup. Log or print this value to verify.

Make sure your environment variables (DB_NAME, DB_USER, DB_PASSWORD, DB_HOST, DB_PORT) are exported before running Daphne/server on your deployment (e.g., inside your start_app.sh).

Example:

export DB_NAME=yourdbname

export DB_USER=yourdbuser

export DB_PASSWORD=yourdbpassword

export DB_HOST=your-rds-endpoint.amazonaws.com

export DB_PORT=5432

Confirm that your settings.py is reading these variables via os.environ.get.

After updating, redeploy. If it still fails, log/print the values to debug.

The HOST value must match the RDS endpoint, not localhost or blank.

Your Django app defaults to connecting to the local database because it doesn't find the correct database host.

Set and export your environment variables with the correct database endpoint before starting your app to fix the issue.​

The error message: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory means your application is attempting to connect to a local PostgreSQL server using a Unix domain socket, not your remote RDS instance using TCP/IP.

This happens because the HOST parameter is either missing or set to a value (localhost, None, or an empty string) that psycopg2 interprets as a local connection.


Immediate Fixes (Check These Variables)

You mentioned you checked the environment variables, but the running Daphne process (not just your shell) isn't getting them correctly.

  1. Verify DB_HOST: Ensure the environmental variable DB_HOST is set exactly to your AWS RDS endpoint (e.g., my-rds-instance.xyz.us-west-2.rds.amazonaws.com).

  2. Verify DB_PORT: Ensure DB_PORT is set to the correct TCP port, usually 5432.

Why Your SSH Migration Worked

When you SSH'd and ran the migration, your shell environment likely had the correct variables loaded, so the connection worked. The issue is in how CodeDeploy/Daphne is loading the variables into the deployed application process.


Secondary Issue (For migrate Failure)

If the connection details are definitely correct and you're still having issues applying migrations via the script, check your Security Groups:

  • The RDS Security Group must explicitly allow inbound traffic on port 5432 from the EC2 instance's Security Group.

The error means your Django app is trying to connect to PostgreSQL via a local UNIX socket instead of your AWS RDS instance. Specifically, this part of the traceback shows it:

connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed:
No such file or directory

That happens when Django thinks the database is local because either:

  1. DB_HOST is empty or incorrect, or
  2. The environment variables are not loaded correctly when daphne starts.

To fix it

  1. Check the actual values Django gets Run this inside your instance:

    python3.13 manage.py shell
    

    Then:

    from django.conf import settings
    print(settings.DATABASES)
    

    Ensure "HOST" shows your RDS endpoint (like mydb.xxxxxx.us-east-1.rds.amazonaws.com), not empty or "localhost".


  1. Fix environment loading in CodeDeploy

    In your start_app.sh, migrations and Daphne may not see environment variables if you only export them in another context.

    Make sure you export them in the script or load them from an .env file:

    export DB_NAME=mydb
    export DB_USER=myuser
    export DB_PASSWORD=mypassword
    export DB_HOST=mydb.xxxxxx.us-east-1.rds.amazonaws.com
    export DB_PORT=5432
    

    Or use:

    source /home/ec2-user/app/.env
    

    Then start Django.


  1. Test direct connection

    psql -h $DB_HOST -U $DB_USER -d $DB_NAME
    

    If this works but Django still fails, the problem is environment visibility.


  1. Don’t use 127.0.0.1 in Daphne (-b 127.0.0.1) unless nginx is reverse proxying to it. It doesn’t affect the DB issue but can hide errors when debugging.

Вернуться на верх