【问题标题】:Connecting PostgreSQL from TypeORM docker container从 TypeORM docker 容器连接 PostgreSQL
【发布时间】:2021-11-21 19:30:51
【问题描述】:

我正在尝试使用 typeorm 将 postgres db 连接到 nodejs。

我尝试在 localhost 中使用 postgres 和 nodejs 执行此操作,并且效果很好。但是,当我将 postgres 和 nodejs 放入 docker 容器时,我遇到了问题。

(docker inspect 中用于 postgres 容器的“IPAdress”字段为 172.19.0.3)

来自 Nodejs 的错误:

web_1    | error: TypeORM connection error:  Error: connect ECONNREFUSED 172.19.0.3:5433

docker-compose.yml

services:
  web:
    build: .
    volumes:
      - ./:/app
    ports:
      - "9001:9001"
    links:
      - pg_db

  pg_db:
    image: postgres
    ports:
      - "5433:5433"
    env_file: 
      - docker.env

ormconfig.json

[
  {
    "name": "default",
    "driver": {
      "type": "postgres",
      "host": "pg_db",
      "port": 5433,
      "username": "postgres",
      "password": "test",
      "database": "testDB"
    },
    "autoSchemaSync": true,
    "entities": [
      "src/controller/entity/*.js"
    ],
    "cli": {
      "entitiesDir": "src/controller/entity"
    }
  }
]

谢谢

【问题讨论】:

    标签: postgresql typescript docker typeorm


    【解决方案1】:

    PostgreSQL 的默认端口是 5432。在你的 nodejs 配置中更改它。

    端口暴露对于你的 nodejs 来说不是所必需的,只是将该端口链接到你的本地主机(或其他 IP):

        ports:
          - "5433:5433"
    

    您可以删除它们。

    但是,如果您无论如何都需要 postgres 听 5433,则需要进行一些自定义:

      pg_db:
        ...
        environment:
        - PGPORT=5433
        ...
    

    【讨论】:

    • 哇,我很愚蠢。谢谢修复它。我故意将其设为 5433,因为 postgres 的 localhost 实例正在使用端口 5432,但出于某种原因,我认为 docker 容器 postgres 将自动使用 5433。
    猜你喜欢
    • 1970-01-01
    • 2017-10-15
    • 2021-03-23
    • 2018-01-02
    • 2021-02-03
    • 1970-01-01
    • 2021-08-10
    • 2019-12-19
    相关资源
    最近更新 更多