nginx DNS Cache when Using AWS ALB

nginx DNS Cache when Using AWS ALB

Takahiro Iwasa
(岩佐 孝浩)
Takahiro Iwasa (岩佐 孝浩)
1 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;
Takahiro Iwasa
(岩佐 孝浩)

Takahiro Iwasa (岩佐 孝浩)

Software Developer at KAKEHASHI Inc.
Involved in the design, development, and operation of the prescription data collection platform