简体   繁体   中英

Django cannot connect to postgresql docker container

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM