Skip to content

MySQL IP Whitelisting

This guide documents how to allow specific IPs to access MySQL on port 3306 and block all others using iptables.

Terminal window
sudo iptables -L -n --line-numbers

To filter only MySQL (port 3306) rules:

Terminal window
sudo iptables -L INPUT -n --line-numbers | grep 3306

βž• Step 2: Add a New IP Address to Allow MySQL Access

Section titled β€œβž• Step 2: Add a New IP Address to Allow MySQL Access”

Replace YOUR.IP.ADD.RESS with the IP you want to allow:

Terminal window
sudo iptables -A INPUT -p tcp -s YOUR.IP.ADD.RESS --dport 3306 -j ACCEPT

Example:

Terminal window
sudo iptables -A INPUT -p tcp -s 152.58.69.149 --dport 3306 -j ACCEPT

Run:

Terminal window
sudo iptables -L INPUT -n --line-numbers | grep 3306

If you see a rule like:

17 DROP tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:3306

That means rules below this DROP will not work β€” they are ignored.

🧽 Delete the DROP rule (replace 17 with actual line number):

Terminal window
sudo iptables -D INPUT 17

πŸ’‘ Use this again if numbers have shifted:

Terminal window
sudo iptables -L INPUT -n --line-numbers | grep 3306

βœ… Re-add the DROP rule at the end:

Terminal window
sudo iptables -A INPUT -p tcp --dport 3306 -j DROP

This ensures all allowed IPs are evaluated before blocking others.

Terminal window
sudo iptables -L INPUT -n --line-numbers | grep 3306

Example output:

1 ACCEPT tcp -- 152.58.69.149 0.0.0.0/0 tcp dpt:3306
2 ACCEPT tcp -- 103.162.217.218 0.0.0.0/0 tcp dpt:3306
...
10 DROP tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:3306

πŸ’Ύ Step 6: Save iptables Rules (Persistent After Reboot)

Section titled β€œπŸ’Ύ Step 6: Save iptables Rules (Persistent After Reboot)”

Ubuntu/Debian:

Terminal window
sudo apt install iptables-persistent
sudo netfilter-persistent save