【问题标题】:Postgres connection refused with node inside docker compose [duplicate]Postgres连接被docker compose内的节点拒绝[重复]
【发布时间】:2022-01-01 23:39:34
【问题描述】:

所以我有一个使用 express、Postgres 和 pgweb 的应用程序。它们自己工作正常,但从 express 访问数据库时出现以下错误:

postgres_db_1  | 2021-11-23 13:08:59.474 UTC [1] LOG:  database system is ready to accept connections
app_1          | /usr/src/app/helpers/queries.js:7
app_1          |         if (error) throw error
app_1          |                    ^
app_1          |
app_1          | Error: connect ECONNREFUSED 127.0.0.1:5432
app_1          |     at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1161:16) {
app_1          |   errno: -111,
app_1          |   code: 'ECONNREFUSED',
app_1          |   syscall: 'connect',
app_1          |   address: '127.0.0.1',
app_1          |   port: 5432
app_1          | }

我的 docker-compose 文件:

version: "3.9"

services:
  postgres_db:
    image: postgres
    environment:
      - POSTGRES_DB=postgres
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
    ports:
      - "5432:5432"

  pgweb:
    image: sosedoff/pgweb
    restart: unless-stopped
    environment:
      - DATABASE_URL=postgres://postgres:postgres@postgres_db:5432/postgres?sslmode=disable
    ports:
      - "8081:8081"
    depends_on:
      - postgres_db

  app:
    image: node
    build: ./API/
    restart: always
    volumes:
      - .:/app/
      - /app/node_modules
    ports:
      - "3001:3001"
    depends_on:
      - postgres_db

还有我在 express 中的连接配置:

module.exports = {
    user: 'postgres',
    host: 'localhost',
    database: 'postgres',
    password: 'postgres',
    port: 5432,
}

【问题讨论】:

    标签: node.js postgresql docker express


    【解决方案1】:

    在 Docker 中,您应该通过容器名称连接到容器。具体来说,您的 Postgres 的主机是 postgres_db 而不是 localhost。您需要将配置从 host: 'localhost' 修改为 host: 'postgres_db'

    此外,如果您的 Postgres 不打算公开,则无需通过 - "5432:5432" 发布其端口。

    【讨论】:

      猜你喜欢
      • 2021-10-12
      • 2020-09-08
      • 2019-01-02
      • 2021-05-26
      • 2019-11-12
      • 2018-07-03
      • 2021-03-23
      • 2016-03-08
      • 2017-08-05
      相关资源
      最近更新 更多