Score:0

NGINX environment-based routing

vn flag

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!

Score:0
vn flag

I went a different route - via templates, environment variables, and envsubst utility which is shipping in the latest nginx docker images.

In template:

set $upstream_back1 "${BACK1}";
set $upstream_back2 "${BACK2}";

In Dockerfile

RUN envsubst < yourtemplate > /etc/nginx/nginx.conf
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.