Configuring nginx Resolver Settings for ELB and Dynamic DNS Backends
When nginx sits behind ELB or other dynamic DNS backends, configure resolver settings so it does not keep stale IP addresses.
When using AWS Elastic Load Balancer (ELB) or similar services that resolve to dynamic IP addresses, it’s crucial to properly configure nginx to manage DNS cache. Failing to address this can lead to issues as nginx may continue using outdated IPs.
Why DNS Cache Matters
Elastic Load Balancers often return different IP addresses for the same DNS name, making DNS caching problematic. By default, nginx caches DNS resolutions indefinitely, which can cause it to direct traffic to stale IPs.
The following nginx.conf demonstrates a standard setup that does not account for DNS caching. This configuration will fail when the ELB changes its IP addresses.
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;}Adjusting nginx Configuration to Shorten DNS Cache TTL
To address this, you can explicitly define a DNS resolver with a shortened cache TTL.
location / { # Added to shorten cache TTL resolver 192.168.0.2 valid=60s; 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;}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). - Please refer to the official documentation.
valid=60s:- Limits the TTL of cached DNS responses to 60 seconds, ensuring nginx frequently resolves fresh IPs.
Related posts
Sign in with Slack Using Cognito User Pools and OIDC
This note describes how to federate Cognito user pools with Slack using OIDC to implement "Sign in with Slack".
Deploying FastAPI on AWS Lambda with Lambda Web Adapter
This example guides you through the process of developing API backends with FastAPI using Lambda Web Adapter.
API Gateway WebSocket: Implementing a Mock Integration
This note describes how to build an API Gateway WebSocket endpoint using mock integration.
Uploading to S3 Through CloudFront Pre-Signed URLs
CloudFront signed URLs let you upload to S3 through a custom domain—useful when direct S3 pre-signed URLs are not an option.
AWS EventBridge Scheduler: Automate EC2 Scheduling with Ease
This note describes how to automate starting and stopping of EC2 instances using EventBridge Scheduler.
