Typeorm 失败时重试连接
Typeorm retry connectio on failure
我有一个非常简单的 node.js
应用程序,它使用 Typeorm
与 postgres 数据库通信。如果我 运行 它在我的主机上,或者在两个单独的 docker 容器中,它工作正常。
当我创建一个启动 Postgres 的 docker-compose 文件并且节点 application.Typeorm 无法连接到 Postgres 时出现问题,因为它启动得更快。
这是连接到数据库的代码部分
createConnection({
type: "postgres",
host: "0.0.0.0",
port: 5432,
username: "***",
password: "***",
database: "***",
entities: [
***
],
synchronize: true,
logging: false
}).then(async connection => {...
错误代码消息是
Error: connect ECONNREFUSED 127.0.0.1:5432
web_1 | at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1056:14) {
web_1 | errno: 'ECONNREFUSED',
web_1 | code: 'ECONNREFUSED',
web_1 | syscall: 'connect',
web_1 | address: '127.0.0.1',
web_1 | port: 5432
web_1 | }
有没有办法重试连接?
事实证明,要从 docker compose 连接 Postgres DB,您需要连接的不是本地主机,而是您在 docker-compose.yaml 文件中提供的服务名称。例如这是我的 docker-compose.yaml 文件
version: "3"
services:
db:
image: postgres
restart: always
environment:
POSTGRES_USER: '***'
POSTGRES_PASSWORD: '***'
POSTGRES_DB: '***'
ports:
- 5432:5432
expose:
- 5432
web:
build: .
ports:
- 3000:3000
depends_on:
- db
为了让 typeorm 连接到 Postgres,我需要像这样指定连接属性
{
type: "postgres",
host: "",
port: 5432,
username: "***",
password: "***",
database: "***",
entities: [
***
],
synchronize: true,
logging: false
}
我有一个非常简单的 node.js
应用程序,它使用 Typeorm
与 postgres 数据库通信。如果我 运行 它在我的主机上,或者在两个单独的 docker 容器中,它工作正常。
当我创建一个启动 Postgres 的 docker-compose 文件并且节点 application.Typeorm 无法连接到 Postgres 时出现问题,因为它启动得更快。
这是连接到数据库的代码部分
createConnection({
type: "postgres",
host: "0.0.0.0",
port: 5432,
username: "***",
password: "***",
database: "***",
entities: [
***
],
synchronize: true,
logging: false
}).then(async connection => {...
错误代码消息是
Error: connect ECONNREFUSED 127.0.0.1:5432
web_1 | at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1056:14) {
web_1 | errno: 'ECONNREFUSED',
web_1 | code: 'ECONNREFUSED',
web_1 | syscall: 'connect',
web_1 | address: '127.0.0.1',
web_1 | port: 5432
web_1 | }
有没有办法重试连接?
事实证明,要从 docker compose 连接 Postgres DB,您需要连接的不是本地主机,而是您在 docker-compose.yaml 文件中提供的服务名称。例如这是我的 docker-compose.yaml 文件
version: "3"
services:
db:
image: postgres
restart: always
environment:
POSTGRES_USER: '***'
POSTGRES_PASSWORD: '***'
POSTGRES_DB: '***'
ports:
- 5432:5432
expose:
- 5432
web:
build: .
ports:
- 3000:3000
depends_on:
- db
为了让 typeorm 连接到 Postgres,我需要像这样指定连接属性
{
type: "postgres",
host: "",
port: 5432,
username: "***",
password: "***",
database: "***",
entities: [
***
],
synchronize: true,
logging: false
}