【问题标题】:SequelizeConnectionRefusedError: connect ECONNREFUSED 127.0.0.1:4321SequelizeConnectionRefusedError:连接 ECONNREFUSED 127.0.0.1:4321
【发布时间】:2020-12-14 07:11:19
【问题描述】:

我正在使用 Sequelize ORM 和 PostgreSQL 方言,托管在 localhost 上运行的 docker 容器中。应用通过 3050 端口运行,数据库通过 5432 端口重定向到 4321。

错误:

Server is running on port: 3050
Unable to connect to the database: SequelizeConnectionRefusedError: connect ECONNREFUSED 127.0.0.1:4321

docker-compose.yml

version: "3"

services:
  app:
    build: .
    command: yarn start
    ports:
      - "3050:3050"
    depends_on:
      - postgres
    volumes:
      - .:/home/app/medtech
      - /home/app/medtech/node_modules
  postgres:
    image: postgres:alpine
    ports:
      - "4321:5432"
    environment:
      POSTGRES_USER: postgres
      POSTGRES_DB: medtech_dev
      POSTGRES_PASSWORD: uaz0ZWrsCeUG3271GsRB

我的数据库连接 sn-p

import Sequelize from 'sequelize';
import Constants from '../utils/constants';

const sequelize = new Sequelize(
  Constants.database.name,
  Constants.database.user,
  Constants.database.password, {
    host: Constants.database.host,
    port: Constants.database.port,
    dialect: 'postgres',
    pool: {
      max: 10,
      min: 0,
      acquire: 10000,
      idle: 20000,
    },
    timezone: Constants.timezone,
  },
);

常量值来自我的 .env:

DATABASE_PORT=4321
DATABASE_HOST=localhost
DATABASE_NAME=medtech_dev
DATABASE_USER=postgres
DATABASE_PASSWORD=uaz0ZWrsCeUG3271GsRB

出于某种我不知道的原因我正在使用一个单独的文件来运行我的种子和迁移,使用完全相同的数据库常量并且它可以工作。这里是:

const Constants = require('../utils/constants').default;

module.exports = {
  username: Constants.database.user,
  port: Constants.database.port,
  password: Constants.database.password,
  database: Constants.database.name,
  host: Constants.database.host,
  dialect: 'postgres',
};

在我对文件和阅读的许多线程进行了许多更改之后,我想不出是什么导致了这个问题。那是我第一次使用 Docker,我不知道我的 Docker 配置文件是否真的有问题或其他错误。

感谢您的帮助。

【问题讨论】:

  • 请添加常量值

标签: node.js postgresql docker docker-compose sequelize.js


【解决方案1】:

您的应用容器和 postgres 在两个不同的容器中运行,这意味着它们是两台不同的机器,每台机器都有自己的 ip。

您不能使用 localhost:postgresport 从您的应用容器调用 postgres 服务,反之亦然,从 postgres 到应用容器

Constants.database.host 似乎是 localhost 或 172.0.0.1 ,要访问 postgres 容器,您必须调用容器 ip 或名称或服务名称

在您的情况下,将 Constants.database.host 值更改为 postgres 并尝试一下

【讨论】:

  • 常量值来自 .env 文件,其值与我们在 docker-compose.yml 中的值相同。我已将主机更改为 'postgres' 并使用不同的 IP 得到相同的错误:172.19.0.2:4321
  • 4321 是 docker 外的暴露端口,如果您要从同一网络中的其他容器调用它,则必须将端口更改为本地端口 5432,因此将端口号更改为成为5432
  • 效果很好。太感谢了!现在我弄清楚了我的迁移和种子使用 localhost:4321 的原因,这只是因为我当时在 docker 之外运行。
猜你喜欢
  • 2021-01-19
  • 2019-12-22
  • 2019-05-28
  • 1970-01-01
  • 2022-01-15
  • 2020-03-12
  • 1970-01-01
  • 2020-11-27
相关资源
最近更新 更多