How can I use SSH to securely access a remote MySQL database?

Published on Aug. 22, 2023, 12:18 p.m.

To use SSH to securely access a remote MySQL database, you can create an SSH tunnel to forward the MySQL port from the remote server to your local machine. This allows you to establish a secure connection to the remote server and access the MySQL database without exposing the database to the public internet.

Here are the general steps to create an SSH tunnel to a remote MySQL database:

  1. Install and configure an SSH client on your local machine.
  2. Log in to the remote server using SSH.
  3. Forward the remote MySQL port to a local port using the SSH command with the -L option. For example, to forward the MySQL port 3306 from the remote server to port 3306 on your local machine, you can use the following command:

ssh -L 3306:localhost:3306 remote_user@remote_host

This will create an encrypted SSH tunnel and forward all traffic on port 3306 (MySQL) from the remote server to your local machine.
4. Connect to the MySQL database using your local machine as the host and the forwarded port number (3306 in this example).

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

This will connect to the MySQL database running on the remote server through the SSH tunnel.

Once you have established the SSH tunnel and connected to the MySQL database, you can use any MySQL client to manage the database, such as the MySQL command-line client or MySQL Workbench.