2

I want to resolve DNS every time when a new request will come, I am trying to resolve DNS dynamically in Nginx by setting DNS in a variable. It is working correctly for the below example.

server {
    location /mypath {
        resolver 10.0.3.2 10.0.2.2 ipv6=off valid=10s;
        resolver_timeout 30s;
        set $backend_servers backends.example.com;
        proxy_pass http://$backend_servers/mypath;
    }
}

but when I have multiple Location blocks with the same DNS name in the variable, it is not able to resolve the DNS.

server {
    location /mypath {
        resolver 10.0.3.2 10.0.2.2 ipv6=off valid=10s;
        resolver_timeout 30s;
        set $backend_servers backends.example.com;
        proxy_pass http://$backend_servers/mypath;
    }
    location /mysecondpath {
        resolver 10.0.3.2 10.0.2.2 ipv6=off valid=10s;
        resolver_timeout 30s;
        set $backend_servers backends.example.com;
        proxy_pass http://$backend_servers/mysecondpath;
    }
}

If you observe $backend_servers is used in both location block. if I use any one of them only Nginx proxy works perfectly. when I use both it returns 502.

What I am doing wrong here? Thanks in advance.

Darshan Jain
  • 316
  • 2
  • 9

1 Answers1

2

Two things why DNS resolver is not working with proxy URLs

  1. DNS Resolver that you are using is might be wrong. Please confirm with Your infra admin. According to your DNS resolver, I guess your AWS VPC CIDR block is 10.0.0.0/16. If it is correct then use 10.0.0.2 As DNS resolver.

  2. Also when you are using a dynamic proxy (Proxy through a variable), You need to specify query param as well. The correct syntax that worked for me is as below

    server { location /mypath/(.*) { resolver 10.0.0.2 ipv6=off valid=10s; resolver_timeout 30s; set $backend_servers backends.example.com; proxy_pass http://$backend_servers/mypath/$1$is_args$args; } location /mysecondpath/(.*) { resolver 10.0.0.2 ipv6=off valid=10s; resolver_timeout 30s; set $backend_servers backends.example.com; proxy_pass http://$backend_servers/mysecondpath/; } }