DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk11 min

Iptables Tutorial: Firewall Rules for Your Linux VPS

A practical iptables tutorial for Linux VPS administrators: inventory services, protect SSH, open only required ports, configure IPv6, persist rules and recover safely from lockouts.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use iptables on a VPS by first inventorying the services you actually expose, then adding loopback and established-connection rules, narrowly permitting administration and application ports, and only then changing unsolicited inbound and forwarding traffic to DROP. Test from a second connection before making the restrictive policy persistent. IPv4 and IPv6 require separate rule sets, and a reboot can erase rules unless your distribution loads a saved configuration.

What iptables does on a VPS

iptables is the command-line interface to Linux Netfilter packet filtering and network address translation (NAT). A rule specifies packet-matching criteria and a target. The targets you use most often on a host firewall are ACCEPT, DROP, and RETURN.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Chain Traffic handled Typical VPS use
INPUT Packets destined for the VPS itself SSH, web, DNS, monitoring and VPN access
OUTPUT Packets generated locally by the VPS Updates, DNS lookups, API calls and replies
FORWARD Packets routed through the VPS Gateway, router, container or VPN forwarding

For a normal web or application VPS, the usual security-first policy is to allow loopback traffic, allow packets belonging to connections that the server already accepted, permit SSH only from an administration source, open only the application ports you serve, and drop unsolicited inbound and routed traffic. Outbound traffic is commonly left available so the machine can update and reach required dependencies; restrict it only when you have documented every required destination.

Filtering is stateful when you use connection tracking. Netfilter remembers connection state, so a rule accepting ESTABLISHED,RELATED traffic allows replies to an SSH or HTTPS connection without opening every ephemeral return port. The userspace conntrack tool can inspect or manage tracked connections when diagnosing stateful behavior.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.

Decide what the firewall must protect

Account for the provider layer

Many VPS platforms offer an external security group or cloud-firewall layer. Treat that as defense in depth, not a replacement for the host firewall: a host rule set still protects traffic that reaches the virtual machine through an overlooked provider rule, an internal interface, or a newly attached network. Conversely, an external console or recovery network may be your only way back after a bad host rule.

Write an explicit service inventory

Do not start by copying a generic “open these ports” list. Record each listener, its protocol, who needs to reach it, and whether it is public.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Service Protocol and port Permitted source Decision
SSH administration TCP 22, or your configured port Fixed office, VPN or bastion addresses Permit only those source addresses
HTTP TCP 80 Internet, if serving plain HTTP or redirects Open only when the service listens
HTTPS TCP 443 Internet Open for a public TLS service
DNS resolver or authoritative server UDP and TCP 53 Documented client networks Never expose an unintended open resolver
Monitoring agent Agent-specific port Monitoring network Restrict by source, interface or VPN
VPN Protocol and port used by your VPN Internet or known peers Allow the exact transport, including UDP where required
Application or database Application-specific Only dependent hosts or private networks Prefer a private interface; do not publish by default

Check listeners with your operating system’s socket tools before writing rules. A port that is not listening gains nothing from a firewall exception, while a newly deployed service can become unreachable if its port was never documented.

Prepare safely before changing rules

Keep a recovery path

Have the VPS provider’s serial console, web console or rescue environment available. Keep your current SSH session open and, if possible, establish a second session from an independent client or network. Never apply a default DROP policy for the first time while relying on a single connection.

Inspect and back up the active configuration

sudo iptables -L
sudo iptables -L -v -n
sudo iptables -S
sudo iptables-save | sudo tee ~/iptables-before-change.rules

The first command lists chains and policies. Adding -v -n shows packet and byte counters without reverse-DNS lookups, which makes addresses and activity easier to read. The rule specification output from -S is convenient for review and recreation. A fresh Ubuntu installation can show ACCEPT policies with few or no rules; that is an unfiltered default, not evidence that the host is protected.

Identify the correct SSH source

Use the public address of the administration workstation, VPN egress or bastion that should connect. If that address changes frequently, use a VPN or bastion with a stable address rather than opening SSH to the entire Internet. A source restriction written with the wrong address can lock out every administrator as soon as the old session closes.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.

Build a conservative IPv4 policy

The following sequence is an example for a VPS that serves SSH on TCP 22 and a public web service on TCP 80 and 443. Replace the SSH source and service list with the inventory you created. Run each command separately and check for errors.

1. Add the rules that preserve local and existing connections

sudo iptables -A INPUT -i lo -j ACCEPT
sudo iptables -A OUTPUT -o lo -j ACCEPT
sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
sudo iptables -A OUTPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
sudo iptables -A INPUT -m conntrack --ctstate INVALID -j DROP

