Make your `iptables` rules permanent

发布于:2024-10-13 ⋅ 阅读:(114) ⋅ 点赞:(0)

$ sudo iptables -t nat -L -v -n

Chain PREROUTING (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination         
   79  4390 DNAT       tcp  --  enp1s0 *       0.0.0.0/0            0.0.0.0/0            tcp dpt:24662 to:10.8.0.2:24662
 6986  538K DNAT       udp  --  enp1s0 *       0.0.0.0/0            0.0.0.0/0            udp dpt:24672 to:10.8.0.2:24672
   10   568 DNAT       tcp  --  enp1s0 *       0.0.0.0/0            0.0.0.0/0            tcp dpt:10647 to:10.8.0.4:10647
  339 26148 DNAT       udp  --  enp1s0 *       0.0.0.0/0            0.0.0.0/0            udp dpt:10523 to:10.8.0.4:10523

Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination         

Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination         

Chain POSTROUTING (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination         
26591 3302K MASQUERADE  all  --  *      enp1s0  10.8.0.0/24          0.0.0.0/0   

To make your iptables rules permanent so that they persist after a reboot, you can use the iptables-persistent package or manually save and restore the rules. Here are two common approaches:

Method 1: Using iptables-persistent (Recommended)

  1. Install the package:

    sudo apt-get update
    sudo apt-get install iptables-persistent
    

    During the installation, it will prompt you to save your current iptables rules.

  2. If you need to save the rules manually at any point:

    sudo netfilter-persistent save
    
  3. The rules are now saved in /etc/iptables/rules.v4 for IPv4 and /etc/iptables/rules.v6 for IPv6. These rules will be automatically applied after each reboot.

Method 2: Manual Save and Restore

  1. Save the current iptables rules to a file:

    sudo iptables-save > /etc/iptables/rules.v4
    
  2. To restore the rules automatically after reboot, edit the /etc/rc.local file and add the following line before exit 0:

    iptables-restore < /etc/iptables/rules.v4
    
  3. Ensure that the /etc/rc.local file is executable:

    sudo chmod +x /etc/rc.local
    

Now, your iptables rules should be loaded automatically after every reboot.

eMule firewall config - iptables forward rules
Remove a rule from iptables