ENOTFOUND
DNS lookup failed for the specified domain name.
Usually happens because:
- ☑ Hostname Typos
- ☑ Network Offline
- ☑ Missing Host Mapping
🔍 Quick Checklist:
What is ENOTFOUND?
ENOTFOUND stands for 'Entry Not Found'. In Node.js networking, it indicates that a DNS lookup (getaddrinfo) failed to resolve the given hostname into an IP address. This occurs if there is a typo in the hostname, if your DNS server is offline, or if you lack internet connectivity.
Common Causes
- Hostname Typos: Providing paths or protocols in the hostname query (e.g. 'http://api.com' instead of 'api.com').
- Network Offline: Local internet or container DNS resolvers are offline.
- Missing Host Mapping: Querying custom local hostnames without defining them in the /etc/hosts file.
| Cause | Frequency |
|---|---|
| Hostname Typos | ⭐⭐⭐⭐⭐ |
| Network Offline | ⭐⭐⭐⭐ |
| Missing Host Mapping | ⭐⭐⭐ |
Common Mistakes
- Passing the protocol (like http://) inside host lookup parameters (e.g. dns.lookup('http://google.com') will throw ENOTFOUND; pass 'google.com' instead).
- Assuming local containers can resolve hostnames without adding Docker service networks.
How to Fix
Framework-Specific Examples
Handling downstream DNS resolving failures in an Express controller.
app.get('/service', async (req, res, next) => {
try {
await axios.get('https://invalid-api-domain.com');
} catch (err) {
if (err.code === 'ENOTFOUND') {
return res.status(502).json({ error: 'Upstream gateway DNS resolution failed.' });
}
next(err);
}
});Server Configuration Examples
Configuring explicit DNS resolvers inside Nginx to prevent routing failures.
resolver 8.8.8.8 8.8.4.4 valid=300s;
resolver_timeout 5s;Best Practices
- Validate URL syntax configurations dynamically before parsing hostnames.
- Monitor DNS health queries.
Frequently Asked Questions (FAQ)
Q: What does ENOTFOUND mean?
It stands for Error Not Found. In the context of system networking, it indicates that the DNS server could not resolve the requested hostname into a valid IP address.
Q: Why does dns.lookup('http://google.com') throw ENOTFOUND?
DNS lookups resolve pure hostnames (like 'google.com'). They do not understand application layer protocol prefixes (like 'http://' or 'https://') or path suffixes. Pass only the host.
Q: How do I add custom local hostname mappings?
Add mapping entries to your operating system's hosts file (located at `/etc/hosts` on Linux/macOS, or `C:\Windows\System32\drivers\etc\hosts` on Windows).
Q: Can I set a custom DNS server in Node.js?
Yes. You can use the `dns.setServers()` method to configure specific DNS servers (e.g., Google DNS `8.8.8.8`) for resolution.