Feb 01. 2019 · by Helge Sverre

Connect to databases on Laravel Forge on your local machine

By default Laravel Forge only allows SSH connections via SSH public key authentication, if you want to connect to your remote (laravel forge) database from your local SQL Client OR if you want your local Craft CMS install to talk directly to the remote database, you need to create an SSH tunnel.

Run this in your terminal
BASH
ssh -L 3307:FORGE-PRIVATE-IP:3306 forge@FORGE-PUBLIC-IP
  • 3307 - the local port on your machine that the tunnel binds to
  • 3306 - the port on the remote host that is listening
  • forge - the ssh username, this is usually "forge".
  • FORGE-PRIVATE-IP - the private (internal) IP of the forge server
  • FORGE-PUBLIC-IP - the public IP address (or domain) of the forge server

You find these values in your Forge server detail page, the first IP is the Public IP Address, second one inside (paranthesis) are the Private IP Address

The IPs and Server name are fictitious in this image for illustrative purposes

Now you can connect to your remote database from your local Craft CMS install.

.env file
ENV
DB_DRIVER="mysql"
# We're connecting to localhost here
# but it's really forwarding it to the remote server via our SSH Tunnel
DB_SERVER="localhost" 
DB_USER="database-user"
DB_PASSWORD="database-password"
DB_DATABASE="craft_database"

# Since we bound the 3307 port in our SSH tunnel,
# this is what we'll use, the default is usually 3306
DB_PORT="3307"

This is useful to know if you want to work with your Craft CMS templates locally, but want to have a single source of truth (remote database) so that clients and other developers can create content/work on the same site.

Note
Your SSH public key needs to be added to the server, you can do that at this URL:
https://forge.laravel.com/user/profile#/keys