The scenario is like this, I have a nginx reverse proxy server in front of two app servers which are backups of each other, I want nginx to forward all user requests to the first app server at first, and if the first app server is down, I want nginx to forward all user requests to the second app server from that time on, until if the second app server is down, and nginx should revert back to forward all user requests to the first app server, so on and so forth. Of course, if both app servers are down then nginx will return an error.

I looked into settings like upstream load balancing and proxy_next_upstream settings but it seems not really what I'm looking for here. Any idea how to configure nginx for my scenario? Thanks.


You'll want to be using the nginx upstream configuration in order to achieve this..

upstream mybackend {
    # first app server

    # second app server
    server backup;

server {

    location / {
        proxy_pass http://mybackend;

The key here is the backup parameter, which tells nginx to only utilize that node in the event that primary nodes (i.e; nodes not tagged backup) are unavailable.

Full documentation here.

  • doesn't that mean the nginx reverse proxy will first try to forward the request to the first app server every time, and then only forward to the backup server when it finds the first server not available? what I'm looking for is actually that when the first server becomes unavailable, it will switch to the second server as the primary server from that time on, and then only switch back to the first server when the second server becomes unavailable. – hellopeach Sep 5 '18 at 15:57
  • I don't believe there's a way you can make it persistently "flip flop" between the 2 servers in the event of node outages. Whatever you configure as your primary will always be considered the primary. In the event of a primary outage, it'll start using the backup node. When the primary node comes back online, it'll return that into service and stop using the backup. As this is a configuration directive, it can't be changed by nginx itself. – dannosaur Sep 6 '18 at 7:20

After more search around, I decided to use OpenResty (https://openresty.org/) for my needs, specifically the LuaUpstreamNginxModule https://github.com/openresty/lua-upstream-nginx-module and with some custom Lua scripts, it seems to work perfectly for my scenario.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.