iptables
the classic firewalliptables manages packet-filtering rules in the kernel. Rules live in chains — INPUT, OUTPUT, FORWARD — and are checked in order until one matches. nftables has replaced it underneath, but iptables syntax is still what most guides, Docker and many servers use.
Rules are read top to bottom, first match wins — so order is everything.
At the terminal
Read the session first, then the notes: each numbered line in the output is answered by the note with the same number.
What the numbered lines are telling you
The policy is what happens to a packet no rule matches. DROP means everything not explicitly allowed is discarded: 214 packets so far.
Traffic on the lo interface is the machine talking to itself. Blocking it breaks many programs.
Packets belonging to connections already established are accepted. This one rule lets answers to your own outgoing requests back in.
New TCP connections to port 22 are accepted. The counters show the rule has matched 312 packets.
Switches
A switch changes how the command behaves. These are the ones used day to day; man iptables lists the rest. Single-letter switches can usually be joined, so -l -a may be written -la.
-L- List the rules in a chain.
-n- Numeric: no name lookups.
-v- Verbose: show counters and interfaces.
-A CHAIN- Append a rule to the end of a chain.
-I CHAIN NUM- Insert a rule at position NUM.
-D CHAIN NUM- Delete rule number NUM.
-p PROTO- Match a protocol: tcp, udp, icmp.
--dport PORT- Match the destination port.
-s ADDR- Match the source address.
-j TARGET- What to do on a match: ACCEPT, DROP, REJECT.
-t TABLE- Work on another table, such as nat.
Variations worth knowing
The same tool, pointed at a narrower question. These four cover most of what it is reached for day to day.
sudo iptables -SPrints the rules as the commands that would recreate them.
sudo iptables -I INPUT 1 -s 203.0.113.50 -j DROPInserts a rule at the top to block one address.
sudo iptables -D INPUT 3Deletes rule number 3 from the chain.
sudo iptables-save > rules.v4Saves the current ruleset to a file.
In cybersecurity
A firewall should drop by default and allow by exception.
Setting the policy to DROP before allowing SSH cuts your own connection. Add the allow rules first, and keep console access for a remote server.
iptables changes are in memory only. Without iptables-persistent or an equivalent, a restart leaves the machine with no firewall.
iptables covers IPv4 only. Unless ip6tables has matching rules, every service is still reachable over IPv6.