0

I have 2 projects. The first contains this docker-compose.yml:

# pg/docker-compose.yml
version: "3"
services:
  postgres:
    image: postgres
    environment:
      POSTGRES_USER: pguser
      POSTGRES_DB: pg
    ports:
      - "5432:5432"
    volumes:
      - "postgres-data:/var/lib/postgresql/data"
    networks:
      - some_net

volumes:
  postgres-data:

networks:
  some_net:
    driver: bridge

The second project has this docker compose file:

# pg_client/docker-compose.yml
version: "3"
services:
  postgres_client:
    image: tmaier/postgresql-client
    command: postgres://pguser@localhost:5432/pg
    networks:
      - pg_some_net

networks:
  pg_some_net:
    external: true

The tmaier/postgresql-client image is extremely simple, it has PostgresSQL installed and runs the command psql DOCKER_COMMAND at build time. In my case this is psql postgres://pguser@localhost:5432/pg.

I can connect to my Postgres db just fine from the command line:

$ psql postgres://pgmuser@localhost:5432/pg
psql (12.1)
Type "help" for help.

pg=#

But when the postgres_client container attempts to connect (after running docker-compose up), it fails saying

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

Is there something special about docker-compose that I need to account for when writing my Postgres connection URI?

Any help is much appreciated.

bpgeck
  • 1,592
  • 1
  • 14
  • 32
  • See https://stackoverflow.com/questions/34393779/connect-two-instances-of-docker-compose. Might help you. Each docker compose sets up an isolated network. – Ashhar Hasan Jan 09 '20 at 18:14
  • @AshharHasan Ahhh thank you for finding that. Sounds like I need to ensure both docker-compose files lie in the same network – bpgeck Jan 09 '20 at 18:19
  • @AshharHasan Unfortunately, it looks like adding the containers to the same network does not resolve this issue. – bpgeck Jan 09 '20 at 18:45

1 Answers1

4

The hostname of postgres should resolve to postgres instead of localhost. You can try

command: postgres://pguser@postgres:5432/pg
  • 1
    Woked! Under the hood it looks like docker assigns a separate IP address (not localhost), so when it's in the same network I need to reference the name of the container rather than `localhost` – bpgeck Jan 09 '20 at 18:55
  • 3
    @bpgeck That's a docker compose thing. It sets up hostnames. Does not work with plain standalone containers unles you pass --link. – Ashhar Hasan Jan 10 '20 at 10:56