【问题标题】:Postgres ECONNREFUSED on Docker Compose with NodeJS [duplicate]Postgres ECONNREFUSED 在 Docker Compose 上使用 NodeJS [重复]
【发布时间】:2020-02-03 14:53:00
【问题描述】:

当我通过 docker-compose 运行时尝试从 docker 中的 NodeJS 应用程序连接到 docker 中的 postgres 服务器时收到 ECONNREFUSED。但是我可以从我的主机连接。这是我的 docker-compose.yml:

version: "2.4"

services:
  api:
    build: 
      context: .
      target: dev
    depends_on: 
      - postgres
    ports: 
      - "8080:8080"
      - "9229:9229"
    networks:
      - backend
    environment:
      - NODE_ENV=development
      - PGHOST=postgres
      - PGPASSWORD=12345678
      - PGUSER=test
      - PGDATABASE=test
      - PGPORT=5433
    volumes: 
      - .:/node/app
      - /node/app/node_modules # Use empty volume to hide the node_modules from the host os

  postgres:
    image: postgres:11
    restart: always
    ports:
    - "5433:5432"
    networks:
      - backend
    volumes:
      - db-data:/var/lib/postgresql/data
    environment: 
      POSTGRES_PASSWORD: 12345678
      POSTGRES_USER: test
      POSTGRES_DB: test

networks:
  backend:

volumes:
    db-data:

nodeJS代码:

const client = new Client({
      user: process.env.PGUSER,
      host: process.env.PGHOST,
      database: process.env.PGDATABASE,
      password: process.env.PGPASSWORD,
      port: Number(process.env.PGPORT),
    });
client.connect();

错误:

{ Error: connect ECONNREFUSED 172.22.0.2:5433
api_1   |     at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1106:14)
api_1   |   errno: 'ECONNREFUSED',
api_1   |   code: 'ECONNREFUSED',
api_1   |   syscall: 'connect',
api_1   |   address: '172.22.0.2',
api_1   |   port: 5433 }

同时,我可以毫无问题地从主机操作系统连接到数据库服务器。网络有问题吗?

编辑:在 nodejs 应用程序尝试之前,dB 服务器已准备好接受连接(我也尝试从 nodejs 应用程序内重试连接)。

【问题讨论】:

    标签: node.js postgresql docker-compose


    【解决方案1】:

    不,网络没有任何问题。只是因为你连接到了错误的端口。

    在 compose 网络中,您的 postgres 容器暴露了 5432 端口,因此它只接受来自 compose 网络中该端口的请求。所以只需要把PGPORT=5433改成PGPORT=5432即可。

    您可以从您的主机操作系统访问的原因是因为 docker-compose 映射了您的端口 5433:5432,因此所有从外部(主机操作系统)对 5433 的请求都将传递给您的 compose 网络内的 5432

    希望足够清楚,以便您解决问题。

    【讨论】:

      猜你喜欢
      • 2018-01-16
      • 2018-11-21
      • 1970-01-01
      • 2020-05-10
      • 2022-10-17
      • 2021-02-07
      • 2021-08-12
      • 2019-04-22
      • 2019-02-19
      相关资源
      最近更新 更多