What happened

  1. Postgres container is initializing the data directory (initdb).
  2. During init, Postgres does an internal create-db flow and restarts once.
  3. Your migrate container tried to connect during that restart window → connection refused:
migrate-1 | dial tcp ...:5432: connect: connection refused

Also this line is normal during init (it happens before the DB is created):

FATAL: database "postgres_go" does not exist
CREATE DATABASE

So the fix is: make migrate retry, because this failure is transient.

1) Change migrate to restart on failure

Right now you have restart: "no" which means: fail once → stack fails.

Change it to:

migrate:
  image: migrate/migrate:v4.17.1
  depends_on:
    postgres:
      condition: service_healthy
  volumes:
    - ./apps/api-go/migrations:/migrations
  command: [
"-path","/migrations",
"-database","postgres://postgres:postgres@postgres:5432/postgres_go?sslmode=disable",
"up"
  ]
  restart: on-failure

This way if it hits the “Postgres is restarting” window, it will automatically retry and succeed.

2) Make Postgres healthcheck more “stable” (optional but recommended)

Add start_period so health checks don’t flip-flop during init:

healthcheck:
  test: ["CMD-SHELL","pg_isready -U postgres -d postgres_go"]
  interval: 5s
  timeout: 3s
  retries: 30
  start_period: 10s

This reduces early “healthy” signals while Postgres is still settling.

3) Then rerun cleanly

Because your volumes are fresh and migrate failed:

docker compose down-v
docker compose up--build