21

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?

mikemaccana
  • 3,070
  • 5
  • 24
  • 29
Serhat
  • 333
  • 1
  • 2
  • 6

3 Answers3

23

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.

chrskly
  • 1,539
  • 11
  • 16
3

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
        }

0

Load balancing in nginx is very easy we are just configure server names in upstream scope, where we write server list for load balancing.
nginx support different algorithm for load balancing by default it is round robine, but we configure it with different keys like ip_hash...

http{
 upstream servername{
    ip_hash//for sticky hash
    least_conn//FOR least connection 
    sever localhost:1001;
    sever localhost:1002;
    sever localhost:1003;
}
alexander.polomodov
  • 1,060
  • 3
  • 10
  • 14