简体   繁体   中英

Not able to connect to Postgres database from golang Docker container

I am trying to connect to a Postgres database in a separate container from another separate container that stores a Go server:

Pool, err = pgxpool.Connect(context.Background(),"postgres://postgres:postgres@postgres:5432/postgres")

After doing so, I receive the following error:

2020/09/25 13:40:08 failed to connect to `host=postgres user=postgres database=postgres`: hostname resolving error (lookup postgres on 192.168.65.1:53: no such host)

Here is the docker-compose.yml :

version: "3.8"
services:
  postgres:
    image: postgres:alpine
    environment:
      - POSTGRES_DB=postgres
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
    ports:
      - 5432:5432
    restart: always
  server:
    build: .
    depends_on:
      - postgres
    ports:
      - "2302:2302"
      - "80:80"
    restart: always

I am successfully able to connect to the Postgres database from my OS. Here are the Postgres container initialization logs:

postgres_1  | 
postgres_1  | PostgreSQL Database directory appears to contain a database; Skipping initialization
postgres_1  | 
postgres_1  | 2020-09-25 15:37:50.529 UTC [1] LOG:  starting PostgreSQL 13.0 on x86_64-pc-linux-musl, compiled by gcc (Alpine 9.3.0) 9.3.0, 64-bit
postgres_1  | 2020-09-25 15:37:50.529 UTC [1] LOG:  listening on IPv4 address "0.0.0.0", port 5432
postgres_1  | 2020-09-25 15:37:50.529 UTC [1] LOG:  listening on IPv6 address "::", port 5432
postgres_1  | 2020-09-25 15:37:50.532 UTC [1] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
postgres_1  | 2020-09-25 15:37:50.536 UTC [20] LOG:  database system was shut down at 2020-09-25 15:37:49 UTC
postgres_1  | 2020-09-25 15:37:50.540 UTC [1] LOG:  database system is ready to accept connections

Any clues would be helpful. Thank you in advance.

Try to share a network

version: "3.8"
services:
    postgres:
        image: postgres:alpine
        environment:
        - POSTGRES_DB=postgres
        - POSTGRES_USER=postgres
        - POSTGRES_PASSWORD=postgres
        ports:
        - 5432:5432
        restart: always
        networks: [ "go_develop" ]

    server:
        build: .
        depends_on:
        - postgres
        ports:
        - "2302:2302"
        - "80:80"
        restart: always
        networks: [ "go_develop" ]

networks:
    go_develop:
        driver: bridge

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