I use docker compose to run my application on a VPS server. It consists of a golang backend and PostgreSQL DB. While the backend connected to the DB completely fine on my PC, it fails to do so on the VPS. I've listed host.docker.internal in the .env file, I guess the problem be somewhere there.
Error:
2024/10/15 21:18:16 /app/config/database.go:39
[error] failed to initialize database, got error failed to connect to `user=_ database=_`: hostname resolving error: lookup host.docker.internal on 127.0.0.11:53: no such host
panic: failed to connect to `user=_ database=_`: hostname resolving error: lookup host.docker.internal on 127.0.0.11:53: no such host
goroutine 1 [running]:
politex/backend/config.Connect()
/app/config/database.go:42 +0x378
main.main()
/app/main.go:12 +0x25
docker-compose.yml:
services:
backend:
build:
context: .
dockerfile: Dockerfile
ports:
- "3000:3000"
depends_on:
- db
db:
restart: always
image: postgres:16.4
ports:
- "5432:5432"
environment:
POSTGRES_USER: _
POSTGRES_PASSWORD: _
POSTGRES_DB: _
volumes:
- pgdata:/var/lib/postgresql/data
volumes:
pgdata:
.env:
DB_HOST=host.docker.internal
DB_PASS=_
DB_PORT=5432
DB_USER=_
DB_NAME=_
database.go:
package config
import (
...
)
var Database *gorm.DB
func Connect() error {
envErr := godotenv.Load()
if envErr != nil {
panic(envErr)
}
user := os.Getenv("DB_USER")
host := os.Getenv("DB_HOST")
pass := os.Getenv("DB_PASS")
name := os.Getenv("DB_NAME")
port := os.Getenv("DB_PORT")
dsn := fmt.Sprintf("host=%v user=%v password=%v dbname=%v port=%v sslmode=disable TimeZone=Europe/Moscow", host, user, pass, name, port)
var err error
Database, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
panic(err)
}
Database.AutoMigrate(&entities.Note{})
return nil
}
Solved: I did assign the static IP to the db container and added it to .env file (and yeah, setting host to "db" didn't work for some reason)
docker-compose.yml:
services:
backend:
build:
context: backend
dockerfile: Dockerfile
ports:
- "3000:3000"
networks:
- static
depends_on:
- db
db:
restart: always
image: postgres:16.4
ports:
- "5432:5432"
environment:
POSTGRES_USER: _
POSTGRES_PASSWORD: _
POSTGRES_DB: _
networks:
static:
ipv4_address:
172.20.128.2
volumes:
- pgdata:/var/lib/postgresql/data
volumes:
pgdata:
networks:
static:
ipam:
config:
- subnet: "172.20.0.0/16"
.env:
DB_HOST=172.20.128.2
DB_PASS=_
DB_PORT=5432
DB_USER=_
DB_NAME=_