Nginx Proxy_pass instruction string interpolation

I am running Nginx on Kubernetes.

When I use the following proxy_pass directive, it works as expected:

p>

proxy_pass "http://service-1.default";

But the following does not work:

set $service "service -1";
proxy_pass "http://$service.default";

I receive an error saying that no resolver is defined to resolve service-1.default

As far as I know, proxy_pass is receiving exactly the same string, why does it behave differently?

I need to use variables because I am using regular expressions to dynamically get the service name from the URL.

I found the reason and solution.

Nginx detects whether a variable is used in proxy_pass (I don’t know how it does it). If there is no variable, It resolves the host name and caches the IP address at startup. If there are variables, it uses the resolver (DNS server) to find the IP at runtime.

So the solution is to specify the Kube DNS server, as shown below:

resolver kube-dns.kube-system.svc.cluster.local valid=5s;
set $service "service-1";
proxy_pass "http://$service.default.svc.cluster.local";

Please note that the full local DNS name of the service must be used, which you can obtain by running nslookup service-1.

p>

I am running Nginx on Kubernetes.

When I use the following proxy_pass directive, it works as expected:

proxy_pass "http://service-1.default";

But the following does not work:

set $service "service-1";
proxy_pass "http://$service.default";

I receive an error saying that no resolver is defined to resolve service-1.default

As far as I know, proxy_pass is receiving exactly the same string, why does it behave differently?

I need to use variables because I am using regular expressions to dynamically get the service name from the URL.

I found the reason and the solution Solution.

Nginx detects whether a variable is used in proxy_pass (I don’t know how it does it). If there is no variable, it resolves the host name and caches the IP address at startup. If there are variables, it uses the resolver (DNS server) to find the IP at runtime.

So the solution is to specify the Kube DNS server, as shown below:

< pre>resolver kube-dns.kube-system.svc.cluster.local valid=5s;
set $service “service-1”;
proxy_pass “http://$service.default.svc. cluster.local”;

Please note that the full local DNS name of the service must be used, you can get the name by running nslookup service-1.

Leave a Comment

Your email address will not be published.