Home > Mobile >  How to connect to a postgres database in a docker container?
How to connect to a postgres database in a docker container?

Time:11-11

I setup my django and postgres container on my local machine and all working fine. Local server is running, database running but I am not being able to connect to the created postgres db.

docker-compose.yml

version: '3'

services:
  web:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/app
    ports:
      - "8000:8000"
    depends_on:
      - db

  db:
    image: postgres:13.0-alpine
    volumes:
      - postgres_data:/var/lib/postgresql/data/
    environment:
      - POSTGRES_USER=my_user
      - POSTGRES_PASSWORD=my_password
      - POSTGRES_DB=my_db

volumes:
  postgres_data:

I tried this command: docker exec -it container_id psql -U postgres error: psql: error: could not connect to server: FATAL: role "postgres" does not exist

I am very new to Docker.

CodePudding user response:

You're not using the username and the password you provided in your docker-compose file. Try this and then enter my_password:

docker exec -it container_id psql -U my_user -d my_db --password

Check the official documentation to find out about the PostgreSQL terminal.

CodePudding user response:

I would also like to add, in your compose file you're not exposing any ports for the db container. So it will be unreachable via external sources (you, your app or anything that isn't ran within that container).

  • Related