Search code examples
postgresqlgogo-gorm

gorm: dial tcp 127.0.0.1:5432: connect: connection refused


I am trying to connect to my database created by the following docker configs using gorm:

services:
  app:
    build: 
      context: .
      # Correct the path to your Dockerfile
      dockerfile: Dockerfile
    ports:
      - "127.0.0.1:8080:8080"
    volumes:
      - .:/app
    networks:
      - backend
    depends_on:
      - db
  
  db:
    container_name: simple_api_db_user
    restart: always
    image: postgres:latest
    environment:
      POSTGRES_USER: mateen
      POSTGRES_PASSWORD: password
      POSTGRES_DB: simple_api_db_user
    volumes:
      - db_data:/var/lib/postgresql/data
    networks:
      - backend
    ports:
      - "127.0.0.1:5430:5430"
  
volumes:
  db_data:

networks:
  backend:
    driver: bridge

here is the code to my postgres connection in golang:

func NewPostgresConnection() (*gorm.DB, error) {
    psqlConfig, err := dbConfigs.NewPostgresqlConfig()
    if err != nil {
        return nil, err
    }

    db, err := sql.Open("postgres", psqlConfig.Dsn())
    if err != nil {
        log.Println("DB Connection error : ", err.Error())
        return nil, err
    }

    if err := db.Ping(); err != nil {
        log.Println("DB Ping error: ", err.Error())
        return nil, err
    }

    gdb, err := gorm.Open(postgres.Open(psqlConfig.Dsn()), &gorm.Config{})
    if err != nil {
        return nil, err
    }

    err = Migrate(gdb)
    if err != nil {
        return nil, err
    }

    return gdb, nil
}

and here is my config DSN when I print it out: &{host=simple_api_db_user user=mateen password=password dbname=simple_api_db_user port=5430 sslmode=disable TimeZone=UTC}

I am getting the following error when running my app:

simple-api-user-app-1  | 2023/05/10 14:05:16 DB Ping error:  dial tcp 172.31.0.2:5430: connect: connection refused
simple-api-user-app-1  | 2023/05/10 14:05:16 dial tcp 172.31.0.2:5430: connect: connection refused

Here is my Dockerfile even though I think it might be irrelevant:

# Builder
FROM golang:latest

WORKDIR /app

COPY go.mod go.sum ./

RUN go mod download

RUN go install github.com/cosmtrek/air@latest

COPY . .

CMD [ "air" ]

EXPOSE 8080

PS: When I try to connect to postgres port to 5430 in dbeaver, I get the following error:

The connection attempt failed.
  EOFException
  java.io.EOFException

Edit: the changed


Solution

  • the postgres container is listening on 5432. so the ports options should be set to 5430:5432. this maps port 5430 on your host machine to 5432 on the docker container.