gpt4 book ai didi

node.js - Docker Node App Postgres错误 “Connection terminated unexpectedly”

转载 作者:行者123 更新时间:2023-12-02 19:51:40 24 4
gpt4 key购买 nike

我正在尝试对Node API进行Docker化,并且仅在Dockerized应用中出现错误。在Docker之外,node server.js可以正常工作,没有任何问题。使用docker-compose up,无论有无API调用,我在10分钟后都会收到以下错误消息:

api    | [nodemon] starting `node server.js`
api | listening on port 3000
api | API is ready
api | Error: Connection terminated unexpectedly
api | at Connection.<anonymous> (/api/node_modules/pg/lib/client.js:255:9)
api | at Object.onceWrapper (events.js:427:28)
api | at Connection.emit (events.js:321:20)
api | at Connection.EventEmitter.emit (domain.js:485:12)
api | at Socket.<anonymous> (/api/node_modules/pg/lib/connection.js:139:10)
api | at Socket.emit (events.js:333:22)
api | at Socket.EventEmitter.emit (domain.js:485:12)
api | at endReadableNT (_stream_readable.js:1201:12)
api | at processTicksAndRejections (internal/process/task_queues.js:84:21)
api | [nodemon] app crashed - waiting for file changes before starting...

Docker文件
FROM node
WORKDIR /api
ADD . /api
RUN npm install
RUN npm install -g nodemon
EXPOSE 3000

docker-compose.yml
version: "3.7"
services:
api:
container_name: api
build: .
volumes:
- .:/api
ports:
- "3000:3000"
restart: unless-stopped
working_dir: /api
command: nodemon server.js

server.js
...
try {
let pgDbConfig;
pgDbConfig = {
host: '<host>',
user: '<dbuser>',
password: '<dbpass>',
port: 5432,
database: '<dbname>',
max: 20,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 2000
};

pgPool = new Pool(pgDbConfig);

// the pool will emit an error on behalf of any idle clients it contains if a backend error or network partition happens
pgPool.on('error', (err, client) => {
console.error('Unexpected error on idle pg client', err, client);
});

// trying to use error listener after the connect
pgPool.on('connect', () => {
pgPool.on('error', err => console.log(err));
});

console.log('API is ready');

} catch(exception) {
console.error('API is not ready');
process.exit(1);
}
...

最佳答案

我改变了解释答案的方式:
您基本上需要Postgres服务,在您的镜像中没有该服务,您基本上是在使用节点镜像而不运行Postgres数据库。

试试这个docker-compose.yml

version: "3.7"
services:
api:
container_name: api
build: .
depends_on:
- postgres
volumes:
- .:/api
ports:
- "3000:3000"
restart: unless-stopped
working_dir: /api
command: nodemon server.js
postgres:
image: postgres:10.4
ports:
- "35432:5432"

编辑1

主机
version: "3.7"
services:
api:
container_name: api
build: .
volumes:
- .:/api
ports:
- "3000:3000"
- "5432:5432"
restart: unless-stopped
working_dir: /api
command: nodemon server.js

关于node.js - Docker Node App Postgres错误 “Connection terminated unexpectedly”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60234170/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com