Persistence: Making iptables Changes Stick

Tutorials · Published 2019-08-24 · Revised 2026-11-14
Author-approved revision; target-platform validation outstanding · Joomla source

12,449 Total views across this article’s versions; includes the historical baseline where available.

One of the challenges of iptables, routes, and rules (iprules) is making changes to them permanent. Any changes you make on-the-fly only last until the next system restart. However, there are several ways of making them persist through reboots.

Choose one of the methods below to store your changes in user-manageable scripts that are run every time your server is restarted.

Method #1: systemd Start-Up Process

This method uses two services: one to establish the firewall before normal network configuration, and another to apply routing policy after the interface and source address are ready. The demonstrated network manager is NetworkManager, with a dependency that requires successful firewall startup. The original example was written on Ubuntu 16.04. This revised design still needs validation on the system where you intend to use it.

If you don’t know what systemd is, first read What Is systemd?

Prepare the Two Scripts

First, prepare and test both scripts using Testing Your iptables Rules. The firewall script is /etc/iptables-script.sh; the routing script is /etc/routing-script.sh. They run independently. Remove the old call to the routing script from the firewall script if you’re adapting the earlier combined example.

The firewall sample is an outline. Supply your actual rules and checks before using it. Its placeholder deliberately fails, even if you set the review flag to yes. Early rules must work without DNS, an assigned address, or a remote connection, and permit required network-setup traffic. Cover every address family your server uses.

The routing example expects a configured source address and a directly attached gateway. Check that NetworkManager-wait-online.service participates in startup and that the relevant connection profile requires the IPv4 address you need. Startup completion can include disconnected devices, and a dual-stack profile may otherwise count as activated when only IPv6 is ready. The routing script’s source-address check remains necessary. Keep the dedicated table and rule priority under one owner’s control, and don’t run manual and service-driven updates simultaneously.

Use one owner for each set of firewall rules. Don’t enable this custom firewall service and the persistence plugins in Method #2 to restore competing versions of the same rules.

How the Startup Stages Fit Together

  1. The firewall service applies the reviewed policy before network-pre.target.
  2. NetworkManager starts only after successful firewall service activation, then configures its managed interfaces and addresses.
  3. The routing service runs after network-online.target and successful firewall service startup.

network-online.target is a startup checkpoint, not a continuing connectivity test. An early firewall rule that prevents address assignment can also prevent the routing stage from becoming ready.

The routing dependency and the NetworkManager drop-in below both require successful firewall startup. The drop-in belongs to NetworkManager.service, not to network-online.target or its wait-online service.

This ordering covers normal host network configuration by services that honor these targets. It doesn’t establish protection for networking already started in an initial RAM filesystem or outside that startup sequence. Confirm the local boot arrangement and your independent recovery access before deployment.

Create the Early Firewall Service

Run the administrative commands below from a root shell. An account with sudo access can open one with:

sudo -i

Create the firewall unit, inspecting any existing file before replacing it:

nano /etc/systemd/system/datahacker-firewall.service
[Unit]
Description=Apply the reviewed early firewall policy
DefaultDependencies=no
After=local-fs.target systemd-modules-load.service
Wants=network-pre.target
Before=network-pre.target shutdown.target
Conflicts=shutdown.target

[Service]
Type=oneshot
RemainAfterExit=yes
User=root
Environment=PATH=/usr/sbin:/usr/bin:/sbin:/bin
ExecStart=/etc/iptables-script.sh

[Install]
WantedBy=multi-user.target

DefaultDependencies=no allows this unit to participate in early startup. Its explicit ordering waits for local filesystems and the module-loading service, and places it before network configuration and shutdown. The script, interpreter, tools, and policy files must be available locally at that point; don’t make this stage depend on a network mount. Verify the command search path on your system.

Create the Routing Service

Create the separate routing unit:

nano /etc/systemd/system/datahacker-routing.service
[Unit]
Description=Apply the reviewed routing policy
Requires=datahacker-firewall.service
Wants=network-online.target
After=datahacker-firewall.service network-online.target

