1

How can I connect to my postgresql instance when I am running it via docker.

In my docker-compose I have the image defined as follows:

db:
    image: postgres:9.4
    #container_name: db
    volumes:
      - "/home/data/pgdata:/var/lib/postgresql/data"
    restart: always

I installed the client only:

sudo apt-get install -y postgresql-client

I installed the psql client on ubuntu, and I try to connect to it but can't seem to connect successfuly.

psql -h db -p 5432 -U postgres

psql: could not translate host name "db" to address: Temporary failure in name resolution

I tried different hosts like localhost, 127.0.0.1 and docker_db_1 and they all didn't work.

Community
  • 1
  • 1
Blankman
  • 259,732
  • 324
  • 769
  • 1,199
  • Try adding `link`? https://stackoverflow.com/questions/55081675/django-docker-could-not-translate-host-name-db-to-address-nodename-nor-serv – richyen Dec 19 '19 at 18:38

2 Answers2

1

You did not publish any port so you will not able to connect from the host. You need to publish port to connect container from your Host machine.

db:
  image: postgres:9.4
  container_name: db
  ports:
    - "5432:5432"

Also, you should use localhost if you try to connect from Host, DB is only reachable within docker-compose network

psql -h 127.0.0.1 -p 5432 -U postgres

or you can also verify inside the container

db:
    image: postgres
    container_name: db
    ports:
      - "5432:5432"

to check connection with installing client on host

docker exec -it db bash -c "psql -U postgres"
Adiii
  • 54,482
  • 7
  • 145
  • 148
0

It seems that the OS cannot translate the host name db into an IP address. You may need to add hostname: db into your docker-compose.yml file

richyen
  • 8,114
  • 4
  • 13
  • 28