我正在使用Sequelize ORM和PostgreSQL方言,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
我的db连接段
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,
},
);
常量值来自my.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配置文件是否真的有什么问题,还是其他一些错误。
我很感激任何帮助。
您的应用程序容器和postgres运行在两个不同的容器中,这意味着它们是两台不同的机器,每台机器都有自己的IP。
您不能通过使用localhost:postgresport
从应用程序容器调用postgres服务,反之亦然,从postgres调用到应用程序容器
似乎constants.database.host
是localhost或172.0.0.1,要到达postgres容器,您必须调用容器ip或名称或服务名称
在您的示例中,将constants.database.host
值更改为postgres
并尝试