nginx DNS Cache when Using AWS ALB

nginx DNS Cache when Using AWS ALB

Takahiro Iwasa
Takahiro Iwasa
2 min read
ELB

When using Elastic Load Balancing or something which resolves different IP addresses, we may need to disable nginx’s DNS cache behavior or reduce its TTL.

nginx.conf with DNS Cache On

The following nginx.conf should not properly work because ALB returns different 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;
}

nginx.conf with DNS Cache TTL Shortened

The following nginx.conf should properly work. It caches an IP address for only 60 seconds.

10.0.0.2: Reserved by AWS. The IP address of the DNS server is the base of the VPC network range plus two.

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;
}
--- 	2021-10-28 20:09:37 +0000
+++ 	2021-10-28 20:09:37 +0000
@@ -1,4 +1,6 @@
 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;

Conclusion

When using load balancers resolving to different IP addresses like Elastic Load Balancing, please keep cache TTL in mind.

I hope you will find this post useful.

Takahiro Iwasa

Takahiro Iwasa

Software Developer at KAKEHASHI Inc.
Involved in the requirements definition, design, and development of cloud-native applications using AWS. Now, building a new prescription data collection platform at KAKEHASHI Inc. Japan AWS Top Engineers 2020-2023.