NGINX基于环境的路由
我有一个在多个K8S群集中运行的应用程序;假设有前端服务,还有两个后端服务。
我使用nginx代理前端服务的请求。常规nginx版本,不是 nginx+。 这是nginx.conf:
server {
....
set $back1 "<k8s hostname for the backend1 service>";
set $back2 "<k8s hostname for the backend2 service>";
location /back1 {
rewrite ^/back1/(.*)$ /$1 break;
proxy_pass http://$back1;
}
<and same for the backend 2 service>
}
因此,基本上,发生的是在我的前端应用程序中,我将后端服务地址设置为 localhost/back1 和 local -Host/back2 ,请求点击nginx,从那些 back1 和 back2 前缀中脱掉这些 back1 前缀,并在K8S中实际的后端服务中指定了我指定的任何端点。
由于我有多个K8S群集,因此后端服务主机名也有所不同,我需要在我的Nginx Conf中考虑到这一点。
问题是: 有没有办法让Nginx区分我的K8S簇? 也许我可以将环境变量传递给运行前端服务的容器,并在nginx.conf中进行 If 语句。类似:
server {
if (${env} = "cluster1") {
set $back1 = "<cluster1 hostname>"
}
if (${env} = "cluster2") {
set $back1 = "<cluster2 hostname>"
}
}
或者如果我可以在nginx conf中执行shell命令以获取主机名并在块中写下类似的写入。
感谢此事的任何帮助!
I have a single application running in multiple K8s clusters; Let's say there is a frontend service, and two backend ones.
I use NGINX proxy the requests from the frontend to the backend services. Regular NGINX edition, not NGINX+.
Here is the nginx.conf:
server {
....
set $back1 "<k8s hostname for the backend1 service>";
set $back2 "<k8s hostname for the backend2 service>";
location /back1 {
rewrite ^/back1/(.*)$ /$1 break;
proxy_pass http://$back1;
}
<and same for the backend 2 service>
}
So basically, what happens is that in my frontend application, I set the backend service address to localhost/back1 and localhost/back2, the requests hit NGINX which strips off those back1 and back2 prefixes and call whatever endpoint I specify after in the actual backend services in K8s.
As I have multiple K8s clusters, the backend services hostnames differ, and I need to account for that in my NGINX conf.
The question is:
Is there a way for NGINX to differentiate between my K8s clusters?
Perhaps I can pass an environment variable to the container running my frontend service, and make an if statement in nginx.conf. Something like:
server {
if (${env} = "cluster1") {
set $back1 = "<cluster1 hostname>"
}
if (${env} = "cluster2") {
set $back1 = "<cluster2 hostname>"
}
}
Or if I can execute a shell command in the nginx conf to get the hostname and write similar if blocks.
I would appreciate any help on this matter!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我走了一条不同的路线 - 通过模板,环境变量和Envsubst实用程序,该实用程序正在最新的Nginx Docker映像中发货。
在模板中:
在Dockerfile中
I went a different route - via templates, environment variables, and envsubst utility which is shipping in the latest nginx docker images.
In template:
In Dockerfile