0

I have the below docker-compose.yaml:

version: "3.9"

services:
  server:
    depends_on:
      - db
    build:
      context: .
    container_name: grpc-server
    hostname: grpc-server
    networks:
      - mynet
    ports:
      - 8080:8080
    deploy:
      restart_policy:
        condition: on-failure

  db:
    image: postgres
    container_name: postgres-db
    hostname: postgres
    networks:
      - mynet
    volumes:
      - ./data/db:/var/lib/postgresql/data
    environment:
      - POSTGRES_DB=postgres
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
    ports:
      - 5432:5432

networks:
  mynet:
    driver: bridge

However my server container logs are indicating it can't connect to the db.

[error] failed to initialize database, got error dial tcp 127.0.0.1:5432: connect: connection refused

I'm assuming I need to inject the db path into the server somehow via the mynet?

1 Answer 1

2

It looks like your grpc-server container tries to connect to the database using the address 127.0.0.1:5432.

By default, docker compose creates a virtual network where each container is addressed using it's service name. However, you've overridden that by specifying hostname: postgres for your database container.

So your grpc-server needs to connect to the database using the address postgres:5432 rather than 127.0.0.1:5432.

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

1 Comment

Awesome! I just wasn't sure of the convention. So I would set an environment var for the server using postgres:5432 then from the code read it in instead.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.