1

I have a postgres db running in a docker container:

my docker-compose:

version: "3"
services:
  db:
    image: postgres:13.1-alpine
    environment:
      - POSTGRES_DB=mydb
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=test
    ports:
      - "5432:5432"
    volumes:
      - ./postgres_data:/var/lib/postgresql/data/

Django running on the host machine (ubuntu linux, not in the docker container) cannot connect to it.

django's settings.py:

    DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'HOST' : "localhost",
        'NAME' : "mydb",
        'USER' : "postgres",
        'PASSWORD' : "test",
        'PORT':5432,
    }
}

Exception:

django.db.utils.OperationalError: could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"

Database is certainly avaliable on port 5432(I can connect to it with dbeaver database client on localhost:5432).

What could be the cause of the problem?

Hello
  • 57
  • 1
  • 6

2 Answers2

1

Access it as HOST=db in stead of localhost assuming that the django is also contained in the docker-compose.yml

This is because in your docker-compose the database "service" name is db and therefore its "DNS" name will be db within the docker-compose created network.

Ivonet
  • 2,492
  • 2
  • 15
  • 28
  • 1
    I need to connect from the host machine. From the container it connects no problem – Hello May 21 '21 at 13:41
  • Then the question is of you are running from mac/linux or windows? if you are using docker-machine the IP address can be found with `docker-machine ip default` otherwise I would expect localhost to be working... – Ivonet May 21 '21 at 13:44
  • Running on linux. Not using docker-machine. It's super confusing since other apps can connect – Hello May 21 '21 at 13:48
  • does this one help? https://stackoverflow.com/questions/29937378/django-db-utils-operationalerror-could-not-connect-to-server – Ivonet May 21 '21 at 13:51
  • Nope, didn't help. My uneducated guess is psycopg2 somehow hardcoded to look for postgres server running directly on the host, not in the container connected to a port.. – Hello May 21 '21 at 14:10
-2

figured it out, just had an error in settings.py connection values

Hello
  • 57
  • 1
  • 6