简体   繁体   中英

Getting an error while connecting to postgres running in Docker: pq: password authentication failed for user “postgres”

Trying to open Database but it is saying password authentication failed for user "postgres" I am not able to find the root cause of this problem.First time,i am using Docker. Pleas help

func openDB() (*sqlx.DB, error) {
    q := url.Values{}
    q.Set("sslmode", "disable")
    q.Set("timezone", "utc")

    u := url.URL{
        Scheme:   "postgres",
        User:     url.UserPassword("postgres", "postgres"),
        Host:     "localhost",
        Path:     "postgres",
        RawQuery: q.Encode(),
    }
    fmt.Println(u.String())
    
    // fmt.Println(u.String()) is
    // postgre://postgres:postgres@localhost/postgres?sslmode=disable&timezone=utc
    return sqlx.Open("postgres", u.String())
}

docker-compose.yaml looks like this.

version: '3'
networks:
  shared-network:
    driver: bridge
services:
  db:
    container_name: sales_db
    networks:
      - shared-network
    image: postgres:11.1-alpine
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: postgres
    ports:
      - 5432:5432

There was no problem in code. I changed the port eveything is working now.

func openDB() (*sqlx.DB, error) {
    q := url.Values{}
    q.Set("sslmode", "disable")
    q.Set("timezone", "utc")

    u := url.URL{
        Scheme:   "postgres",
        User:     url.UserPassword("postgres", "postgres"),
        Host:     "localhost:5433", // change here
        Path:     "postgres",
        RawQuery: q.Encode(),
    }
    fmt.Println(u.String())
    
    // fmt.Println(u.String()) is
    // postgre://postgres:postgres@localhost/postgres?sslmode=disable&timezone=utc
    return sqlx.Open("postgres", u.String())
}

and

version: '3'
networks:
  shared-network:
    driver: bridge
services:
  db:
    container_name: sales_db
    networks:
      - shared-network
    image: postgres:11.1-alpine
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: postgres
    ports:
      - 5433:5432 //change here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM