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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

I need to connect from the host machine. From the container it connects no problem
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...
Running on linux. Not using docker-machine. It's super confusing since other apps can connect
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..
-3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.