Connection refused to postgres from golang service

[+] Running 2/2
:heavy_check_mark: Container db Running 0.0s
:heavy_check_mark: Container go-app Created 0.1s
WARN[0000] could not start menu, an error occurred while starting.
Attaching to db, go-app
go-app | wait-for-it.sh: waiting 15 seconds for db:5432
go-app | wait-for-it.sh: db:5432 is available after 0 seconds
go-app | loading enviroment variables…
go-app | Creating User Schema
go-app | 2025/02/02 11:05:44 dial tcp [::1]:5432: connect: connection refused
go-app | exit status 1
go-app exited with code 1

this is the log for after I run : docker compose up
and

// docker-compose.yaml

version: "3.8"

services:
  db:
    image: postgres:16
    container_name: db
    restart: always
    env_file:
      - .env
    ports:
      - "5432:5432"
    volumes:
      - pg_data:/var/lib/postgresql/data

  go-app:
    build: .
    container_name: go-app
    ports:
      - "8080:8080"
    depends_on:
      - db
    env_file:
      - .env
    command: sh -c "./scripts/wait-for-it.sh db:5432 -- go run ./scripts/seedDb.go && ./main"

volumes:
  pg_data: {}

.env

#POSTGRES SERVER
POSTGRES_HOST=localhost
POSTGRES_PORT=5432 # default portP
POSTGRES_USER=<DATABASE-USER>
POSTGRES_DB=<DATABASE-NAME>
POSTGRES_PASSWORD=<DATABASE-PASSWORD>

error log mentioning :
loading enviroment variables
creating user schema

is from seedDB.go file that connects to the postgres instance and creates different schemas and tables and add the data to the table for testing purposes

Containers are for isolation. localhost inside a container is not localhost on host.

All services are available with their service name within a (default) Docker network, try:

POSTGRES_HOST=db
1 Like

Actually, very sorry for this topic
I changed the POSTRES_HOST=db and try to fix and look around what’s the issue so I was testing on localhost at that point using host network on docker

Problem I found was very silly, I was just hard coding “localhost” instead of using POSTGRES_HOST variable in my go code so it was continuously failing how much I change in .env

so, yeah it was a silly mistake
Thank you for reaching out!