[Service]
Type=oneshot
RemainAfterExit=yes
User=root
Environment=PATH=/usr/sbin:/usr/bin:/sbin:/bin
ExecStart=/etc/routing-script.sh

[Install]
WantedBy=multi-user.target

Requires and After together make routing wait for successful firewall activation. The routing script still checks its source address. Reaching the online target doesn’t prove that your chosen gateway or destination is reachable.

Both services use Type=oneshot and retain an active (exited) state after successful completion. That records the last service run; it isn’t a monitor of the installed rules. A nonzero script result fails its service. No automatic retry or cleanup is defined, and earlier successful changes may remain after a later failure.

Require Firewall Success Before Network Startup

Running the firewall first establishes an order, but it doesn’t necessarily stop the network from coming up if the firewall fails.

If you want successful firewall startup to be a prerequisite, add the dependency to the service that actually configures your network. Identify that service before adapting the example; the service name depends on your system.

Here, we’re using NetworkManager.service. Confirm that it is installed and manages the intended interfaces. These inspection commands don’t change network configuration:

systemctl cat NetworkManager.service
nmcli device status
systemctl is-enabled NetworkManager-wait-online.service

If another service manages the network, don’t enable NetworkManager merely to match this example. Adapt and validate the dependency for that service instead. Checking whether wait-online is enabled also doesn’t prove that its connection profiles wait for your required address.

Create this drop-in directory and file. Inspect any existing firewall.conf and preserve its contents before making changes:

mkdir -p /etc/systemd/system/NetworkManager.service.d
nano /etc/systemd/system/NetworkManager.service.d/firewall.conf
[Unit]
Requires=datahacker-firewall.service
After=datahacker-firewall.service

Requires pulls in the firewall service; After makes NetworkManager wait for its activation to finish. A reported firewall startup failure prevents NetworkManager from starting through this unit. Missing configuration must fail the firewall script, not silently skip the service through a Condition setting.

This deliberately trades availability for protection. A mistake in the firewall configuration may leave the server without its normal network connection. Make sure your recovery access works before enabling the dependency.

Test both outcomes in an isolated environment: successful firewall startup should allow network configuration to proceed, while a reported firewall failure should prevent the network-management service from starting. Then confirm that you can correct the failure and recover through the independent console.

Remember, this is a startup requirement, not continuous verification of your firewall rules.

Check the Units and Test Each Stage

Make the unit files root-owned and readable:

chown root:root /etc/systemd/system/datahacker-firewall.service /etc/systemd/system/datahacker-routing.service /etc/systemd/system/NetworkManager.service.d/firewall.conf
chmod 644 /etc/systemd/system/datahacker-firewall.service /etc/systemd/system/datahacker-routing.service /etc/systemd/system/NetworkManager.service.d/firewall.conf

Check the two definitions and NetworkManager with its drop-ins. Address reported errors before continuing; this is not a traffic test:

systemd-analyze verify datahacker-firewall.service datahacker-routing.service NetworkManager.service

Reload the definitions, then inspect the effective NetworkManager configuration. Confirm that both dependency lists include datahacker-firewall.service:

systemctl daemon-reload
systemctl cat NetworkManager.service
systemctl show NetworkManager.service -p Requires -p After

Reloading doesn’t restart an already running NetworkManager or undo existing network configuration. Don’t treat it as a test of the startup requirement. Start and inspect the firewall stage:

systemctl start datahacker-firewall.service
systemctl status datahacker-firewall.service --no-pager
journalctl -u datahacker-firewall.service -b --no-pager

Check the actual firewall policy before proceeding. Once it is correct and the required address is configured, test the routing stage:

systemctl start datahacker-routing.service
systemctl status datahacker-routing.service --no-pager
journalctl -u datahacker-routing.service -b --no-pager

Repeat the traffic and new administrative-connection checks from the testing article. Test failures and repeated runs in an isolated environment. A manual service start after the network is already up doesn’t prove that early boot ordering works.

