I'm having trouble configuring nginx.

I'm using nignx as a reverse proxy. I want to send my all requests to my first server. If the first server is down, I want to send requests to second server.

In short, how can I have a failover solution without load balancing?


Solution 1:

What you want is an active+passive setup. Here's an example nginx conf snippet to get you going:

upstream backend {
    server 1.2.3.4:80 fail_timeout=5s max_fails=3;
    server 4.5.6.7:80 backup;
}

server {
    listen 80;
    server_name whatevs.com;

    location / {
        proxy_pass http://backend;
    }
}

So, 'normally', all requests will go to host 1.2.3.4. If we get three failures to that box, then 4.5.6.7 will take over.

Solution 2:

Extending chrskly's answer, you might want to configure 3 flags/configs.

  1. fail_timeout : Total time by failed attempts and also mark the server as DOWN for that same time. If 5 sec, then will try max_fail attempts in 5 secs and if still fails, mark that server as DOWN for 5 sec.
  2. max_fail : Maximum number of tries
  3. proxy_connect_timeout : The amount of time to wait for a connection.

In following GRPC example, if main server can't be connected in 7 sec, then switch to backup and mark main server as down for 6000s:

upstream grpcservers {
    server 192.168.0.XX:9997 fail_timeout=6000s max_fails=1;  # After 1 fail in 6000s, Main server is marked unavailable for 6000s.
    server 192.168.0.XX:9999 backup;
        } 
location / {
            grpc_pass grpc://grpcservers;
            grpc_connect_timeout 7s;  # If conn cant be made in 7sec, switch to backup
        }