4

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.

2
  • You set the username and password to my_user/my_password in the configuration; do those credentials work? Commented Nov 11, 2022 at 11:26
  • i suppose it works because postgres database is successfully created with those configurations, but i want to connect to this database and not being able to connect ? @DavidMaze Commented Nov 11, 2022 at 11:38

4 Answers 4

7

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.

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

2 Comments

got this error: OCI runtime exec failed: exec failed: unable to start container process: exec: "export PGPASSWORD=my_password; psql -U my_user -d my_db": executable file not found in $PATH: unknown
Assuming your container is up and running, try docker exec -it container_id psql -U my_user -d my_db --password and then enter my_password. Should work fine! And note that it is more convenient to replace container_id by $(docker ps | awk '/postgres/ {print $1}').
1

I think you need to add environment to project container.

   environment:
      - DB_HOST=db
      - DB_NAME=my_db
      - DB_USER=youruser
      - DB_PASS=yourpass
   depends_on:
      - db

add this before depends_on

And now see if it solves

Comments

0

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).

Comments

0

You should add ports to the docker-compose for the postgres image,as this would allow postgres to be accessible outside the container

- ports: 
   "5432:5432"

You can checkout more here docker-compose for postgres

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.