For an already active unit, start doesn’t rerun the script. Use restart for an intentional repeated-run test. Routing can be restarted without rerunning a successful active firewall stage. With this drop-in, stopping or restarting the required firewall unit can also affect NetworkManager and the routing service. Perform that maintenance through your independent console, inspect all three afterward, and start required services again if needed. Stopping the manager does not guarantee that previously configured interfaces lose connectivity.

Enable Startup and Verify After Reboot

If you used the earlier combined rules.service, inspect it and remove its startup links once the replacements are ready and tested. For that specific old unit, systemctl disable rules.service removes those links without undoing its network changes. Don’t leave the combined and split examples enabled together.

After both stages pass their checks, enable them for subsequent boots:

systemctl enable datahacker-firewall.service datahacker-routing.service
systemctl is-enabled datahacker-firewall.service datahacker-routing.service

Reboot with your recovery access available. Inspect both service logs and NetworkManager’s boot ordering, then repeat the firewall, routing, traffic, and new-connection checks. Verify that firewall completion preceded NetworkManager activation and that routing ran after its required address was available.

In the isolated failure test, use a genuine nonzero firewall exit and a fresh activation or boot; an already active firewall unit can hide the scenario you’re trying to test. Check that NetworkManager and routing did not start. From the console, correct the firewall, verify its successful activation, then start NetworkManager and routing in that order. If the drop-in itself must be rolled back, restore its previous contents or remove only the newly added firewall.conf, then reload definitions. Preserve unrelated drop-ins.

Neither service has ExecStop cleanup. Stopping or disabling them doesn’t flush firewall rules or remove routes. Use the reviewed recovery procedure when you need to undo changes.

Method #2: netfilter-persistent and iptables-persistent

This method uses the netfilter-persistent and iptables-persistent packages to restore saved firewall rules during startup. The instructions here are intended for Debian-based systems that provide these packages.

The original examples and screenshots were created on Ubuntu 16.04. Package versions, installation prompts, and startup configuration may differ on your system.

Before following the installation steps, check that your distribution provides the packages and review how it starts them.

Method #2 is an alternative to Method #1 for managing firewall rules. The NetworkManager dependency drop-in in Method #1 specifically requires our custom datahacker-firewall.service. It does not provide the same startup protection for this alternative.

Firewall Rules and Routing Policy

There is an important distinction here. The IPv4 and IPv6 plugins supplied by iptables-persistent save and restore firewall rules. They do not save the routing-policy rules you create with ip rule, or the routing-table entries you create with ip route.

The files /etc/iptables/rules.v4 and /etc/iptables/rules.v6 contain the corresponding firewall rulesets. They are not shell scripts, so adding ip rule or ip route commands to these files will not make those commands run at startup.

If your configuration includes custom routing policy, you need to make that persistent separately.

In Method #1, that is the purpose of /etc/routing-script.sh and its separate routing service. The firewall stage runs before normal network configuration, while the routing stage waits until the required interface and source address are ready.

Method #2 covers firewall-rule persistence only. If you choose this method and also need custom routing policy, you must arrange for those routing rules and routes to be restored separately. Remember that the routing service shown in Method #1 specifically depends on our custom firewall service; it cannot be reused unchanged as an independent companion to Method #2.

How the Two Programs Work Together

How does it work? On a system using the packaged systemd service, that service starts netfilter-persistent during boot. The program calls its installed plugins to perform the requested operation, then exits. It isn’t a background daemon launched by the kernel’s netfilter code.

The iptables-persistent package supplies the plugins that load and save IPv4 and IPv6 firewall rules. That division of responsibility is useful to keep in mind: netfilter-persistent runs the plugins, while the plugins handle the particular rulesets.

Load and Save on Demand

You can also save or load your firewall rules without restarting the device. The distinction matters: saving copies the rules currently in use to disk, while loading restores the saved rules into the active firewall.

Before saving, make sure the current rules are the ones you want to keep. Saving replaces the previous contents of the corresponding rules files.

To save the current rules, run:

sudo netfilter-persistent save

To load the saved rules, run:

sudo netfilter-persistent start

