Docker容器内Node.js无法连接PostgreSQL问题求助
解决Postgres-Express-React-Node容器化后的数据库连接拒绝问题
问题根源
出现ECONNREFUSED 127.0.0.1:5432错误有两个核心原因:
- 后端容器内的
localhost指向容器自身,而非PostgreSQL容器。Docker Compose创建的默认网络中,服务间需通过服务名通信。 - 后端启动速度快于PostgreSQL,数据库尚未完成初始化就被请求连接,导致连接失败。
解决方案
1. 修改后端数据库连接配置
将Node.js代码中的数据库host从localhost替换为Docker Compose中PostgreSQL的服务名postgres:
const { Client } = require("pg"); const client = new Client({ host: "postgres", // 替换为docker-compose里的postgres服务名 port: 5432, user: "postgres", password: "PGAdminAth", database: "postgres", }); client.connect();
2. 配置服务依赖与健康检查(可选但推荐)
在docker-compose.yml中添加健康检查和依赖条件,确保后端仅在PostgreSQL完全就绪后启动:
version: '3.8' services: postgres: image: postgres:12.1 restart: always ports: - "5432:5432" environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: PGAdminAth healthcheck: # 检查PostgreSQL是否可接受连接 test: ["CMD-SHELL", "pg_isready -U postgres"] interval: 5s timeout: 5s retries: 5 backend: build: ./backend container_name: backend_c volumes: - /app/node_modules - ./backend:/app ports: - "4000:4000" depends_on: # 等待PostgreSQL健康检查通过后再启动后端 postgres: condition: service_healthy frontend: build: ./frontend container_name: frontend_c ports: - "3000:3000" stdin_open: true tty: true
补充说明
Docker Compose默认会为所有服务创建一个共享网络,服务之间可以直接通过服务名(如postgres)进行通信,无需使用宿主机IP或localhost。
内容的提问来源于stack exchange,提问作者Atharane
相关产品推荐
相关产品推荐

