【发布时间】:2020-02-03 14:53:00
【问题描述】:
当我通过 docker-compose 运行时尝试从 docker 中的 NodeJS 应用程序连接到 docker 中的 postgres 服务器时收到 ECONNREFUSED。但是我可以从我的主机连接。这是我的 docker-compose.yml:
version: "2.4"
services:
api:
build:
context: .
target: dev
depends_on:
- postgres
ports:
- "8080:8080"
- "9229:9229"
networks:
- backend
environment:
- NODE_ENV=development
- PGHOST=postgres
- PGPASSWORD=12345678
- PGUSER=test
- PGDATABASE=test
- PGPORT=5433
volumes:
- .:/node/app
- /node/app/node_modules # Use empty volume to hide the node_modules from the host os
postgres:
image: postgres:11
restart: always
ports:
- "5433:5432"
networks:
- backend
volumes:
- db-data:/var/lib/postgresql/data
environment:
POSTGRES_PASSWORD: 12345678
POSTGRES_USER: test
POSTGRES_DB: test
networks:
backend:
volumes:
db-data:
nodeJS代码:
const client = new Client({
user: process.env.PGUSER,
host: process.env.PGHOST,
database: process.env.PGDATABASE,
password: process.env.PGPASSWORD,
port: Number(process.env.PGPORT),
});
client.connect();
错误:
{ Error: connect ECONNREFUSED 172.22.0.2:5433
api_1 | at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1106:14)
api_1 | errno: 'ECONNREFUSED',
api_1 | code: 'ECONNREFUSED',
api_1 | syscall: 'connect',
api_1 | address: '172.22.0.2',
api_1 | port: 5433 }
同时,我可以毫无问题地从主机操作系统连接到数据库服务器。网络有问题吗?
编辑:在 nodejs 应用程序尝试之前,dB 服务器已准备好接受连接(我也尝试从 nodejs 应用程序内重试连接)。
【问题讨论】:
标签: node.js postgresql docker-compose