Nginx proxy and load-balancing overview

Nginx Proxy and Upstream Modules

Nginx continues to gain market share and is probably the most viable open-source HTTP server currently competing against Apache today. With its asynchronous, event-driven architecture, Nginx is able to scale extremely well and can outperform Apache under heavy loads. Couple this with its support for proxying WebSocket protocol, and you’ve got a solid choice for a reverse proxy or load balancer.

These functions are derived from their respective modules, and both Proxy and Upstream are commonly included with system packages. You can confirm that these packages were included by checking the configuration arguments with nginx -V. If the output includes upstream and proxy references, you’re ready to configure them.

Nginx Upstream Configuration

Upstream configuration consists of defining the reverse proxy or load-balancing servers, the balancing methods and associated server weights if you want to change the default of 1. Requests will be distributed between the servers using a weighted round-robin balancing method by default.

You can also configure how many times a server fails prior to being skipped (max_fails, default is 1) for a specific duration (fail_timeout, defaults is 10 seconds and used by max_fails to determine how long before the failure limit resets itself). A backup server can be defined to be used when the primary servers fail.

When using ip_hash, one or more of the load-balancing servers can be marked as permanently unavailable by following the server name with down. It doesn’t use the max_fails or fail_timeout directives.

Nginx Proxy Configuration

With just a few lines, Nginx’s proxy module can be configured to operate as forward/standing or reverse proxy. Both use the proxy_pass directive in the location context.

This may look familiar if you’ve worked with FastCGI, SCGI, memcached, or uwsgi.

There are many additional directives available, that can be used for more advanced configuration.

Forward proxy server

  • Accessing blocked sites over SSL
  • Serving geo restricted content by identifying servers within approved location
  • Caching proxied content to improve speeds to frequently used sites

Reverse proxy server

  • Balancing loads between multiple disparate servers
  • Redirecting traffic to a secondary server when undergoing maintenance or testing on your main one
  • Providing a layer of protection for a real server by allowing access only through designated Nginx servers