Automatic Failover and Maintenance Pages with iptables

Using iptables for automatic failover or maintenance pages might seem like a strange choice, but it works!

iptables has an obscure but useful feature, the socket filter. From the man page:


This matches if an open socket can be found by doing a socket lookup on the packet.

In other words, we can use this filter to redirect incoming connections to a “failover” server when the main server.

This can be accomplished with a couple iptables commands:

sudo iptables -A PREROUTING -t nat -i <interface> -p tcp --dport <server port> -m socket -j ACCEPT
sudo iptables -A PREROUTING -t nat -i <interface> -p tcp --dport <server port> -j REDIRECT --to-port <failover port>

What these rules do is let through a connection when there is a server listening on the port, otherwise, redirect it to a failover server listening on a separate port.

The error message used by this website.
The error message used by this website.
I can think of a few ways to use this. For example, sometimes, I need to restart the nginx server that fronts this website, such as for configuration changes. During the few seconds when Docker is recreating the nginx container, users trying to visit the site get an ugly “connection refused” error. Instead of driving users away, the server can automatically show users a prettier error message using a small Node.js server telling them to refresh in a few seconds.

While proxies like haproxy also work, I needed a quick and lightweight way to automatically display a maintenance page. iptables does the job beautifully.

There might be many ways to use this iptables feature. Share your ideas in the comments below!

2 thoughts on “Automatic Failover and Maintenance Pages with iptables”

  1. Are you a MaxCDN employee? I think they use iptables too. This seems to be some kind of a patch for what occurs naturally. Creating a fail-safe feedback loop. Good idea. Setting it up would require some careful port analysis. I wonder if this works on a local Mac publishing to a shared hosting service, or even just authoring files pre-publish? Intrinsic value.

Comments are closed.