How to Fix Nginx Upstream DNS Resolution Error
In this tutorial, you'll learn about How to Fix Nginx Upstream DNS Resolution Error. We cover key concepts, practical examples, and best practices.
Nginx returns 502 Bad Gateway with host not found in upstream or no resolver defined to resolve in the error log — the upstream hostname cannot be resolved because no resolver directive is configured.
The Problem
2026/06/24 10:00:00 [error] host not found in upstream "backend.example.com"
in /etc/nginx/sites-enabled/example.com:15
Step-by-Step Fix
Step 1: Add resolver directive
http {
resolver 127.0.0.53 valid=30s;
server {
location /api/ {
resolver 8.8.8.8 valid=30s;
proxy_pass http://backend.example.com;
}
}
}
Step 2: Use variables in proxy_pass for runtime DNS resolution
location /api/ {
resolver 8.8.8.8 valid=30s ipv6=off;
set $backend "backend.example.com";
proxy_pass http://$backend;
}
Step 3: Validate resolver works
dig @127.0.0.53 backend.example.com
nslookup backend.example.com 8.8.8.8
Step 4: Use upstream block with DNS-based servers
upstream backend {
zone backend 64k;
server backend.example.com resolve;
}
server {
resolver 127.0.0.53 valid=10s;
location / {
proxy_pass http://backend;
}
}
Step 5: Set DNS cache TTL
resolver 127.0.0.53 valid=60s;
resolver_timeout 5s;
Prevention Tips
- Always configure a
resolverwhen using hostnames inproxy_pass - Use
valid=30sto control how often DNS is re-resolved - Use variables in proxy_pass to force runtime DNS resolution
- Monitor Nginx error logs for DNS resolution failures
Common Mistakes with upstream dns
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists
These mistakes appear frequently in real-world NGINX code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro