无法在docker compose中连接到postgres

4
尝试使用Docker Compose实现Flask + PostgreSQL + Nginx的简单设置,如果我删除数据库连接逻辑,一切似乎都可以工作,但是如果不删除,它会无法解析服务名称而无法连接到数据库:
来自Flask的错误:
app_1       | {for debug, conn string used} postgresql://postgres:kftxx2h9mvOqhz3zyLIL-NG7RiUabFEzdCQCNtska-OmeASaSFk3frbKJMVqsZ@postgres:5432/postgres
app_1       | {for debug, start timestamp of first attempt to connect} 2018-03-25 18:38:48.898683
app_1       | Error: (psycopg2.OperationalError) could not translate host name "postgres" to address: Name or service not known
app_1       |  (Background on this error at: http://sqlalche.me/e/e3q8)
That last error repeats bunch of times, since I'm making multiple attempts to connect until it succeeds.
postgres_1  | 2018-03-25 18:38:38.871 UTC [1] LOG:  listening on IPv4 address "0.0.0.0", port 5432
postgres_1  | 2018-03-25 18:38:38.871 UTC [1] LOG:  listening on IPv6 address "::", port 5432
postgres_1  | 2018-03-25 18:38:38.875 UTC [1] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
postgres_1  | 2018-03-25 18:38:38.891 UTC [19] LOG:  database system was shut down at 2018-03-25 18:38:37 UTC
postgres_1  | 2018-03-25 18:38:38.896 UTC [1] LOG:  database system is ready to accept connections

请注意,问题并不是当我尝试建立连接时Postgres还没有准备好(请检查时间戳+如果失败则在Python中尝试多次建立连接,并在每个连接之间设置小的延迟)。

Compose:

version: '2'
services:

  data:
    image: postgres:latest
    volumes:
      - /var/lib/postgresql
    command: "true"

  postgres:
    restart: always
    image: postgres:latest
    env_file:
      - db_env_file
    volumes_from:
      - data
    ports:
      - "5432:5432"
    expose:
      - "5432"

  app:
    restart: always
    build: ./app
    env_file:
      - app_env_file
    networks:
      - mainnet
    depends_on:
      - "postgres"
    links:
      - postgres:postgres
    volumes:
      - ./app:/usr/src/app

  nginx:
    restart: always
    build: ./nginx
    networks:
      - mainnet
    links:
      - app
    volumes:
      - ./app/static:/usr/share/nginx/html
    ports:
      - "80:8080"

networks:
    mainnet:

db_env_file

POSTGRES_USER=postgres
POSTGRES_DB=postgres
POSTGRES_PASSWORD=kftxx2h9mvOqhz3zyLIL-NG7RiUabFEzdCQCNtska-OmeASaSFk3frbKJMVqsZ
PGDATA=/var/lib/postgresql/data/app_db_data

app_env_file

PYTHONUNBUFFERED=1 APP_DB_CONNECT_STRING=postgresql://postgres:kftxx2h9mvOqhz3zyLIL-NG7RiUabFEzdCQCNtska-OmeASaSFk3frbKJMVqsZ@app_db:5432/postgres

这是一个名为“app_env_file”的变量,其中包含两个参数:PYTHONUNBUFFERED和APP_DB_CONNECT_STRING。其中,APP_DB_CONNECT_STRING是一个PostgreSQL数据库连接字符串,用于连接应用程序与数据库。
DEBUG_ENABLE=true
APP_SECRET=5:G[m+^]`^a|>^F^t8@5r/?$}S'S$(3q"{0qZN%JH!wYlwp"~"Gcw{Wd7CP]=K&P=R6klvzcg1]"!j+EY!lYJBtR:HLlXIqg#h$Uimb8ZycZg`>(1KvdNAxV16o62sF~_$Spo1+G-c-/k"Nlv(:>d5<~=X!M2iz0kc(5xZg^*MR$S.cp^^d7osHBsz<6Xsov8-X&1]LTzscCv1G}]RUsWP@v
DB_NAME=postgres
DB_USER=postgres
DB_PASS=kftxx2h9mvOqhz3zyLIL-NG7RiUabFEzdCQCNtska-OmeASaSFk3frbKJMVqsZ
DB_SERVICE=postgres
DB_PORT=5432

连接逻辑:

 print("Connecting...", file=sys.stderr)
    print(self.db_connect_string)
    print(datetime.datetime.now())
    connected = False
    connectCount = 0
    while not connected:
        if connectCount > 0:
            sleep(1.0)

        connectCount += 1
        try:
            conn = self.engine.connect()
            conn.close()
            connected = True
        except OperationalError as e:
            if connectCount > 100:
                raise

            print("Error: " + str(e), file=sys.stderr)

尝试将连接URI更改为本地主机,同时在PostgreSQL中添加'expose: 5432',但并没有真正帮助解决问题。


你能否移除链接和网络,使得所有容器都在同一个网络中? - jrtapsell
1个回答

3

根据您的日志所述

app_1       | Error: (psycopg2.OperationalError) could not translate host name "postgres" to address: Name or service not known

我猜是因为您没有设置容器的hostname参考文档
hostname: foo

为了验证这一点,您可以在每个容器中检查 /etc/hosts。 例如:
# get the containers name
docker ps
# display /etc/hosts content
docker exec -it <your_container_name> cat /etc/hosts

此外,由于您的容器加入相同的网络,因此您不需要使用链接进行连接。请参阅Legacy container links

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接