You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Docker环境下Node.js+Sequelize连接PostgreSQL超时求助

解决Docker中Node.js(Sequelize)无法连接PostgreSQL的问题

1. 数据库凭证变量错误

你的凭证代码中存在变量引用错误:PGDATABASE 错误指向了不存在的 process.env.PGNAME,且未给 PGPORT 设置默认值或环境变量。

修复后的凭证代码:

const credentials = {
  PGUSER: process.env.PGUSER,
  PGDATABASE: process.env.PGDATABASE, // 修正为正确的环境变量
  PGPASSWORD: process.env.PGPASSWORD,
  PGHOST: process.env.PGHOST,
  PGPORT: process.env.PGPORT || 5432, // 兜底PostgreSQL默认端口
  PGNAME: 'postgres'
}
console.log("env Users: " + process.env.PGUSER + " env Database: " + process.env.PGDATABASE + " env PGHOST: " + process.env.PGHOST + " env PORT: " + process.env.EXTERNAL_PORT)
module.exports = credentials;

2. Docker Compose 配置补全

depends_on 仅等待容器启动,不保证数据库就绪;同时缺失 PGPORT 环境变量,需添加健康检查和端口变量。

修复后的docker-compose.yml:

version: "3.8"
services:
  rapi:
    container_name: rapi
    image: rapi/latest
    build: .
    ports:
      - "3001:3001"
    environment:
      - EXTERNAL_PORT=3001
      - PGUSER=rapiuser
      - PGPASSWORD=12345
      - PGDATABASE=postgres
      - PGHOST=rapi_db
      - PGPORT=5432 # 添加容器内PostgreSQL端口变量
    depends_on:
      rapi_db:
        condition: service_healthy # 等待数据库健康检查通过
  rapi_db:
    container_name: rapi_db
    image: "postgres:12"
    ports:
      - "5432:5432"
    environment:
      - POSTGRES_USER=rapiuser
      - POSTGRES_PASSWORD=12345
      - POSTGRES_DB=postgres
    volumes:
      - rapi_data:/var/lib/postgresql/data
    healthcheck: # 添加数据库健康检查
      test: ["CMD-SHELL", "pg_isready -U rapiuser -d postgres"]
      interval: 5s
      timeout: 5s
      retries: 5
volumes:
  rapi_data: {}

3. Sequelize 配置修正

dialect 参数需直接指定为 postgres,多余的 protocol 参数可移除,同时优化重试逻辑。

修复后的Sequelize代码:

const { Sequelize } = require('sequelize');
const credentials = require('./path-to-your-credentials-file'); // 替换为实际文件路径

const db = new Sequelize(
  credentials.PGDATABASE,
  credentials.PGUSER,
  credentials.PGPASSWORD,
  {
    host: credentials.PGHOST,
    dialect: 'postgres', // 直接指定数据库方言
    port: credentials.PGPORT,
    logging: false,
    define: {
      timestamps: false
    },
    pool: {
      max: 10,
      min: 0,
      acquire: 100000,
    },
    retry: {
      match: [/Deadlock/i, Sequelize.ConnectionError],
      max: 5, // 增加重试次数提升成功率
      backoffBase: 3000,
      backoffExponent: 1.5,
    },
  }
);

// 手动添加连接测试与重试逻辑
async function testConnection() {
  try {
    await db.authenticate();
    console.log('数据库连接成功');
  } catch (error) {
    console.error('连接失败,3秒后重试...', error.message);
    setTimeout(testConnection, 3000);
  }
}

testConnection();

module.exports = db;

4. Dockerfile 端口一致性优化

Dockerfile中暴露的端口与实际服务端口不一致,建议统一:

修复后的Dockerfile:

FROM node:16

EXPOSE 3001 # 改为服务实际使用的端口

RUN npm i npm@latest -g

COPY package.json package-lock.json* ./
RUN npm install --no-optional && npm cache clean --force

WORKDIR /app # 使用/app作为工作目录,避免根目录混乱
COPY . .

CMD [ "node", "index.js" ]

内容的提问来源于stack exchange,提问作者Abhishek Agrawal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 07:40:36