How to connect to MySQL with an SSH tunnel

If you need to connect to your MySQL database remotely, using an SSH tunnel is the safest and most reliable way to do it. This method encrypts your connection, keeping your data secure and avoiding compliance issues.

This guide requires that you have installed PuTTY and set up SSH key access on your VPS.

Why Remote MySQL Connections Are Disabled

To protect our network, remote MySQL connections are disabled by default because port 3306, the standard MySQL connection port, is closed. On shared hosting, we cannot open this port due to strict security policies. If you have a VPS, we can open it upon request, but doing so comes with serious security risks.

Leaving port 3306 open makes your database vulnerable to brute-force attacks, SQL injection, and denial-of-service (DoS) attacks. It can also lead to PCI-DSS compliance issues, which could be a problem if you handle payments through providers like Visa, Mastercard, or American Express. PCI-DSS requires encryption of data in transit, which is not inherently provided by MySQL alone. In short, an open MySQL port can be a major security hole.

How an SSH Tunnel Works

An SSH tunnel lets you securely connect to your database without opening port 3306 to the internet. Instead, you first establish an SSH connection to your server using a key pair (recommended) or password. This connection creates a secure, encrypted tunnel between your local machine and the remote database.

Once the tunnel is active, you can connect to MySQL as if it were running locally, using something like localhost:3307. Behind the scenes, all traffic is securely routed through SSH, keeping it encrypted and protected from outside threats.

Using an SSH tunnel is a simple yet effective way to connect to your database securely whilst avoiding the unnecessary risks associated with allowing connections over port 3306 through the firewall.

Create an SSH Tunnel using PuTTY

1. First off open a PuTTY window and enter either the IP or hostname of your VPS followed by port 9248 or 22.

PuTTY window showing sessions area with connection details
Sessions in PuTTY

2. Moving forward in the category section click on the SSH dropdown using the + icon and then click “Tunnels”. From here in the source port section put in the Remote SQL port 3306 and add the destination as localhost:3306.

Tunnels Category in PuTTY
Tunnels

3. Afterwards click “Add” this will add that configuration to the forwarded ports list.

Configured PuTTY Tunnel
Configured Tunnel

4. Finally, using the category menu click back on “Session” from here you can choose to save this configuration to use it at a later date or open the connection with the “Open” button.

PuTTY saved Session profile