iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more
Need a server to try this on? Antihost offers Linux VPS plans with NVMe storage, full root access and a 14-day free trial.
Use iptables as a deny-by-default host firewall: allow loopback, established connections, SSH from a known administration source, and only the application ports your VPS serves; then drop unsolicited inbound and forwarded traffic. Build and test the accept rules before changing default policies, apply the same design separately with ip6tables, and save the result through your distribution’s persistence mechanism.
What iptables protects on a VPS
iptables is the command-line interface to Linux Netfilter packet filtering and network address translation (NAT). A rule matches packet properties—such as protocol, source address, destination port, interface, or connection state—and sends a matching packet to a target. The common terminal targets are ACCEPT, DROP, and RETURN. The Ubuntu iptables(8) manual summarizes the model as: “A firewall rule specifies criteria for a packet and a target.”
| Chain | Traffic examined | Typical VPS use |
|---|---|---|
INPUT |
Packets destined for this server | SSH, HTTP, HTTPS, monitoring, and other services listening on the VPS |
OUTPUT |
Packets generated locally | Updates, DNS lookups, API calls, mail delivery, and return traffic |
FORWARD |
Packets routed through the server | Usually denied on an ordinary host; required only when the VPS routes traffic for a VPN, container network, or another interface |
Most VPS policies are stateful. Netfilter’s connection-tracking subsystem remembers whether a packet belongs to a new, established, or related connection, so a reply can be accepted because it is part of a permitted conversation rather than because every ephemeral return port was opened. Ubuntu describes this as a stateful firewall that “tracks the state of connections and makes decisions based on the context of each packet.” The conntrack userspace tool can inspect or manage tracked connections when deeper diagnosis is needed.
Plan the firewall before changing a remote server
Define the threat model
A host firewall reduces the services reachable from the network. It does not patch vulnerable software, replace SSH authentication, encrypt application traffic, or stop an attacker who already has a valid local account. Your first objective is to expose as few listening services as possible and to restrict administrative access to known sources.
#1 Best Overall
- Used Book in Good Condition
Use the VPS provider’s external firewall or security-group layer as a second boundary when it is available. An external rule can block traffic before it reaches the guest operating system; the in-guest policy still protects the machine if the provider rule is changed, bypassed, or unavailable. Keep the two inventories consistent so that a port opened in one layer is not accidentally assumed to be protected by the other.
Keep a recovery path
A default DROP policy can terminate your only SSH session immediately. Before applying it, confirm that the SSH accept rule is already loaded, leave a second administrative session open, and test from a separate client. Have the provider’s serial console, web console, or rescue environment ready. A restrictive ruleset can also break an application-to-database connection, a VPN tunnel, or a monitoring agent even when SSH still works, so test those paths explicitly.
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallOutdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchInventory actual services and sources
Do not open a port because it is conventional; open it because a service on this VPS needs it. Record the listening address, transport protocol, intended clients, and whether access should be limited to an administration network.
| Service or path | Typical rule | Scope to decide |
|---|---|---|
| SSH administration | TCP 22, or your configured SSH port | One office/VPN public address or a narrowly defined management subnet |
| HTTP | TCP 80 | Public only when the server deliberately redirects or serves HTTP |
| HTTPS | TCP 443 | Public when the application is internet-facing |
| DNS client lookups | UDP and, when needed, TCP 53 outbound | Usually handled by an outbound policy; restrict destinations if your design requires it |
| Monitoring | The exact port and protocol used by your agent | Monitoring collector addresses only |
| VPN | The protocol and port of the chosen VPN | Public or limited to peers, plus forwarding rules if the VPS routes VPN traffic |
| Application or database | The service’s actual TCP/UDP port | Prefer private addresses or specific application hosts; never expose a database merely for convenience |
Inspect and back up the current rules
Inspect before editing. A fresh Ubuntu installation may show ACCEPT policies with no meaningful rules; that is an unprotected baseline, not proof that the server is secure.
sudo iptables -L
sudo iptables -L -v -n --line-numbers
sudo iptables-save
The first command gives a readable listing. The verbose, numeric form shows packet and byte counters without doing reverse DNS lookups and includes rule numbers for later deletion. Save a rollback copy somewhere accessible through the console as well as in your normal backup system:
sudo iptables-save | sudo tee ~/iptables-before-change.rules > /dev/null
Also record the current IPv6 policy; IPv4 output tells you nothing about IPv6:
Rank #2
sudo ip6tables -L -v -n --line-numbers
sudo ip6tables-save | sudo tee ~/ip6tables-before-change.rules > /dev/null
Build a safe IPv4 policy
The following sequence is deliberately ordered. Add the rules that preserve administration and existing conversations first. Only after you have verified them should you change the chain policies.
1. Set an administration source
Use a documentation address in examples and substitute the public address or subnet from which you actually administer the VPS. A single fixed address is narrower than an entire corporate range.
ADMIN_IP=203.0.113.10
If your management address changes frequently, use a VPN or provider console rather than opening SSH to the entire internet. If SSH listens on a nonstandard port, substitute that port in every command below; changing the port alone is not a security boundary.
2. Permit loopback traffic
Local services commonly communicate through the loopback interface. Permit both directions before applying restrictive policies:
Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Fix the driver behind crashes, sound loss and screen glitches3Repair Windows errors before they cause bigger problemssudo iptables -A INPUT -i lo -j ACCEPT
sudo iptables -A OUTPUT -o lo -j ACCEPT
3. Permit established and related traffic
This stateful rule allows replies to connections that the host has already accepted and protocols related to those connections:
sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
sudo iptables -A OUTPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
Keeping the outbound rule explicit makes the policy understandable even when you later tighten OUTPUT. If you intentionally use a stateless design, you must account for both directions and every required return path yourself.
Rank #3
4. Allow SSH only from the intended source
Add a new-connection rule for the source you recorded. The source restriction is the important part:
sudo iptables -A INPUT -p tcp -s 203.0.113.10/32 --dport 22
-m conntrack --ctstate NEW -j ACCEPT
For a management subnet, use its real CIDR instead of /32. If you administer through a VPN, allow the VPN’s address range or the VPN interface according to your topology. Test a second SSH connection from that source while the original session remains open.
Recommended Free Tools
5. Open only the public application ports
For a web server that intentionally serves both HTTP and HTTPS, one multiport rule is concise:
sudo iptables -A INPUT -p tcp -m multiport --dports 80,443
-m conntrack --ctstate NEW -j ACCEPT
Remove port 80 if the server should accept HTTPS only. For a private application, add a source restriction just as you did for SSH:
sudo iptables -A INPUT -p tcp -s 198.51.100.25/32 --dport 8443
-m conntrack --ctstate NEW -j ACCEPT
Replace the example address and port with the actual caller and listener. Do not publish database ports, administration dashboards, or monitoring endpoints unless their clients and authentication model require network access.
6. Add forwarding rules only when the VPS routes traffic
An ordinary web or application VPS does not need to forward packets. Keep forwarding denied. A VPN gateway, router, or host using a container network needs a documented forwarding policy: permit only the source, destination, interface, and protocol required, and retain the established/related rule for return traffic. The generic forwarding default should not be changed to ACCEPT merely to make an application work; identify the missing path first.
Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Rank #4
7. Set default policies after validation
Once SSH and every required service has been tested from its intended client, set the defaults:
sudo iptables -P INPUT DROP
sudo iptables -P FORWARD DROP
sudo iptables -P OUTPUT ACCEPT
This leaves ordinary outbound activity available while unsolicited inbound and routed traffic are denied. If your threat model requires restricted egress, inventory update servers, DNS resolvers, time sources, APIs, mail relays, and other destinations before changing OUTPUT; an outbound DROP policy without those exceptions can silently break the system.
8. Review the resulting order and counters
sudo iptables -L -v -n --line-numbers
Rules are evaluated from the top of a chain downward. A broad earlier ACCEPT can make a later restriction ineffective, while an early DROP can prevent a later service rule from ever matching. Counters increase when traffic reaches a rule, which helps distinguish an unused rule from a client that never sent traffic to the VPS.
The Tool Desk
Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Apply an equivalent IPv6 policy
iptables manages IPv4; ip6tables manages IPv6. They are separate policy surfaces. If the VPS has a public IPv6 address, an IPv4-only firewall does not protect that address. Repeat the inventory, source restrictions, service rules, and default policies with the IPv6 commands.
sudo ip6tables -A INPUT -i lo -j ACCEPT
sudo ip6tables -A OUTPUT -o lo -j ACCEPT
sudo ip6tables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
sudo ip6tables -A OUTPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
sudo ip6tables -A INPUT -p tcp -s 2001:db8:1234::10/128 --dport 22
-m conntrack --ctstate NEW -j ACCEPT
sudo ip6tables -A INPUT -p tcp -m multiport --dports 80,443
-m conntrack --ctstate NEW -j ACCEPT
sudo ip6tables -P INPUT DROP
sudo ip6tables -P FORWARD DROP
sudo ip6tables -P OUTPUT ACCEPT
The 2001:db8::/32 network is reserved for documentation; replace it with the real management prefix. IPv6 also depends on ICMPv6 for neighbor discovery and path operation. If you use a restrictive IPv6 policy, permit the ICMPv6 types required by your network rather than blocking ICMPv6 wholesale. Test SSH, web access, and any application endpoint over IPv6 from an independent IPv6-capable client.
Save rules so a reboot does not erase them
Commands entered with iptables change the running kernel configuration. They can disappear at reboot unless a persistence service or boot configuration loads them again. Use the persistence mechanism supported by your distribution and verify that it actually restores the rules on startup.
Best Value
Ubuntu examples commonly store the IPv4 snapshot at /etc/iptables/rules.v4; an IPv6 snapshot is normally kept separately. After final testing, export the active rules to the file used by your configured loader:
sudo iptables-save | sudo tee /etc/iptables/rules.v4 > /dev/null
sudo ip6tables-save | sudo tee /etc/iptables/rules.v6 > /dev/null
Writing the files alone does not guarantee restoration. Confirm that the distribution’s persistence service is installed, enabled, and configured to load those files, then perform a planned reboot or use the service’s reload operation during a maintenance window. Ubuntu 22.04 can expose iptables syntax through an nftables backend, so inspect which backend your system uses and avoid assuming that an interactive command and a persistence workflow are identical.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Verify from outside the VPS and document rollback
Test every intended path
- From a second SSH client on the approved administration source, open a new session.
- From an unapproved source, confirm that SSH is refused or times out as expected.
- Connect to each public application port from an independent client and verify the application, not merely that the TCP handshake succeeds.
- Exercise outbound functions such as package updates, DNS resolution, API calls, monitoring, and mail if the server uses them.
- If the VPS routes VPN or other traffic, test both directions and confirm that forwarding counters increase only on the intended rules.
- Repeat the tests over IPv6 when the VPS advertises an IPv6 address.
- Recheck counters and save the tested configuration after any correction.
Recover from a lockout
Use the provider console or rescue environment rather than repeatedly retrying SSH. Restore the backup snapshots you made before editing:
sudo iptables-restore < ~/iptables-before-change.rules
sudo ip6tables-restore < ~/ip6tables-before-change.rules
If the backup is unavailable, a console session can temporarily restore access by setting permissive policies, adding a verified SSH rule, and then rebuilding the policy in the correct order:
sudo iptables -P INPUT ACCEPT
sudo iptables -P FORWARD ACCEPT
sudo iptables -P OUTPUT ACCEPT
Use that emergency state only while connected through the trusted console. Recreate and test the least-privilege rules before returning to production; leaving all policies at ACCEPT defeats the purpose of the firewall.
Choose between iptables, nftables, and ufw
Modern Ubuntu documentation identifies nftables as the successor to the iptables component in Netfilter. Ubuntu’s iptables package can nevertheless provide the familiar iptables command syntax while using an nftables backend. The right interface depends on whether you need a simple policy or granular packet logic.
| Interface | Abstraction level | IPv4 and IPv6 | Expressiveness | Persistence and migration considerations |
|---|---|---|---|---|
| Direct iptables/ip6tables | Low-level, widely documented command interface | Separate commands and rule sets | Detailed matches, chains, connection state, NAT, and packet conditions | Save and restore through the distribution’s supported mechanism; verify whether commands use a legacy or nftables backend |
| nftables | Current Netfilter rule framework | Can express both families in one ruleset design | Rich sets, maps, concatenated matches, and explicit chain policies | Use the operating system’s nftables service and native configuration; plan migration instead of mixing unmanaged rule sources |
| ufw | Simplified frontend for common host policies | Provides higher-level IPv4/IPv6 rules when enabled and configured | Convenient allow/deny profiles, less direct control over complex packet conditions | Let ufw own the policy if you choose it; avoid conflicting manual rules that make troubleshooting and persistence ambiguous |
Choose ufw when your needs are a small set of allow/deny rules and you value a simpler command surface. Choose nftables for a new granular design on a current distribution. Use direct iptables commands when you must maintain an existing ruleset, follow software documentation written for that interface, or need its familiar match and chain model. In every case, the lockout precautions, separate IPv6 review, independent testing, and persistence checks remain necessary.
Troubleshoot the failures that matter most
SSH worked until the policy changed
- Use the console or a still-open session to list rules with line numbers.
- Confirm the SSH rule has the correct source address, port, protocol, and interface.
- Check that the rule appears before any drop rule and that its counter increases during a connection attempt.
- Remember that a changing home or office address can make a previously correct
/32rule obsolete.
The website is unreachable but SSH works
- Confirm that the service is listening on the expected address and port.
- Check that both TCP 80 and TCP 443 were opened only when both are required.
- Inspect counters to see whether packets reach the intended rule.
- Check the provider firewall layer as well as the guest policy; either layer can block the connection.
An application cannot reach its database or external API
- Identify whether the connection is local, routed through
FORWARD, or outbound throughOUTPUT. - Verify that the database source address and port are explicitly allowed when the database is on another host.
- Confirm that established/related rules are present so replies are accepted.
- Do not solve an unknown path by changing all policies to
ACCEPT; trace the required direction and add the narrow rule.
IPv6 remains reachable after IPv4 is locked down
- List
ip6tablesrules and policies independently. - Apply the same source restrictions and service decisions to IPv6.
- Test from an IPv6 client and account for required ICMPv6 operation.
- If IPv6 is not part of the deployment, disable or remove the public address through the provider and operating-system configuration rather than assuming an IPv4 firewall covers it.
The rules disappear after reboot
- Compare the live output of
iptables -L -v -nwith the saved files. - Check that the persistence package or service is installed, enabled, and loading the files at boot.
- On Ubuntu 22.04, determine whether the iptables command is using the nftables backend and keep the persistence workflow consistent with that choice.
- After a controlled reboot, repeat the external tests instead of treating a successful boot as proof that the policy was restored correctly.
A practical maintenance routine
Firewall work is a change-management task, not a one-time command. Keep a short record of every allowed port, its business owner, permitted sources, the date it was added, and the rule or configuration file that implements it. Remove exceptions when services are retired. Review counters periodically for rules that never match, because unused rules often indicate stale documentation or an unnecessary exposure. Before kernel, network, VPN, container, or SSH changes, repeat the inventory and keep console access available.
For a typical Linux VPS, the durable pattern is simple: expose only required services, constrain management sources, preserve loopback and stateful return traffic, deny unsolicited inbound and forwarding traffic, treat IPv6 as an equal policy surface, and verify recovery before you need it.
Free tools Windows power users keep installed
One-click scans. No signup required.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