These commands call the installed plugins. With the IPv4 and IPv6 plugins supplied by iptables-persistent, each handles its corresponding ruleset according to its configuration. You do not choose IPv4 or IPv6 from a prompt each time, and you do not need to run the command twice to request both.

Installation Walk-Thru

First, prepare and test your iptables rules. The screenshots below come from the original Ubuntu 16.04 example.

Verify netfilter-persistent is available:

Checking whether netfilter-persistent is installed

Install iptables-persistent as root:

apt install -y iptables-persistent

In the original installation example, selecting Yes at the first prompt saves the current IPv4 rules in /etc/iptables/rules.v4.

Installation prompt to save IPv4 rules

Selecting Yes at the second prompt saves the current IPv6 rules in /etc/iptables/rules.v6.

Installation prompt to save IPv6 rules

Here is the post-installation output from Ubuntu 16.04:

Post-installation output on Ubuntu 16.04

Check that your rules were saved. This screenshot shows the IPv4 file:

Saved IPv4 rules

Verify Rules Are Restored After a Reboot

After restarting the device, check that the intended rules are active. A successful startup message is useful, but it does not establish that every rule was restored or that traffic behaves as intended.

Before rebooting, keep a separate copy of your tested configuration for comparison. For Method #2, confirm that the saved files contain the rules you intend to restore. Have the recovery access described earlier available before testing.

After rebooting, inspect the system before manually loading rules or restarting services. Otherwise, you may correct a startup failure without realizing it occurred.

Check the Startup Results

For Method #1, inspect both services and their messages from the current boot:

sudo systemctl status datahacker-firewall.service datahacker-routing.service
sudo journalctl -b -u datahacker-firewall.service -u datahacker-routing.service

For Method #2 on a system using the packaged systemd service:

sudo systemctl status netfilter-persistent.service
sudo journalctl -b -u netfilter-persistent.service

Look for failed commands, missing rules files, or skipped operations. Remember that these services perform startup tasks and then exit; they do not need a continuously running process to have completed successfully.

Check the Active Firewall Rules

Display the active IPv4 and IPv6 rulesets:

sudo iptables-save
sudo ip6tables-save

Despite their names, these commands display the rules here. Without a filename or output redirection, they do not overwrite your saved rules files.

Compare the output with your tested configuration. For Method #2, also compare it with /etc/iptables/rules.v4 and /etc/iptables/rules.v6. Check the expected tables, chains, default policies, rule order, and rule contents. Include any NAT or mangle rules your configuration uses.

Timestamps and packet counters may differ. Other software may also add rules, but unexpected differences still need an explanation. An empty listing or a missing expected table is not a successful verification.

Use the same iptables backend that your startup configuration uses when making these comparisons.

Check Routing Policy Separately

If you configured custom routing policy, verify its rules and routing table as well. For the IPv4 example in Method #1, replace TABLE_ID, DESTINATION_IP, and SOURCE_IP below with your actual values:

ip -4 rule show
ip -4 route show table TABLE_ID
ip -4 route get DESTINATION_IP from SOURCE_IP

Confirm the intended rule priority, source-address match, and selected table. Check that the table contains the expected routes and that the route lookup selects the intended gateway and interface.

The route lookup does not send traffic. It shows the routing decision for the supplied addresses.

Test the Intended Behavior

Finally, repeat the traffic tests used before rebooting. Confirm that permitted connections work and that connections intended to be blocked are blocked. Test IPv4 and IPv6 wherever your configuration supports them, using another device when checking access to this server.

If a check fails, investigate before saving again. Saving at this point could replace your known-good rules with the incomplete configuration you are trying to diagnose.

Revisit the Package-Configuration Prompts

The prompts shown in the installation screenshots are part of package configuration. They ask whether you want to save the current IPv4 and IPv6 rules.

To revisit those prompts after installation, run:

sudo dpkg-reconfigure iptables-persistent

This reconfigures the installed package. It is not the command for simply loading your saved rules. The prompts and their appearance may differ with the package version and your system’s configuration.

Download the Example Files

These are the same examples shown above. Review and configure them before use.