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:
socket
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.
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!
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.
Great idea — simple, too.