I have one problem with docker
func ConnectToDB() {
var err error
dsn := "host=localhost user=postgres password=postgres dbname=yandex port=5432 sslmode=disable"
DB, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatal("failed to connect with database")
}
}
that’s my function that connect’s to db
and that’s my docker-compose file
version: "3.8"
services:
server:
container_name: server
build:
context: .
restart: unless-stopped
depends_on:
postgres:
condition: service_healthy
ports:
- "8080:8080"
volumes:
- type: bind
source: ./static
target: /app/static
environment:
POSTGRES_PASSWORD: "postgres"
postgres:
container_name: storage
image: postgres:16.2
restart: unless-stopped
environment:
POSTGRES_PASSWORD: postgres
POSTGRES_USER: postgres
POSTGRES_DB: yandex
healthcheck:
test: [ "CMD-SHELL", "pg_isready -U postgres" ]
interval: 10s
timeout: 5s
retries: 5
ports:
- "5432:5432"
volumes:
- type: bind
source: ./init.sql
target: /docker-entrypoint-initdb.d/init.sql
So after commands
docker-compose build
docker-compose up
that gives me an error
server | [error] failed to initialize database, got error failed to connect to host=localhost user=postgres database=yandex
: dial error (dial tcp [::1]:5432: connect: cannot assign requested address)
server | 2024/05/02 20:17:58 failed to connect with database
can you tell what am I doing wrong?
I tried to change localhost in function
like thist
func ConnectToDB() {
var err error
dsn := "host=postgres user=postgres password=postgres dbname=yandex port=5432 sslmode=disable"
DB, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatal("failed to connect with database")
}
}
and that worked
but why?
Ansar Rakhimov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.