Connect to MySQL Remotely
It can sometimes be useful to enable remote connections to MySQL. This allows you to directly connect to MySQL on one of your servers from an application or MySQL client running on a different system.
There are two different ways to access MySQL remotely:
- Using an SSH tunnel.
- Enabling direct access to MySQL from remote systems.
Connecting to MySQL Using an SSH Tunnel
Using an SSH tunnel is the easiest and safest option for remote MySQL access for development purposes. An SSH tunnel will make it look like MySQL is running on your local system. SSH does this by opening a local port and seamlessly transferring all of the communication over that port through to MySQL running on your server.
To create an SSH tunnel from Mac or Linux, you can run the command line
SSH command with the
-L to enable local port forwarding.
ssh -L localhost:2000:localhost:3306 serverpilot@SERVER_IP_ADDRESS
In the example above, SSH would open port 2000 on your local system, and you can then communicate with MySQL by connecting to this local port. For example, you can connect using the MySQL command:
mysql --protocol=tcp --host=localhost --port=2000 --user=DB_USER_NAME -p
Enabling Direct Access to MySQL from Remote Systems
Step 1: Configure MySQL to listen on all interfaces.
By default, MySQL only listens for connections on localhost, so the first step is to reconfigure MySQL on your database server to listen on all interfaces. To do this, log in to your server as root.
If you are running an Ubuntu 16.04 or 18.04 server, edit this file:
For 14.04 or 12.04 servers, edit this file:
Find the following line in either file:
bind-address = 127.0.0.1
Change the bind-address to 0.0.0.0:
bind-address = 0.0.0.0
Save this file and then run the following command as root:
sudo service mysql restart
Step 2: Open TCP port 3306 in your server's firewall.
The firewall configured by ServerPilot blocks all access to MySQL from outside of your server. So, you will need to customize your firewall to allow access to MySQL.
To open up access to MySQL from outside of your server, see our article on customizing your firewall. If you use a firewall management service like HeatShield, see its documentation on securing MySQL with a firewall.
Additional Step for EC2: Allow TCP port 3306 in your security groups.
If this is an EC2 server, you must also allow port 3306 in your server's security groups.
Last updated: April 26, 2018