Search code examples
pythondjangopostgresqldockerubuntu

Can't connect to local postgresql server from my docker container


I'm trying to connect to local postgresql server from my docker container. I'm using Ubuntu 22.04.4.

This is my docker-compose.yml.

version: '3'

services:
    ...
    backend:
        build:
            context: '.'
            dockerfile: 'Dockerfile'
        ports:
            - '8000:80'
            - '8001:8001'
        env_file:
            - .env-docker
        image: backend-django:latest
    ...

This is my .env-docker.

DEBUG=True
SECRET_KEY=******
DATABASE_USER=postgres
DATABASE_NAME=postgres
DATABASE_PASSWORD=postgres
DATABASE_HOST=host.docker.internal
DATABASE_PORT=5432

This is my Dockerfile.

FROM python:3.11
ENV PYTHONBUFFERED 1

...

EXPOSE 8000
CMD ["gunicorn", "-b", "0.0.0.0", "config.wsgi"]

It was working in Windows but not in Ubuntu now.

Is it related to postgresql? I'm using the same version of postgresql and I can connect to local postgresl using PgAdmin.

How can I connect to postgresql server from my docker container?

(I added this to my docker container in docker-compose.yml (from this post - From inside of a Docker container, how do I connect to the localhost of the machine?) but still not working.

extra_hosts:
    - "host.docker.internal:host-gateway"

)


Solution

  • Add this to your container in docker-compose.yml.

    extra_hosts:
        - "host.docker.internal:host-gateway"
    

    If you keep getting errors, change listen_addresses in postgresql.conf

    listen_addresses = '*'
    

    And add these lines to your pg_hba.conf

    host    all all 0.0.0.0/0   scram-sha-256
    host    all all ::/0    scram-sha-256
    

    After this, restart the postgresql service.

    sudo systemctl restart postgresql