I am new to Docker and Golang. I am trying to run Golang server locally and connect it with my postgres docker image.Basically I want the DB to run as docker container with persitant volume
Error
PS C:\Users\usero\Desktop\Operation_GatiShakti\goBackEnd> go run .
mongodb://mongoadmin:password@localhost:27017/?tls=false
2025/08/04 22:08:16 POSTGRES_URI: postgres://myuser:mypassword@localhost:5432/mydatabase?sslmode=disable
2025/08/04 22:08:16 Failed to connect to PostgreSQL: failed to connect to `user=myuser database=mydatabase`: [::1]:5432 (localhost): failed SASL auth: FATAL: password authentication failed for user "myuser" (SQLSTATE 28P01)
exit status 1
I have created my docker-compose.yml file as -
services:
postgres:
image: postgres:latest
container_name: my-postgres
environment:
POSTGRES_DB: mydatabase
POSTGRES_USER: myuser
POSTGRES_PASSWORD: mypassword
volumes:
- postgres_data:/var/lib/postgresql/data
ports:
- "5432:5432"
restart: unless-stopped
volumes:
postgres_data:
Inside my Golang code the .env file has
POSTGRES_URI=postgres://myuser:mypassword@localhost:5432/mydatabase?sslmode=disable
The main.go file:
func main() {
var pgPool *pgxpool.Pool
//======================================
// ENVIRONMENT VARIABLE
//======================================
err := godotenv.Load(".env")
if err != nil {
log.Fatal("Error loading .env file")
}
//======================================
// MongoDB connection
//======================================
client, err := mongoFunctions.ConnectMongoDB()
if err != nil {
log.Fatalf("Failed to connect to MongoDB: %v", err)
}
defer func() {
if err = client.Disconnect(context.Background()); err != nil {
log.Fatalf("Failed to disconnect from MongoDB: %v", err)
}
}()
// Set global MongoDB collection handle
MONGO_DB_UPSC := client.Database("UPSC")
//======================================
// PostgreSQL connection
//======================================
pgPool, err = connectPostgres()
if err != nil {
log.Fatalf("Failed to connect to PostgreSQL: %v", err)
}
defer pgPool.Close()
smtpConfig := resetPassword.SMTPConfig{
Host: "smtp.hostinger.com",
Port: "587",
Username: "[email protected]",
Password: os.Getenv("SMTP_PASSWORD"),
From: "[email protected]",
}
resetService := resetPassword.NewService(pgPool, smtpConfig)
// Setup logger
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
slog.SetDefault(logger)
// Setup Gin router
router := gin.Default()
router.Use(corsMiddleware)
//-----------------------------------
// LOGIN
//-----------------------------------
router.POST("/login", ratelimit.LoginMiddleware(), func(c *gin.Context) {
authentication.LoginUser(c, pgPool)
})
router.GET("/refresh", func(c *gin.Context) {
authentication.RefreshHandler(c.Writer, c.Request)
})
router.GET("/me", func(c *gin.Context) {
userID, err := authentication.ValidateAccessToken(c.Request)
if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
return
}
c.JSON(http.StatusOK, gin.H{"id": userID})
})
//-----------------------------------
// PASSWORD RESET
//-----------------------------------
router.POST("/resetpassword", resetService.ResetPasswordHandler)
//-----------------------------------
// MONGO
//-----------------------------------
router.GET("/UPSC_History", func(c *gin.Context) {
mongoFunctions.GetAllDocument(c, MONGO_DB_UPSC, "History")
})
//---------------------------------------
// POSTGRES
//---------------------------------------
router.GET("/pg-users", func(c *gin.Context) {
registration.GetPostgresUsersHandler(c, pgPool)
})
router.POST("/pg-users", func(c *gin.Context) {
registration.CreatePostgresUserHandler(c, pgPool)
})
router.POST("/pg-users/check", func(c *gin.Context) {
registration.CheckUserExistsHandler(c, pgPool)
})
router.Run(":8080")
}
// ✅ CORS middleware
func corsMiddleware(c *gin.Context) {
origin := c.Request.Header.Get("Origin")
if origin != "" {
c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type")
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
}
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
return
}
c.Next()
}
// ✅ PostgreSQL connection
func connectPostgres() (*pgxpool.Pool, error) {
uri := os.Getenv("POSTGRES_URI")
log.Println("POSTGRES_URI:", os.Getenv("POSTGRES_URI"))
if uri == "" {
log.Fatal("POSTGRES_URI environment variable is required")
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
pool, err := pgxpool.New(ctx, uri)
if err != nil {
return nil, err
}
if err := pool.Ping(ctx); err != nil {
return nil, err
}
return pool, nil
}
I have tried removing image and volumes and restarting container, creating a new user as well. Tried Localhost, 127.0.0.1 and 0.0.0.0 as Ip.Postgres Docker image logs show it runs on 0.0.0.0
This fails even on typing correct password
psql -h localhost -p 5432 -U myuser
. But commands like - docker exec -it postgres_demo psql -U postgres work
psql(get this working before trying Go) - using yourdocker-compose.ymlthis works for me if I specify the database (e.g.psql -h localhost -d mydatabase -p 5432 -U myuser). Please add logs (docker compose logs postgres) to your question and show the full output frompsql.