EHOSTDOWN is a socket connection error indicating the remote host is down or unreachable at the network layer. This error occurs when Node.js receives status information from the underlying communication services that the target host is down.
EHOSTDOWN is a low-level network error that originates from the operating system's socket layer. It indicates that the remote host you're trying to connect to is down according to information received from the underlying communication services. This error is distinct from EHOSTUNREACH (no route to host) - EHOSTDOWN specifically means the host itself is down, not that there's no network path to reach it. The error typically occurs when making HTTP requests, connecting to databases, or establishing any TCP/socket connection where the target system is unavailable. In Node.js, this error can manifest in various contexts including HTTP requests, database connections, Redis clients, and AWS SDK operations. Sometimes the error message can be misleading - for example, AWS SDK may show EHOSTDOWN when the actual issue is expired credentials rather than network connectivity.
First, check if the target host is actually reachable using basic network tools:
# Ping the target host
ping example.com
# Check TCP connectivity on the specific port
telnet example.com 80
# Or use nc (netcat)
nc -zv example.com 80If these commands fail, the host may genuinely be down or unreachable from your network.
Implement error handling to catch EHOSTDOWN errors gracefully:
const http = require('http');
const options = {
hostname: 'example.com',
port: 80,
path: '/',
method: 'GET'
};
const req = http.request(options, (res) => {
// Handle response
});
req.on('error', (err) => {
if (err.code === 'EHOSTDOWN') {
console.error('Host is down:', err.message);
// Implement retry logic or fallback
} else {
console.error('Request error:', err);
}
});
req.end();For promise-based code with axios or fetch, use try-catch:
const axios = require('axios');
try {
const response = await axios.get('http://example.com');
} catch (error) {
if (error.code === 'EHOSTDOWN') {
console.error('Host is down, retrying with backup server...');
// Implement fallback logic
} else {
throw error;
}
}If you see EHOSTDOWN with IP 169.254.169.254 (AWS metadata service), the issue is likely expired credentials rather than network:
# For AWS SSO users, refresh your session
aws sso login --profile your-profile
# Or re-configure credentials
aws configureIn your code, ensure proper credential handling:
const AWS = require('aws-sdk');
// Explicitly set credentials with error handling
AWS.config.credentials = new AWS.SharedIniFileCredentials({
profile: 'your-profile'
});
AWS.config.credentials.get((err) => {
if (err) {
console.error('Error loading credentials:', err);
} else {
console.log('Credentials loaded successfully');
}
});For transient network issues, implement automatic retry with backoff:
async function fetchWithRetry(url, maxRetries = 3, baseDelay = 1000) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
const response = await fetch(url);
return response;
} catch (error) {
if (error.code === 'EHOSTDOWN' && attempt < maxRetries) {
const delay = baseDelay * Math.pow(2, attempt - 1);
console.log(`Attempt ${attempt} failed, retrying in ${delay}ms...`);
await new Promise(resolve => setTimeout(resolve, delay));
} else {
throw error;
}
}
}
}
// Usage
try {
const result = await fetchWithRetry('http://example.com/api');
} catch (error) {
console.error('All retry attempts failed:', error);
}Check if firewall rules or network configuration are blocking the connection:
# Check local firewall (Linux)
sudo iptables -L -n
# Check if SELinux is blocking (RHEL/CentOS)
sudo getenforce
sudo ausearch -m avc -ts recent
# Verify DNS resolution
nslookup example.com
dig example.com
# Check routing table
netstat -rn
# or
ip route showIf you're in a corporate environment, check proxy settings:
// Set proxy for Node.js HTTP requests
const https = require('https');
const HttpsProxyAgent = require('https-proxy-agent');
const agent = new HttpsProxyAgent('http://proxy.company.com:8080');
https.get('https://example.com', { agent }, (res) => {
// Handle response
});Understanding EHOSTDOWN vs EHOSTUNREACH:
EHOSTDOWN specifically indicates the host is down (received from layer 2/3), while EHOSTUNREACH means no route exists to the host. EHOSTDOWN is less common and typically indicates more direct connectivity failure.
Layer 2 Connectivity:
EHOSTDOWN often occurs at layer 2 (data link layer) when a device is directly connected but doesn't respond to ARP requests. This is common in scenarios where a device loses power or its network interface fails.
Misleading AWS SDK Errors:
The AWS SDK may report EHOSTDOWN when trying to reach the metadata service (169.254.169.254) if credentials are expired. This is misleading because the issue isn't network connectivity but authentication. Always check credential status first when seeing this error with AWS services.
Container and Cloud Environments:
In containerized environments (Docker, Kubernetes), EHOSTDOWN can occur when:
- Container networking isn't properly configured
- Service mesh sidecar isn't ready
- Host VM experiences networking issues
- Pod-to-pod networking fails due to CNI plugin issues
Health Checks and Circuit Breakers:
Implement health check mechanisms and circuit breaker patterns to handle hosts that frequently go down:
const CircuitBreaker = require('opossum');
const options = {
timeout: 3000, // 3 seconds
errorThresholdPercentage: 50,
resetTimeout: 30000 // 30 seconds
};
function makeRequest() {
return fetch('http://example.com/api');
}
const breaker = new CircuitBreaker(makeRequest, options);
breaker.fallback(() => {
return { data: 'cached or default data' };
});
breaker.on('open', () => {
console.log('Circuit breaker opened - too many failures');
});Monitoring and Alerting:
Log EHOSTDOWN errors with context (timestamp, target host, retry attempts) to help identify patterns. Use structured logging libraries like winston or pino for better observability.
Error: EMFILE: too many open files, watch
EMFILE: fs.watch() limit exceeded
Error: Middleware next() called multiple times (next() invoked twice)
Express middleware next() called multiple times
Error: Worker failed to initialize (worker startup error)
Worker failed to initialize in Node.js
Error: EMFILE: too many open files, open 'file.txt'
EMFILE: too many open files
Error: cluster.fork() failed (cannot create child process)
cluster.fork() failed - Cannot create child process