Rolling updates of backend with udp server sockets

Solution 1:

You can do this with iptables. To create a port forwarding from 17X to 16X:

iptables -A PREROUTING -t nat -p tcp -m tcp --dport 16012 -j DNAT --to-destination :17012
iptables -A PREROUTING -t nat -p udp -m udp --dport 16002 -j DNAT --to-destination :17002

Then when you want to switch which port it is pointing to after you have started up the updated version of your app:

iptables -D PREROUTING -t nat -p tcp -m tcp --dport 16012 -j DNAT --to-destination :17012
iptables -D PREROUTING -t nat -p udp -m udp --dport 16002 -j DNAT --to-destination :17002
iptables -A PREROUTING -t nat -p tcp -m tcp --dport 16012 -j DNAT --to-destination :18012
iptables -A PREROUTING -t nat -p udp -m udp --dport 16002 -j DNAT --to-destination :18002

If you are on a distro using an iptables.service and you want these changes to be permanent, you can add the -A lines to /etc/sysconfig/iptables or wherever your config file is located. If you are using a distro that makes use of a firewalld.service then you can achieve the same goal and have it be permanent across reboots this way:

This first line is only needed once to enable masquerading in general

firewall-cmd --permanent --add-masquerade

Then to create your initial forwardings:

firewall-cmd --permanent --add-forward-port=port=16002:proto=udp:toport=17002
firewall-cmd --permanent --add-forward-port=port=16012:proto=tcp:toport=17012

When you want to change the application to listening on a different port, just run:

firewall-cmd --permanent --remove-forward-port=port=16002:proto=udp:toport=17002
firewall-cmd --permanent --remove-forward-port=port=16012:proto=tcp:toport=17012
firewall-cmd --permanent --add-forward-port=port=16002:proto=udp:toport=18002
firewall-cmd --permanent --add-forward-port=port=16012:proto=tcp:toport=18012