MySQL IP Whitelisting
π MySQL IP Whitelisting with iptables on a VPS
Section titled βπ MySQL IP Whitelisting with iptables on a VPSβThis guide documents how to allow specific IPs to access MySQL on port 3306 and block all others using iptables.
π Step 1: View Current iptables Rules
Section titled βπ Step 1: View Current iptables Rulesβsudo iptables -L -n --line-numbersTo filter only MySQL (port 3306) rules:
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:
sudo iptables -A INPUT -p tcp -s YOUR.IP.ADD.RESS --dport 3306 -j ACCEPTExample:
sudo iptables -A INPUT -p tcp -s 152.58.69.149 --dport 3306 -j ACCEPTβ οΈ Step 3: Check for DROP Rule Interference
Section titled ββ οΈ Step 3: Check for DROP Rule InterferenceβRun:
sudo iptables -L INPUT -n --line-numbers | grep 3306If you see a rule like:
17 DROP tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:3306That means rules below this DROP will not work β they are ignored.
π Step 4: Reorder the DROP Rule
Section titled βπ Step 4: Reorder the DROP Ruleβπ§½ Delete the DROP rule (replace 17 with actual line number):
sudo iptables -D INPUT 17π‘ Use this again if numbers have shifted:
sudo iptables -L INPUT -n --line-numbers | grep 3306β Re-add the DROP rule at the end:
sudo iptables -A INPUT -p tcp --dport 3306 -j DROPThis ensures all allowed IPs are evaluated before blocking others.
β Step 5: Verify Final iptables Rule Order
Section titled ββ Step 5: Verify Final iptables Rule Orderβsudo iptables -L INPUT -n --line-numbers | grep 3306Example output:
1 ACCEPT tcp -- 152.58.69.149 0.0.0.0/0 tcp dpt:33062 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:
sudo apt install iptables-persistentsudo netfilter-persistent save