The loopback rules keep local services communicating with one another. The state rule permits replies and related flows, while dropping invalid tracked packets removes traffic that does not fit a valid connection state. If your system uses a different connection-tracking module, follow that distribution’s syntax consistently rather than mixing incompatible forms.

2. Permit SSH from an intended administration network

sudo iptables -A INPUT -p tcp -s 198.51.100.24/32 --dport 22 -m conntrack --ctstate NEW -j ACCEPT

198.51.100.24/32 is an example documentation address; replace it with your real administration address or CIDR range. If SSH uses another port, change --dport. Keeping the NEW match makes the rule’s purpose clear; established packets are already handled by the earlier state rule. Do not use a broad source such as 0.0.0.0/0 unless you have a specific, documented reason and compensating controls.

3. Permit only public application ports

sudo iptables -A INPUT -p tcp -m multiport --dports 80,443 -m conntrack --ctstate NEW -j ACCEPT

If the VPS is not serving HTTP or HTTPS, omit this rule. For a DNS service, add separate UDP and TCP rules and restrict the source to the client networks that should query it:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
sudo iptables -A INPUT -p udp -s 203.0.113.0/24 --dport 53 -m conntrack --ctstate NEW -j ACCEPT
sudo iptables -A INPUT -p tcp -s 203.0.113.0/24 --dport 53 -m conntrack --ctstate NEW -j ACCEPT

Replace the documentation network with the real client range. Authoritative DNS and resolver deployments have different exposure requirements; do not copy these exceptions without deciding who is allowed to query.

4. Review before enforcing default drops

sudo iptables -L INPUT -v -n --line-numbers
sudo iptables -L OUTPUT -v -n --line-numbers
sudo iptables -L FORWARD -v -n --line-numbers
sudo iptables -S

Confirm that the SSH accept rule appears before any eventual catch-all drop, that the source address is correct, and that every required service has an exception. Test a second SSH connection and an application request while the current session remains open.

Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by

5. Set the default policies only after validation

sudo iptables -P INPUT DROP
sudo iptables -P FORWARD DROP
sudo iptables -P OUTPUT ACCEPT

These policies affect packets that reach the end of a chain without matching an earlier rule. They do not reorder existing rules. Setting INPUT or FORWARD to DROP before the corresponding accept rules are present can immediately terminate your SSH connection and disrupt application-to-database or other routed traffic.

If your threat model requires outbound filtering, build and test an explicit OUTPUT allowlist first. An unconditional outbound drop can break package updates, DNS, time synchronization, certificate renewal, monitoring and cloud-init.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Design details that prevent common mistakes

Rule order is decisive

iptables evaluates a chain from the first rule downward and stops when a terminating target makes a decision. A broad drop placed above an SSH or web exception wins. Insert a rule at a specific position with iptables -I INPUT 1 ... when you must place it ahead of an existing rule, then inspect the numbered chain again.

Do not confuse local, routed and container traffic

Traffic to a service on the VPS uses INPUT. Traffic generated by a process on the VPS uses OUTPUT. Traffic passing between interfaces, including some VPN, router and container arrangements, uses FORWARD. A policy that protects INPUT does not automatically protect a server acting as a router.

Use counters as evidence

Run sudo iptables -L -v -n after a test request. Increasing packet and byte counters show which rule handled the traffic. A zero counter can mean the client never reached the VPS, the service is listening on another port, the packet used IPv6, or an earlier rule matched first.

IPv6 needs its own firewall

iptables manages IPv4. IPv6 is managed separately with ip6tables. If the VPS has a public IPv6 address, an IPv4-only policy can leave services reachable over IPv6 even though every IPv4 test appears secure.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.

Repeat the design for IPv6 with IPv6 sources and addresses:

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 -m conntrack --ctstate INVALID -j DROP
sudo ip6tables -A INPUT -p tcp -s 2001:db8:1234::24/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 addresses in this example are documentation prefixes. Substitute the actual IPv6 address or prefix of your administration network. Test SSH and web access over IPv6 explicitly; a successful IPv4 test proves nothing about the IPv6 path.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Make rules survive a reboot

Runtime rules live in kernel memory. A command that works interactively can disappear at the next reboot unless a persistence service or configuration file restores it. On Ubuntu, a common arrangement stores IPv4 rules in /etc/iptables/rules.v4 and IPv6 rules in /etc/iptables/rules.v6. Ubuntu 22.04 can expose iptables syntax through an nftables backend, so the command name does not by itself tell you which Netfilter implementation is active.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

