Configuring nginx Resolver Settings for ELB and Dynamic DNS Backends

Configuring nginx Resolver Settings for ELB and Dynamic DNS Backends

Configure nginx to refresh DNS records when proxying to ELB or another backend with changing IP addresses.

Takahiro Iwasa
2 min read

When nginx proxies to an AWS Elastic Load Balancer (ELB) or another service with dynamic IP addresses, its DNS resolution behavior must be configured carefully. Otherwise, nginx may continue sending traffic to an outdated address.

Why DNS Cache Matters

An Elastic Load Balancer can return different IP addresses for the same DNS name. When a literal hostname is used in proxy_pass, nginx resolves it when the configuration is loaded and does not automatically honor the DNS record’s TTL.

The following nginx.conf does not account for changes to the ELB addresses and may continue using an address resolved during startup or reload.

nginx.conf
location / {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://internal-xxx-alb-1234567890.ap-northeast-1.elb.amazonaws.com;
}

Configuring Runtime DNS Resolution

Define a DNS resolver with a short validity period and pass the upstream hostname through a variable so that nginx resolves it at runtime.

nginx.conf
location / {
# Added to shorten cache TTL
resolver 192.168.0.2 valid=60s;
set $backend internal-xxx-alb-1234567890.ap-northeast-1.elb.amazonaws.com;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://$backend;
}
  • resolver:
    • Specifies the DNS server.
    • The IP address of the DNS server for each VPC is the base of the VPC network range plus two (e.g., 192.168.0.2).
    • See the official documentation for details.
  • valid=60s:
    • Limits the TTL of cached DNS responses to 60 seconds, ensuring nginx frequently resolves fresh IPs.

Conclusion

Using a variable in proxy_pass together with a resolver directive allows nginx to refresh the ELB’s IP addresses at runtime.

The resolver 192.168.0.2 valid=60s; directive points to the VPC DNS server and caches responses for 60 seconds. Assigning the hostname to $backend makes proxy_pass use that resolver instead of relying only on the address obtained when the configuration was loaded.

The same pattern applies to other upstream services whose DNS names resolve to changing IP addresses.

About the author

Takahiro Iwasa

Takahiro Iwasa

Software Developer

This blog shares technical notes from hands-on projects—architecture, implementation, and AWS service integrations.