Blankman
Blankman

Reputation: 267000

Connecting to postgres instance that is running via docker on my ubuntu server

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.

Upvotes: 1

Views: 264

Answers (2)

richyen
richyen

Reputation: 9968

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

Upvotes: 0

Adiii
Adiii

Reputation: 59946

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"

Upvotes: 1

Related Questions