Monday, 15 September 2014

Nginx service failover to 1x1 gif with timeout

That's what I love nginx for. Really simple and declarative. At 8086 we have a service that is non-stable, at 8091 there is virtual gif substitutor. On 300ms timeout there will be 1x1 gif as a response. Nginx resides on 8090 for presentation.

http {
  include mime.types;
  default_type application/octet-stream;
  upstream backend {
    server localhost:8086;
    server localhost:8091 backup;
  }
  server {
    listen 8090;
    server_name localhost:8090;
    location /sf.gif { empty_gif; }
    location / {
      proxy_pass http://backend;
      proxy_next_upstream error timeout
        invalid_header http_500 http_502 http_503
        http_504 http_403 http_404;
      proxy_connect_timeout 300ms;
      proxy_set_header Host $host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For
        $proxy_add_x_forwarded_for;
      proxy_redirect off;
    }
  }
  server {
    listen 8091;
    server_name localhost:8091;
    location / {
      rewrite ^ http://localhost:8090/sf.gif redirect; }
    location ^ {
      rewrite ^ http://localhost:8090/sf.gif redirect; }
  }
}