SSH tunneling provides a secure way to connect to your MySQL database over an encrypted SSH connection, protecting your data from being intercepted during transmission. This is especially useful when accessing a remote MySQL server that isn’t exposed to the public internet.

In this tutorial, we will learn how to connect to a MySQL database using an SSH tunnel securely.

Prerequisites

Before we get started, make sure you have the following:

  • Access to a remote server with SSH enabled.
  • MySQL server installed and running on the remote server.
  • SSH client installed on your local machine.
  • MySQL client installed on your local machine.

Step 1 – Open SSH Tunnel Using Command Line

To create an SSH tunnel, you can use the ssh command from your local machine. The basic syntax is as follows:

ssh -L local_port:remote_host:remote_port user@ssh_server -N

Here’s what each part means:

  • -L local_port:remote_host:remote_port: This specifies the local port, remote host, and remote port for the tunnel.
  • user@ssh_server: Your SSH username and the server you are connecting to.
  • -N: This tells SSH not to execute a remote command (just create the tunnel).

For example, to forward your local port 3306 to the remote MySQL server’s port 3306 through an SSH server, you would use:

ssh -L 3306:localhost:3306 root@mysql-server-ip -N

Step 2 – Verify the SSH Tunnel

After running the command, your terminal will wait and not show any output, indicating that the tunnel is active. You can verify this by opening a new terminal window and checking the SSH connection:

netstat -plant | grep 3306

If the SSH tunnel is working, you should see output similar to this:

tcp        0      0 127.0.0.1:3306          0.0.0.0:*              LISTEN      1234/ssh

Step 3 – Connecting to MySQL Through the SSH Tunnel

With the SSH tunnel set up, you can connect to the MySQL server using the mysql command:

mysql -h 127.0.0.1 -P 3306 -u your_mysql_user -p

You will be prompted to enter your MySQL password. Once authenticated, you can run your MySQL commands as if connected directly to the remote server.

Conclusion

In this article, we demonstrated how to connect to a MySQL database securely using an SSH tunnel. We covered setting up the SSH tunnel from the command line, verifying the tunnel, and connecting to MySQL using the command line. SSH tunneling ensures your database connections are secure, protecting sensitive data from potential interception. You can now access your MySQL hosted on dedicated server hosting from Atlantic.Net!