#unable to establish connection with docker postgresql container

17 messages · Page 1 of 1 (latest)

true furnace
#

hi, im facing this issue since couple of days.
this is my config.go file

package config

import (
    "fmt"
    "log"
    "os"

    "github.com/jinzhu/gorm"
    _ "github.com/lib/pq"
)

var DB *gorm.DB

func InitDB() {
    var err error
    dsn := fmt.Sprintf("host=%s port=%s user=%s dbname=%s sslmode=disable password=%s",
        os.Getenv("DB_HOST"), os.Getenv("DB_PORT"), os.Getenv("DB_USER"), os.Getenv("DB_NAME"), os.Getenv("DB_PASSWORD"))

    DB, err = gorm.Open("postgres", dsn)
    if err != nil {
        log.Fatalf("Could not connect to the database: %v", err)
    } else {
        log.Fatalf("[+] access granted")
    }
}

this is my docker-compose.yml file

version: '3.8'

services:
  db:
    image: postgres:13
    container_name: xyz_game_db
    environment:
      POSTGRES_DB: xyz_game
      POSTGRES_USER: admin
      POSTGRES_PASSWORD: b0ss
    ports:
      - "5432:5432"
    volumes:
      - db_data:/var/lib/postgresql/data

volumes:
  db_data:

this is my .env file

DB_HOST=localhost
DB_PORT=5432
DB_USER=admin
DB_NAME=xyz_game
DB_PASSWORD=b0ss
PORT=8080

and this is the error o/p while trying to connect to psql container with validd credentials

PS C:\Projects\xxxxxxx> go run .\main.go
2024/06/15 19:59:10 Could not connect to the database: pq: password authentication failed for user "admin"
`exit status 1```
somber tusk
#

is xyz vs sailors just a change for the post here?

#

if so, could you run netstat -ano | find 5432 in cmd (not sure what find is in powershell) and find what process that pid belongs to? just to double-check that you're not accidentally shadowing ports, since docker will silently fail on that

true furnace
somber tusk
#

ok, what are both pid 5984 and 6840

#

check task manager or tasklist

true furnace
somber tusk
#

ok, so you have postgres running on your windows host

#

that’s what you’re connecting to, not the one in docker

true furnace
#

how to proceed further

somber tusk
#

remove postgres on your windows host, or choose a different port

true furnace
#

please guide me on where to change the port in yml file,
whether left:right ? also is this single change sufficient ?

somber tusk
#

it’s the left one; that specifies the port on the host

#

you still want the port inside the container to be 5432

#

that will be sufficient once you also change it in your environment for your go program, yes

true furnace
#

sure, lemme give it a shot

orchid dawn
#

As long as your application is using postgres directly in the container you can change ports binding without changing anything else