panic: dial tcp 192.168.0.2:5432: connect: connection refused
package database
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
"WebApp/config"
)
func Connect() (*sql.DB, error) {
psqlInfo := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=disable",
config.DB_HOST, config.DB_PORT, config.DB_USER, config.DB_PASSWORD, config.DB_NAME)
db, err := sql.Open("postgres", psqlInfo)
if err != nil {
panic(err)
}
defer db.Close()
err = db.Ping()
if err != nil {
panic(err)
}
fmt.Printf("\nSuccessfully connected to database!\n")
return db, nil
}
version: '3'
services:
backend:
build:
context: ../RestAPI-Golang
dockerfile: Dockerfile.dev
environment:
- DB_USER=username
- DB_PASSWORD=password
- DB_NAME=default_database
- DB_PORT=5432
- DB_HOST=database
ports:
- "3000:3000"
volumes:
- ../RestAPI-Golang:/app
depends_on:
- database
database:
image: postgres
restart: always
volumes:
- ./db-data/:/var/lib/postgresql/data/
environment:
- POSTGRES_USER=username
- POSTGRES_PASSWORD=password
- POSTGRES_DB=default_database
ports:
- "5432:5432"
db-admin:
image: adminer
ports:
- 8080:8080
I've tried using local host instead of the database container name, using the container ip, and other options online but I have had no luck. I believe the docker container name resolves to the ip of the container? And since it's communication within the same docker network I do not need to expose any additional ports?