问题描述

我正在尝试连接到另一个与存储Go服务器的单独容器不同的容器中的Postgres数据库:

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)
 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

我可以从操作系统成功连接到Postgres数据库.这是Postgres容器初始化日志:

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.

推荐答案

尝试共享网络

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

这篇关于无法从golang Docker容器连接到Postgres数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!