Fixing SequelizeConnectionRefusedError with Sequelize & Docker

Updated: December 29, 2023 By: Guest Contributor Post a comment

Understanding the Error

The SequelizeConnectionRefusedError: connect ECONNREFUSED in a Node.js project using Sequelize and Docker typically signifies that the Sequelize ORM (Object-Relational Mapping) library is trying to connect to a database, but the connection attempt is being refused. This can be caused by several reasons such as the database container not running, the container not accepting connections, or Sequelize being misconfigured to connect to the right host and port.

Resolving the Error

Check Database Container Status

First, ensure that your database container is running. You can check this with Docker commands such as docker ps to list running containers or docker-compose ps if you’re using Docker Compose. If it’s not running, start it with docker start followed by the container name, or docker-compose up for a Docker Compose environment.

Configuration Check

Next, verify the database connection settings in your Sequelize configuration. These settings should match the service name and port you’ve defined in your docker-compose.yml file. Ensure that the host is set to the name of the service, and the port matches the one exposed by the Docker container.

Network Check

In some cases, the problem might be related to Docker networking. Make sure the Node.js application and the database are on the same network, and Docker’s port mappings are correctly configured.

Code Example

Here is a complete basic code example that uses Sequelize to connect to a PostgreSQL database within a Docker environment:

const Sequelize = require('sequelize');

const sequelize = new Sequelize('database', 'username', 'password', {
 host: 'db',  // same as Docker Compose service name
 dialect: 'postgres',
 port: 5432  // default port for PostgreSQL
});

sequelize.authenticate().then(() => {
 console.log('Connection has been established successfully.');
}).catch(err => {
 console.error('Unable to connect to the database:', err);
});

In docker-compose.yml, the database service would be defined like this:

services:
  db:
    image: postgres
    ports:
      - '5432:5432'
    environment:
      POSTGRES_PASSWORD: password

Make sure to replace ‘database’, ‘username’, and ‘password’ with the actual credentials used for your database.