Node.js ENOTFOUND
DNS lookup failed because the hostname could not be resolved.
Explanation
ENOTFOUND occurs when the DNS (Domain Name System) lookup for a hostname fails, meaning the hostname could not be resolved to an IP address. This is a common Node.js error when making HTTP requests, connecting to databases, or reaching any network service. Common causes include the hostname being misspelled, DNS server being unreachable, the domain not existing, local hosts file missing an entry, or temporary DNS resolution failures. The error includes the hostname that failed to resolve.
Common Causes
- Hostname misspelled
- DNS server unreachable
- Domain doesn't exist or expired
- Local hosts file missing entry
- Temporary DNS failure
Solution
Verify the hostname is spelled correctly. Check DNS resolution: nslookup hostname or dig hostname. Test if DNS servers are reachable. Check /etc/hosts for local entries. Try using the IP address directly to bypass DNS. Flush DNS cache: sudo dscacheutil -flushcache (Mac) or sudo systemctl restart nscd (Linux). Check network connectivity. Verify the domain exists and hasn't expired. For local development, ensure /etc/hosts or equivalent has the correct entries. Use environment variables for hostnames to avoid hardcoding.
Code Example
// ENOTFOUND when connecting to service
const mysql = require('mysql2');
const connection = mysql.createConnection({
host: 'mydb.local', // DNS resolution fails!
user: 'root'
});
connection.connect((err) => {
if (err && err.code === 'ENOTFOUND') {
console.error('Cannot resolve hostname:', err.hostname);
}
});
// Fix: check DNS resolution
const dns = require('dns');
dns.lookup('mydb.local', (err, address) => {
if (err) {
console.error('DNS failed:', err.message);
} else {
console.log('Resolved to:', address);
}
});
// Use IP directly for testing
const connection = mysql.createConnection({
host: '127.0.0.1', // bypass DNS
user: 'root'
});
// Check DNS from command line
nslookup mydb.local
dig mydb.local
// Flush DNS cache (Mac)
sudo dscacheutil -flushcache
sudo killall -HUP mDNSResponder
Error Information
Language
javascript
Framework
nodejs
Difficulty
Beginner
Views
15
Related Errors
502
DevOps
Nginx 502 Bad Gateway
Nginx received an invalid response from the upstream server (PHP-FPM, Node.js, etc.).
JavaScript
ReferenceError: X is not defined
The code references a variable or function that hasn't been declared.
DevOps
Container Name Already in Use
A Docker container with the specified name already exists.
DevOps
Kubernetes OOMKilled
A container was killed by Kubernetes because it exceeded its memory limit.