简体   繁体   English

将 docker 服务连接到 docker 数据库容器时出现 Postgres ENOTFOUND 错误

[英]Postgres ENOTFOUND error when connecting docker services to a docker database container

I can't get one of my containers (service) to connect to the postgres database container through docker.我无法让我的容器(服务)之一通过 docker 连接到 postgres 数据库容器。 It seems to be complaining about using the wrong database...(I'm using node.js with the 'pg' and 'pg-promise' libraries.).它似乎在抱怨使用错误的数据库......(我正在使用带有“pg”和“pg-promise”库的 node.js。)。

My postgres connection info我的 postgres 连接信息

const pg = require('pg');
const pgp = require('pg-promise')();

var config = {
  user: 'root',
  password: 'myPassword',
  database: 'myDb',
  host: 'database',
  port: 5432
};
const db = pgp(config);

Error when docker attempts to connect to the database docker 尝试连接数据库时出错

{ Error: getaddrinfo ENOTFOUND database database:5432
    at errnoException (dns.js:28:10)
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:76:26)
  code: 'ENOTFOUND',
  errno: 'ENOTFOUND',
  syscall: 'getaddrinfo',
  hostname: 'database',
  host: 'database',
  port: 5432 }

I know that by default the container has the same hostname as the service name, but that didn't work (my service name is "database").我知道默认情况下,容器与服务名称具有相同的主机名,但这不起作用(我的服务名称是“数据库”)。 Anything I'm missing?我缺少什么吗?

docker-compose.yml docker-compose.yml

version: '3'

services:
  myapp:
    build: My-App/
    depends_on:
      - 'database'
    ports:
      - '5000:5000'

  database:
    image: postgres:11.5

So I eventually found the answer, so I thought I'd share:所以我最终找到了答案,所以我想我会分享:

The reason Docker couldn't automatically connect to Postgres was because Postgres was still initializing (and not receiving connection requests while it booted up). Docker 无法自动连接到 Postgres 的原因是 Postgres 仍在初始化(并且在启动时未收到连接请求)。

One solution I found was to artificially delay Docker's connection attempt (basically wait until Postgres is ready before attempting to connect).我发现的一种解决方案是人为延迟 Docker 的连接尝试(基本上等到 Postgres 准备好再尝试连接)。

EDIT: Docker-compose version 3 now has docs on how to control which containers start first: https://docs.docker.com/compose/startup-order/编辑:Docker-compose 版本 3 现在有关于如何控制哪些容器首先启动的文档: https : //docs.docker.com/compose/startup-order/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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