How to fix Error: connect EHOSTUNREACH (host unreachable) in Node.js

Node.jsINTERMEDIATEMEDIUMUpdated Dec 9, 2025ยท 275 views

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.

Quick fix

Fixes EHOSTUNREACH

# 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.com
  1. Verify the target host is reachable
  2. Check your firewall and security settings
  3. Verify network configuration and routing
  4. Implement proper error handling with retry logic
node.js โ€” error
# 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.com
Error: connect EHOSTUNREACH (host unreachable)

What this error means

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.

Typical symptoms

  • Network requests fail immediately with "Error: connect EHOSTUNREACH"
  • Application crashes if error is not caught properly
  • Intermittent connectivity issues when network configuration changes
  • npm install commands fail with EHOSTUNREACH errors
  • Container-to-container communication fails in Docker or Kubernetes
  • HTTP client requests timeout or fail before reaching the target server
  • WebSocket connections cannot be established

Common causes

  1. Target host or server is powered off or disconnected from the network
  2. Incorrect IP address or hostname specified in the connection request
  3. Firewall rules blocking outbound traffic to the destination host or port
  4. Network routing tables missing routes to the target network
  5. VPN or proxy configuration preventing direct access to the host
  6. Docker or Kubernetes network misconfiguration causing container isolation
  7. DNS resolution returning an incorrect or unreachable IP address
  8. Network interface down or misconfigured on the client machine
  9. MTU (Maximum Transmission Unit) mismatch in Docker-in-Docker setups
  10. Cloud security group rules blocking egress traffic
  11. Subnet masks or router configuration errors preventing routing

How to fix "Error: connect EHOSTUNREACH (host unreachable)"

1Verify the target host is reachable

First, confirm that the target host is actually reachable from your machine using basic network tools:

bash
# 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.com

If ping or telnet fails, the issue is at the network level, not with your Node.js application.

2Check your firewall and security settings

Firewall rules may be blocking outbound connections to the target host or port:

bash
# 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 allprofiles

If 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:

bash
# AWS - check security group rules
aws ec2 describe-security-groups --group-ids sg-xxxxxxxxx
3Verify network configuration and routing

Check your machine's routing table to ensure there's a route to the destination network:

bash
# On Linux/macOS
netstat -rn
# or
ip route show

# On Windows
route print

Look for a default gateway or specific route that covers the target IP address. If missing, you may need to add a route:

bash
# 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.1
4Implement proper error handling with retry logic

Add robust error handling to gracefully handle EHOSTUNREACH errors in your Node.js code:

javascript
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:

javascript
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();
5Fix Docker container networking issues

If running in Docker, ensure containers can reach external networks:

bash
# 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 bridge

Enable bridge-netfilter for proper iptables support:

bash
# 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 --system

For Docker-in-Docker MTU issues:

bash
# Set MTU in Docker daemon config
sudo nano /etc/docker/daemon.json

Add:

json
{
  "mtu": 1450
}

Then restart Docker:

bash
sudo systemctl restart docker
6Debug DNS resolution issues

Incorrect DNS resolution can return unreachable IP addresses:

bash
# 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.com

In your Node.js application, you can specify DNS resolution options:

javascript
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);
  }
});

Advanced notes

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.

Frequently asked questions

What does "EHOSTUNREACH" mean?
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.
How do I fix "EHOSTUNREACH"?
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.
What causes "EHOSTUNREACH"?
Target host or server is powered off or disconnected from the network Incorrect IP address or hostname specified in the connection request Firewall rules blocking outbound traffic to the destination host or port
Is the "EHOSTUNREACH" error serious?
It is a medium-severity error โ€” more of a blocker than a risk. The steps above resolve it.

Official resources & further reading