2

I have the following config below on Nginx.conf

<b>
http {
    log_format my_upstream '$remote_addr [$time_local] "$request" $status'
        '"$upstream_addr" $upstream_response_time $upstream_http_etag $host $http_host';
    access_log /var/log/nginx/upstream.log my_upstream;

upstream myapp{
         ip_hash;
         server x.x.x.174:8001;
         server x.x.x.96:8001;
     }

    server {
     listen 9000;
     #websocket
     location /jms {
         proxy_pass http://myapp/jms;
         proxy_http_version 1.1;
         proxy_set_header Upgrade $http_upgrade;
         proxy_set_header Connection "Upgrade";
         proxy_set_header Host $upstream_addr;
     }

     location / {
        proxy_pass http://myapp;
     }
     }
}
</b>

I tried setting the Host to $upstream_addr, but unfortunately, I'm receiving null in the request. Could anyone please help me in setting up the Host as $upstream_addr. Thanks, Bhaskar.

Bhaskar
  • 21
  • 1
  • 5
  • `proxy_set_header` is executed before `proxy_pass` even if you put it after `proxy_pass`, and before entering load balancing, $upstream_addr is null – Larry.He Apr 04 '18 at 14:52

1 Answers1

1

As Larry mentioned, the request headers (and body) are fixed before the upstream is selected. Hence your $upstream_addr would always return null.

What you can do is add two levels of proxy. But this might get messy if you have a lot of upstreams of myapp.

upstream myapp{
     ip_hash;
     server x.x.x.174:8001;
     server x.x.x.96:8001;
 }

upstream main {
  server 127.0.0.1:8001;
  server 127.0.0.1:8002;
}
server {
  listen      8001 ;

  location / {
    proxy_pass       http://x.x.x.174:8001/jms;
    proxy_set_header Host x.x.x.174:8001;
  }
}

server {
  listen      8002 ;
  location / {
     proxy_pass       http://x.x.x.96:8001/jms;
     proxy_set_header Host x.x.x.96:8001;
  }
}

server {
listen 9000;
#websocket
location /jms {
     proxy_pass http://main;
     proxy_http_version 1.1;
     proxy_set_header Upgrade $http_upgrade;
     proxy_set_header Connection "Upgrade";
}

location / {
    proxy_pass http://myapp;
}
}
  • Thanks, Larry and Aakash for making me understand and providing a solution, is there any other better approach than opening multiple ports. – Bhaskar Apr 05 '18 at 03:09
  • @bhaskar I also had similar requirement, so i also tried this option. But with 2 levels of proxy, nginx is not trying next upstream main server in case one localserver is throwing 502. I even configured all possible values for proxy_upstream_next.. did you also face this issue – Rajat Goyal Aug 09 '21 at 21:35