Home > front end >  failed to connect with Postgres container in Django
failed to connect with Postgres container in Django

Time:01-06

django.db.utils.OperationalError: connection to server at "db" (172.18.0.2), port 5432 failed: FATAL: the database system is starting up

I have an issue connecting to the Postgres contaner. I was trying in different ways like setting passwords only in the docker-compose file. Still am stuck.

docker-compose.yml

version: '3'
services:
  db:
    image: postgres:alpine
    environment:
      - POSTGRES_PASSWORD=password
      - POSTGRES_USER=user
      - POSTGRES_DB=userdb
    volumes:
      - django_db:/var/lib/postgresql/data
    container_name: db
  
  singup: 
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    ports:
      - 8000:8000
    container_name: singup
    depends_on:
      - db 
volumes:
  django_db:

database setting

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'userdb',
        'USER': 'user',
        'PASSWORD': 'password',
        'HOST': 'db',
    }
}

CodePudding user response:

This is a timing issue, even thought you have the below line

  singup: 
    depends_on:
      - db 

It's just waiting for db container to be up and running, not neccessarily Postgres.

To avoid this, use a tool such as wait-for-it, dockerize, sh-compatible wait-for, or RelayAndContainers template. These are small wrapper scripts which you can include in your application’s image to poll a given host and port until it’s accepting TCP connections.

For example, to use wait-for-it.sh or wait-for to wrap your service’s command:

  singup: 
    depends_on:
      - db
    command: ["./wait-for-it.sh", "db:5432", "--", "python", "app.py"]

Repo of wait-for-it: https://github.com/vishnubob/wait-for-it

  •  Tags:  
  • Related