7

I think this problem should be very easy to solve, but I am pulling my hair out. I have the following docker-compose:

version: "3"
services:

  pg-db:
    image: postgres:11
    environment:
      POSTGRES_PASSWORD: "postgres"
      POSTGRES_USER: "postgres"
      POSTGRES_DB: "postgres"
    ports:
      - 5432:5432
    #network_mode: host

Then I run docker-compose up and it starts the container

pg-db_1_78e7ec4a95e6 | 2020-02-21 13:53:53.928 UTC [1] LOG:  database system is ready to accept connections

I can connect to it with docker exec

docker exec -it docker_pg-db-compose_1_78e7ec4a95e6 psql -h pg-db -U postgres postgres

But I can't manage to connect to it by 'naked' psql:

psql postgresql://postgres:postgres@localhost:5432/postgres

psql: could not connect to server: Connection refused
    Is the server running on host "localhost" (::1) and accepting
    TCP/IP connections on port 5432?

psql postgresql://postgres:postgres@pg-dg:5432/postgres
psql: could not translate host name "pg-db" to address: Name or service not known

I've tried with network_mode but it doesn't help.

2 Answers 2

11

After starting docker-compose, you need to get the docker container ip by doing this:

docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' container_name_or_id

Then you can do postgresql://postgres:postgres@<container idp>:5432/postgres you should be able to connect to it

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

2 Comments

It works with that IP. Do you happen to know if it's possible to configure a hostname instead of having to use the IP?
docker can manage host inside a container, but do not mmanage the host /etc/hosts, so no for now there is not good way to do that.
2

I'm using a modified version of the docker-compose file provided in the Postgres DockerHub page.

version: '3.1'
services:
  db:
    image: postgres:11
    restart: always
    ports:
      - 5432:5432
    environment:
      POSTGRES_PASSWORD: postgres

When I run docker-compose up I get a very similar "ready" message:

db_1  | 2020-02-21 14:34:17.826 UTC [1] LOG:  database system is ready to accept connections

At this point, I can connect to Postgres using psql.

$ psql -h localhost -U postgres
Password for user postgres: 
psql (12.2, server 11.7 (Debian 11.7-1.pgdg90+1))
Type "help" for help.

postgres=#

I'm also able to connect using the connection string that you provided, and postico:

postico 1 postico 2

The differences are subtle, I'm not sure if the restart policy makes any difference here, but give it a try.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.