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
200
Related Errors
Database
Unknown Column
The SQL query references a column that doesn't exist in the specified table.
Node.js
Unhandled Promise Rejection
A Promise was rejected but no error handler was attached to catch the rejection.
ERR_REQUIRE_ESM
Node.js
ERR_REQUIRE_ESM
Node.js cannot require() an ES module; use import() instead.
JavaScript
RangeError: Maximum Call Stack Size Exceeded
The function calls itself recursively too many times, exceeding the stack size limit.