How To Migrate Iptables Firewall Rules to a New Server

Try it in our public cloud & Get $5 Credit
CLAIM NOW

This guide will go over the basic steps you should take in order to transfer firewall rules from one server to another.

Getting started

You’ll need the following in place before getting started with this guide:
• 2 Node (Cloud Server or Dedicated Server)

You’ll be transferring rules from one to another, so if you like, make sure they each have different firewall rules before beginning the guide so as to demonstrate its effectiveness.

Tutorial

First, check current iptables rules on server1.

iptables -S

Output Sample:

-P INPUT ACCEPT
-P FORWARD ACCEPT
-P OUTPUT ACCEPT
-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 443 -j ACCEPT
-A INPUT -s 1.2.3.4/32 -j DROP

You have the option to save server1’s iptables rules to a file. This is the command to do so.

iptables-save > iptables-rules-file

Now you can copy the file from server1 to server2. This is really all you’ll need to reinstate the rules on the other server.

scp iptables-rules-file root@ip.of.server.2:/root

Restore the rules on server2 from the file you just transferred.

iptables-restore < /root/iptables-rules-file

Review your iptables rules on server2 to make sure that they were indeed copied over.

iptables -S

Here's a sample of the output you should expect to see.

-P INPUT ACCEPT
-P FORWARD ACCEPT
-P OUTPUT ACCEPT
-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 443 -j ACCEPT
-A INPUT -s 1.2.3.4/32 -j DROP

Conclusion

With that, you should now have successfully migrated your iptables rules from one server to another. Refer to the man pages for iptables to get an idea of what else you can do with this versatile program. If you liked this KB article, please share it with your friends.