Lewis Tyler

Connecting to a database in Vagrant (SSH Tunnel)

Sometimes you might need to connect to a database inside a virtual machine like Vagrant.

Since a Vagrant VM is a self-contained operating system you can’t simply connect to its services with a regular IP address and port as you would under normal circumstances.

What you need is an SSH tunnel. Inside your Vagrant installation’s local directory run:

vagrant ssh-config

In my case it gave me this output:

HostName 127.0.0.1
User vagrant
Port 2222
UserKnownHostsFile /dev/null
StrictHostKeyChecking no
PasswordAuthentication no
IdentityFile /[project]/.vagrant/machines/default/virtualbox/private_key
IdentitiesOnly yes
LogLevel FATAL
ForwardAgent yes

Since my Vagrant project was using SSH Agent Forwarding, I had to reference the above IdentityFile in my tunnel command:

ssh -i ~/[project]/.vagrant/machines/default/virtualbox/private_key -N -L 13306:127.0.0.1:3306 -p 2222 vagrant@localhost

As my VM’s db was at the MySQL default 127.0.0.1:3306 I referenced that, prefaced by the port I wanted to map to 13306 (substitute this for whatever you like).

After that you can connect to the database using IP?. In my case I was connecting Laravel to an existing database server, so I just plonked those details in my .env. Job done.