iptables Allow a Port from Specific IPs Only
Enter the port and the addresses that may use it. You get the allow rules and the drop rule in the order that works.
Rules, in this order
An allow rule alone blocks nobody when the INPUT policy is ACCEPT, so the drop rule is required. Every line inserts at position 1, so the drop rule goes in first and the allow rules end up above it. Iptables stops at the first match, which lets your addresses through and drops the rest.
Check the order
The ACCEPT lines must appear above the DROP or REJECT line. Then test: from an allowed address the port answers, from any other it does not (nc -vz SERVER_IP PORT).
Keep it after a reboot
Do not filter your SSH port this way unless you have another way in. Cloud providers also filter separately, see Oracle Cloud.
Example: allow MySQL only from two addresses
To let only 203.0.113.5 and the subnet 198.51.100.0/24 reach MySQL on port 3306, the generator produces:
sudo iptables -I INPUT 1 -p tcp --dport 3306 -j DROP sudo iptables -I INPUT 1 -p tcp -s 198.51.100.0/24 --dport 3306 -j ACCEPT sudo iptables -I INPUT 1 -p tcp -s 203.0.113.5 --dport 3306 -j ACCEPT
Listing the chain afterwards should show the two ACCEPT rules above the DROP rule, similar to this:
Chain INPUT (policy ACCEPT) num target prot opt source destination 1 ACCEPT tcp -- 203.0.113.5 0.0.0.0/0 tcp dpt:3306 2 ACCEPT tcp -- 198.51.100.0/24 0.0.0.0/0 tcp dpt:3306 3 DROP tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:3306
When INPUT rules do not apply
Ports published by Docker are forwarded to the container and never reach the INPUT chain, so the rules above do not filter them. Put such rules in the DOCKER-USER chain instead, and test from an outside address, because rules there see the packet after Docker's address translation.
Related: iptables command generator, port 3306 notes, save rules permanently.
FAQ
How do I allow only one IP to a port with iptables?
Add an ACCEPT rule with -s and the address, then a DROP rule for the same port below it.
Can I allow several IP addresses?
Yes. List them, one ACCEPT rule each, or use a CIDR range. For very long lists ipset is more efficient.
Why does another IP still connect?
No DROP rule follows the ACCEPT rule, or the DROP rule sits above the ACCEPT rule.