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
16
Related Errors
Frontend
Webpack Module Not Found
Webpack cannot resolve a module or file imported in the code.
ERR_REQUIRE_ESM
Node.js
ERR_REQUIRE_ESM
Node.js cannot require() an ES module; use import() instead.
Frontend
React Key Warning
React warns that list items are missing unique "key" props for efficient rendering.
Database
Duplicate Entry
The code tries to insert a record with a value that already exists in a unique column.