Skip to content

Restricting MySQL port access

This guide explains two methods to restrict or block access to MySQL port 3306 on an unmanaged server.

Important: You must have root access to the server. This guide applies only to unmanaged products.

If you do not need external access to MySQL, you can disable networking.

Even with networking disabled, you can still access MySQL securely from a remote computer using an SSH tunnel.

  1. Log in to your server via SSH.
  2. Open the MySQL configuration file /etc/my.cnf with your preferred text editor.
  3. Locate this line:
#skip-networking

Note: If the line does not exist, add it.

  1. Remove the # so it reads:
skip-networking
  1. Save the file and exit the editor.
  2. Restart MySQL:
service mysqld restart

Port 3306 is now closed to external connections.

  1. Log in to your server via SSH.
  2. Open /etc/mysql/my.cnf with your text editor.
  3. Locate the bind-address line:
bind-address = 127.0.0.1
  • If bind-address is set to 0.0.0.0 or missing, MySQL is open to all interfaces.
  • 127.0.0.1 restricts connections to localhost only.
  1. Save any changes and exit.
  2. Restart MySQL:
service mysql restart

Port 3306 is now restricted to local connections.

You can use iptables to selectively block or allow access to port 3306.

  • Block all external access:
iptables -A INPUT -p tcp --dport 3306 -j DROP
  • Allow a specific IP and block others (replace xxx.xxx.xxx.xxx with the allowed IP):
iptables -A INPUT -p tcp --dport 3306 -s xxx.xxx.xxx.xxx -j ACCEPT
iptables -A INPUT -p tcp --dport 3306 -j DROP

To allow additional IPs, insert rules before the DROP rule:

iptables -I INPUT 1 -p tcp --dport 3306 -s xxx.xxx.xxx.xxx -j ACCEPT

This method provides granular control over which IPs can connect to MySQL.