How to remotely connect to MySQL database running on a Vagrant box

While it's common to run PhpMyadmin on servers to manage MySQL databases on them, doing so can open up security holes and so many folks choose not to. But running mysql client from the command line can be painful for heavy use - although a quick "drush sql-cli" to connect to a Drupal database comes in handy. So let's say you are using Vagrant to create and provision your servers, whether local or in the cloud, and you want to use GUI tools to run queries on the database. Instead of opening up access to your mysql server to all Internet hosts and thus being vulnerable to hackers, just keep your mysql listening locally and use the security of ssh to connect remotely. 

1. How do you ssh to your vagrant box? Use the 'vagrant ssh-config'


$ vagrant ssh-config
Host default
HostName 128.199.X.X
User luser
Port 22
UserKnownHostsFile /dev/null
StrictHostKeyChecking no
PasswordAuthentication no
IdentityFile /Users/luser/.ssh/id_dsa
IdentitiesOnly yes
LogLevel FATAL
ForwardAgent yes

2. Save the above output into your ~/.ssh/config file, changing the host name default to something you want to connect as, a shortcut name.

3. Add " LocalForward 13306 127.0.0.1:3306" to the host definition you just added. You can make 13306 any port you want, such as the normal 3306 port for mysql. It should be a number above 1024.

4. Now set your local client to connect to your mysql database using localhost / 127.0.0.1 as host, the above port (13306) for port, and now you should make sure you are ssh'd into the vagrant host (connect by running "ssh default" or whatever host you set, not by running "vagrant ssh") and that should forward a port to connect to your remote mysql server.