# Restricting MySQL port access

> Block outside access to MySQL port 3306 on your VPS by turning off MySQL networking or adding firewall rules.

Source: https://helpcenter.ruachost.com/developers/databases/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.

## **Method 1: Disable MySQL Networking**

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

### **Tip:**

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

### **AlmaLinux and Fedora**

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.

4. Remove the `#` so it reads:

```
skip-networking
```

5. Save the file and exit the editor.
6. Restart MySQL:

```
service mysqld restart
```

Port 3306 is now closed to external connections.

### **Debian and Ubuntu**

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
```

### Note

- 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.

4. Save any changes and exit.
5. Restart MySQL:

```
service mysql restart
```

Port 3306 is now restricted to local connections.

## **Method 2: Configure Firewall Rules**

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
```

### **Tip:**

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.
