This error occurs when Node.js attempts a TCP connection but the operating system cannot find a route to the destination host or network. It indicates network configuration issues, routing problems, or firewall restrictions blocking access to the target host.
The EHOSTUNREACH error is a TCP connection failure that occurs when your Node.js application tries to connect to a specific IP address or hostname, but the underlying operating system is unable to establish a connection to that destination. This error code comes directly from the operating system's network stack, signaling that there is no available route to reach the target host. Unlike ECONNREFUSED (which means the host is reachable but actively refusing the connection), EHOSTUNREACH indicates a lower-level networking problem: the packets cannot even reach the destination host. This can stem from routing protocol issues, firewall blockages, or signals from intermediate gateways indicating the destination is inaccessible. This error commonly appears when making HTTP requests with libraries like axios, fetch, or the native http/https modules, as well as when establishing WebSocket connections or other TCP-based communications.
First, confirm that the target host is actually reachable from your machine using basic network tools:
# Test connectivity with ping
ping target-hostname.com
# Test specific port connectivity
telnet target-hostname.com 80
# Or use nc (netcat)
nc -zv target-hostname.com 80
# Check DNS resolution
nslookup target-hostname.com
dig target-hostname.comIf ping or telnet fails, the issue is at the network level, not with your Node.js application.
Firewall rules may be blocking outbound connections to the target host or port:
# On Linux, check iptables rules
sudo iptables -L -n -v
# On macOS, check firewall status
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --getglobalstate
# On Windows, check Windows Firewall
netsh advfirewall show allprofilesIf you're in a corporate environment, check with your network administrator about proxy or firewall restrictions.
For cloud environments (AWS, GCP, Azure), verify security group rules allow outbound traffic to the target:
# AWS - check security group rules
aws ec2 describe-security-groups --group-ids sg-xxxxxxxxxCheck your machine's routing table to ensure there's a route to the destination network:
# On Linux/macOS
netstat -rn
# or
ip route show
# On Windows
route printLook for a default gateway or specific route that covers the target IP address. If missing, you may need to add a route:
# Linux - add route (example)
sudo ip route add 192.168.1.0/24 via 192.168.0.1
# macOS - add route
sudo route add -net 192.168.1.0/24 192.168.0.1Add robust error handling to gracefully handle EHOSTUNREACH errors in your Node.js code:
const axios = require('axios');
async function makeRequestWithRetry(url, maxRetries = 3) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
const response = await axios.get(url, {
timeout: 5000, // 5 second timeout
});
return response.data;
} catch (error) {
if (error.code === 'EHOSTUNREACH') {
console.error(`Attempt ${attempt}: Host unreachable - ${error.message}`);
if (attempt === maxRetries) {
throw new Error(`Failed after ${maxRetries} attempts: Host unreachable`);
}
// Exponential backoff
const delay = Math.pow(2, attempt) * 1000;
console.log(`Retrying in ${delay}ms...`);
await new Promise(resolve => setTimeout(resolve, delay));
} else {
// Different error, throw immediately
throw error;
}
}
}
}
// Usage
makeRequestWithRetry('http://example.com/api')
.then(data => console.log('Success:', data))
.catch(err => console.error('Final error:', err.message));For native http module:
const http = require('http');
const options = {
hostname: 'example.com',
port: 80,
path: '/api',
method: 'GET',
timeout: 5000,
};
const req = http.request(options, (res) => {
console.log(`Status: ${res.statusCode}`);
});
req.on('error', (error) => {
if (error.code === 'EHOSTUNREACH') {
console.error('Host is unreachable:', error.message);
// Implement retry or fallback logic
} else {
console.error('Request error:', error);
}
});
req.end();If running in Docker, ensure containers can reach external networks:
# Check if container has network connectivity
docker exec <container-name> ping -c 3 8.8.8.8
# Inspect container network settings
docker inspect <container-name> | grep -A 20 NetworkSettings
# Check Docker network configuration
docker network ls
docker network inspect bridgeEnable bridge-netfilter for proper iptables support:
# Enable bridge-nf-call-iptables
sudo modprobe br_netfilter
echo 1 | sudo tee /proc/sys/net/bridge/bridge-nf-call-iptables
echo 1 | sudo tee /proc/sys/net/bridge/bridge-nf-call-ip6tables
# Make permanent
cat <<EOF | sudo tee /etc/sysctl.d/k8s.conf
net.bridge.bridge-nf-call-iptables = 1
net.bridge.bridge-nf-call-ip6tables = 1
EOF
sudo sysctl --systemFor Docker-in-Docker MTU issues:
# Set MTU in Docker daemon config
sudo nano /etc/docker/daemon.jsonAdd:
{
"mtu": 1450
}Then restart Docker:
sudo systemctl restart dockerIncorrect DNS resolution can return unreachable IP addresses:
# Check DNS resolution
nslookup target-hostname.com
dig target-hostname.com
# Try different DNS servers
nslookup target-hostname.com 8.8.8.8
dig @8.8.8.8 target-hostname.comIn your Node.js application, you can specify DNS resolution options:
const dns = require('dns');
// Check DNS resolution in your app
dns.lookup('target-hostname.com', (err, address, family) => {
if (err) {
console.error('DNS lookup failed:', err);
} else {
console.log('Resolved to:', address);
}
});
// Use custom DNS servers
const resolver = new dns.Resolver();
resolver.setServers(['8.8.8.8', '8.8.4.4']);
resolver.resolve4('target-hostname.com', (err, addresses) => {
if (err) {
console.error('Resolution error:', err);
} else {
console.log('Addresses:', addresses);
}
});Kubernetes Networking: In Kubernetes environments, EHOSTUNREACH often occurs when pod network subnets conflict with host networks, or when network policies restrict pod-to-pod communication. Ensure your CNI (Container Network Interface) plugin is properly configured and that network policies allow the required traffic flows.
IPv4 vs IPv6: Some systems may attempt to connect via IPv6 first, which can fail with EHOSTUNREACH if IPv6 routing is not properly configured. You can force IPv4 by using the family: 4 option in Node.js DNS lookups or by disabling IPv6 at the OS level if not needed.
VPN and Split Tunneling: When connected to a VPN, your routing table changes significantly. Some VPNs use split tunneling, which routes only certain traffic through the VPN. If the target host requires VPN access but isn't included in the split tunnel configuration, you'll get EHOSTUNREACH.
AWS VPC and Private Subnets: In AWS, instances in private subnets without NAT Gateway or Internet Gateway configuration cannot reach external hosts. Ensure proper VPC routing tables and gateway configurations.
Monitoring and Logging: Implement network monitoring to track EHOSTUNREACH occurrences. High frequency may indicate infrastructure instability, DNS issues, or DDoS protection blocking your requests.
Error: Listener already called (once event already fired)
EventEmitter listener already called with once()
Error: EACCES: permission denied, open '/root/file.txt'
EACCES: permission denied
Error: Invalid encoding specified (stream encoding not supported)
How to fix Invalid encoding error in Node.js readable streams
Error: EINVAL: invalid argument, open
EINVAL: invalid argument, open
TypeError: readableLength must be a positive integer (stream config)
TypeError: readableLength must be a positive integer in Node.js streams