ECONNREFUSED
The network connection was refused by the target server.
Explanation
ECONNREFUSED is a system error indicating that the connection attempt was actively refused by the server at the target address and port. This means the server is reachable but not accepting connections on the specified port. In Node.js, this commonly happens when trying to connect to a database, Redis, API server, or any network service that isn't running or isn't listening on the expected port. It's different from ETIMEDOUT which means no response at all.
Common Causes
- Target service not running
- Wrong host or port configuration
- Firewall blocking connection
- Docker container networking issue
- Service bound to wrong interface
Solution
Verify the target service is running and listening on the expected port. Check the host and port configuration. Ensure no firewall is blocking the connection. For Docker, verify container networking and port mapping. Use telnet or nc to test connectivity: telnet host port. Check if the service is bound to the correct interface (0.0.0.0 vs 127.0.0.1). For cloud environments, verify security groups allow inbound traffic.
Code Example
// Node.js connection to database
const mysql = require('mysql2');
const connection = mysql.createConnection({
host: 'localhost',
port: 3306,
user: 'root',
password: 'secret'
});
connection.connect((err) => {
if (err) {
if (err.code === 'ECONNREFUSED') {
console.error('MySQL is not running!');
}
return;
}
console.log('Connected!');
});
// Redis connection
const Redis = require('ioredis');
const redis = new Redis({
host: '127.0.0.1',
port: 6379,
retryStrategy: (times) => Math.min(times * 50, 2000)
});
// Test connectivity
const net = require('net');
const socket = net.createConnection(3306, 'localhost');
socket.on('connect', () => {
console.log('Port 3306 is open');
socket.end();
});
socket.on('error', (err) => {
console.error('Connection refused:', err.message);
});
Error Information
Language
javascript
Framework
nodejs
Difficulty
Intermediate
Views
405
Related Errors
Database
Data Truncation
The data being inserted or updated is too long for the column's defined size.
JavaScript
ReferenceError: X is not defined
The code references a variable or function that hasn't been declared.
Database
Access Denied for User
The database rejected the connection because the username or password is incorrect.
ERR_MODULE_NOT_FOUND
Node.js
ERR_MODULE_NOT_FOUND
Node.js cannot find the specified ES module file.