NodeJS 在sequelize连接中,我收到操作超时错误,如何解决这个问题?

iyfjxgzm  于 2022-12-18  发布在  Node.js
关注(0)|答案(1)|浏览(349)

我尝试在Docker内部运行 NodeJS 服务器& Postgres &使用sequalize进行数据库连接。但是,似乎我的 NodeJS 服务器无法与Docker内部的Postgres数据库通信。
在别人把它标记为重复之前,请注意我已经检查了其他的答案&没有一个适合我。我已经尝试过为序列化连接执行重试策略。
这是我的docker-compose文件:

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 # NAME OF THE SERVICE
    depends_on:
      - rapi_db
  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
volumes:
  rapi_data: {}

下面是我的Dockerfile:

FROM node:16

EXPOSE 3000

# Use latest version of npm
RUN npm i npm@latest -g

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

# copy in our source code last, as it changes the most
WORKDIR /
COPY . .

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

我的数据库凭据:

credentials = {
        PGUSER :process.env.PGUSER,
         PGDATABASE :process.env.PGNAME,
         PGPASSWORD : process.env.PGPASSWORD,
         PGHOST : process.env.PGHOST,
         PGPORT:process.env.PGPORT,
         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)
}
//else credentials = {}
module.exports = credentials;


序列化DB代码:

const db =  new Sequelize(credentials.PGDATABASE,credentials.PGUSER,credentials.PGPASSWORD, {
  host: credentials.PGHOST,
  dialect: credentials.PGNAME,
  port:credentials.PGPORT,
  protocol: credentials.PGNAME,
  dialectOptions: {
  },
  logging: false,
  define: {
    timestamps: false
  }
  ,
   pool: {
      max: 10,
      min: 0,
      acquire: 100000,
   },
   retry: {
    match: [/Deadlock/i, Sequelize.ConnectionError], // Retry on connection errors
    max: 3, // Maximum retry 3 times
    backoffBase: 3000, // Initial backoff duration in ms. Default: 100,
    backoffExponent: 1.5, // Exponent to increase backoff each try. Default: 1.1
  },
});
  module.exports = db;
h7wcgrx3

h7wcgrx31#

您的进程.env.PGPORT不存在。请在docker-compose中为服务rapi添加一个环境变量,或在凭据文件中将其设置为5432。

相关问题