Nginx proxy_pass指令字符串插值 [英] Nginx proxy_pass directive string interpolation
问题描述
我正在Kubernetes上运行Nginx.
I'm running Nginx on Kubernetes.
当我使用以下proxy_pass指令时,它会按预期工作:
When I use the following proxy_pass directive it works as expected:
proxy_pass "http://service-1.default";
但是以下方法不起作用:
However the following does not work:
set $service "service-1";
proxy_pass "http://$service.default";
我收到一条错误消息,说no resolver defined to resolve service-1.default
I get an error saying no resolver defined to resolve service-1.default
据我所知proxy_pass
正在接收完全相同的字符串,为什么它的行为有所不同?
As far as I can tell proxy_pass
is receiving the exact same string so why is it behaving differently?
我需要使用一个变量,因为我正在使用正则表达式从URL动态获取服务名称.
I need to use a variable because I'm dynamically getting the service name from the URL using a regex.
推荐答案
我已经找到了原因和解决方案.
I've found the reason and a solution.
Nginx检测proxy_pass
中是否正在使用变量(我不知道它是如何做到的).如果没有变量,它将在启动时解析主机名并缓存IP地址.如果存在变量,它将使用解析器(DNS服务器)在运行时查找IP.
Nginx detects if a variable is being used in proxy_pass
(I don't know how it does that). If there is no variable it resolved the hostname at startup and caches the IP address. If there is a variable it uses a resolver (DNS server) to lookup the IP at runtime.
因此解决方案是像这样指定Kube DNS服务器:
So the solution is to specify the Kube DNS server like this:
resolver kube-dns.kube-system.svc.cluster.local valid=5s;
set $service "service-1";
proxy_pass "http://$service.default.svc.cluster.local";
请注意,必须使用服务的完整本地DNS名称,您可以通过运行nslookup service-1
来获得该名称.
Note that the full local DNS name of the service must be used which you can get by running nslookup service-1
.
这篇关于Nginx proxy_pass指令字符串插值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!