【问题标题】:Typeorm retry connectio on failureTypeorm 失败时重试连接
【发布时间】:2019-11-16 22:29:32
【问题描述】:

我有一个非常简单的node.js 应用程序,它使用Typeorm 与postgres 数据库通信。如果我在我的主机上运行它,或者在两个单独的 docker 容器中运行它,它工作正常。 当我创建一个启动 Postgres 和节点应用程序的 docker-compose 文件时出现问题。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  | }

有没有办法重试连接?

【问题讨论】:

    标签: node.js postgresql docker-compose typeorm


    【解决方案1】:

    事实证明,要从 docker compose 连接 Postgres DB,您需要连接的不是 localhost,而是您在 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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-16
      • 2020-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-25
      • 2019-02-21
      相关资源
      最近更新 更多