After testing, save both families through the persistence mechanism supported by your release. On systems using the netfilter-persistent service, the workflow is typically:

sudo netfilter-persistent save
sudo systemctl enable netfilter-persistent
sudo systemctl status netfilter-persistent

Some installations require the persistence package to be installed first; use your distribution’s package manager and verify the service name rather than assuming it exists. Confirm the files contain the intended rules, reboot only during a controlled maintenance window, and inspect the active chains again after startup.

To restore a saved IPv4 ruleset manually on a recovery console, use the matching restore tool:

sudo iptables-restore < /etc/iptables/rules.v4

Apply the IPv6 file with ip6tables-restore. Keep a known-good copy outside the VPS as well as on the machine; a damaged disk or failed boot cannot read its local backup.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Verify from outside the VPS

  1. From an independent network, open a new SSH session using the permitted source address. Do not close the original session yet.
  2. Request every published web endpoint over both HTTP and HTTPS and confirm that the application, certificate renewal and redirects behave as expected.
  3. Test each private service from its approved network and confirm that the same port is unreachable from an unapproved network.
  4. Repeat relevant tests using the VPS’s IPv6 address.
  5. Watch counters with sudo iptables -L -v -n and the corresponding ip6tables command while testing.
  6. Check application logs and system logs for rejected connections that represent a missing, rather than unwanted, exception.

A provider-level firewall can block a test before it reaches the host, so compare the external policy with the host policy when results conflict. Conversely, a successful provider test does not prove that the host chain accepted the packet.

Recover from a lockout

Use the provider console first

If SSH stops responding immediately after a change, leave the original connection open and connect through the provider’s serial, web or rescue console. Inspect the numbered rules and policies:

sudo iptables -L -v -n --line-numbers
sudo ip6tables -L -v -n --line-numbers

Temporarily restore access

From the console, set permissive policies and remove the faulty runtime rules only long enough to regain administration:

sudo iptables -P INPUT ACCEPT
sudo iptables -P FORWARD ACCEPT
sudo iptables -P OUTPUT ACCEPT
sudo iptables -F
sudo ip6tables -P INPUT ACCEPT
sudo ip6tables -P FORWARD ACCEPT
sudo ip6tables -P OUTPUT ACCEPT
sudo ip6tables -F

These commands are an emergency rollback, not a finished firewall. Rebuild the documented rules, test from a second client, and save the corrected configuration. If a persistence service reloads the bad files at boot, edit or replace those files before restarting it.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

iptables, nftables or ufw?

Option Abstraction IPv4 and IPv6 Expressiveness Persistence and migration Best fit
Direct iptables commands Low-level Netfilter interface Separate iptables and ip6tables rule sets Detailed packet matches, chains and targets Requires an explicit save-and-restore workflow; Ubuntu may route syntax through an nftables backend Operators who need familiar granular rules or must integrate with existing tooling
nftables Current Netfilter framework Designed to express both families in one ruleset Rich sets, maps, chains and stateful matching Native nft configuration and service integration; migration requires understanding backend differences New designs and complex policies on distributions that standardize on nftables
ufw Simplified frontend Provides simpler dual-stack policy commands Convenient common allow and deny rules, less direct control of complex packet logic Manages its own persistent configuration Readers who need a straightforward host policy rather than custom chains

Ubuntu’s security documentation describes nftables as the successor to the iptables component in Netfilter and positions ufw as a simpler frontend. Modern Ubuntu packages can provide an iptables-compatible interface backed by nftables. Choose one management approach deliberately: mixing commands and frontends without knowing which backend owns the active rules makes troubleshooting and persistence harder.

Operational checklist

  • List every listener and mark it public, private, VPN-only or local.
  • Record the exact SSH source, port and an out-of-band recovery method.
  • Back up the current IPv4 and IPv6 rules before editing.
  • Add loopback and ESTABLISHED,RELATED rules before restrictive policies.
  • Permit only the required ports, protocols, interfaces and source networks.
  • Review numbered chains and counters before setting default drops.
  • Apply an equivalent policy with ip6tables when IPv6 is enabled.
  • Test from an independent client while the original session remains open.
  • Save both rule sets through the distribution-supported persistence service.
  • Document rollback commands and review the policy whenever a service, address or provider network changes.

The practical goal is not the largest rule list; it is a small, documented policy whose exceptions match real services and whose recovery path has been tested. Start with the inventory, validate every accept rule from outside the VPS, then enforce and persist the default-deny boundary.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.