To connect to a MySQL database on a Forge server from your local development environment, you can use an SSH tunnel. This allows you to securely connect to the remote database as if it were running locally. Here's how you can set it up:
Step 1: Set Up SSH Tunnel
-
Open your terminal and run the following command to create an SSH tunnel. Replace
forge_user,forge_server_ip, and3306with your Forge server's SSH username, IP address, and MySQL port, respectively:ssh -L 3307:127.0.0.1:3306 forge_user@forge_server_ip3307is the local port you will use to connect to the remote MySQL server. You can choose any available port on your local machine.127.0.0.1:3306is the address and port of the MySQL server on the Forge server.
-
Keep this terminal window open while you work, as closing it will terminate the SSH tunnel.
Step 2: Update Your .env File
Modify your Laravel project's .env file to connect to the database through the SSH tunnel:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3307
DB_DATABASE=your_database_name
DB_USERNAME=your_database_username
DB_PASSWORD=your_database_password
DB_HOSTshould be127.0.0.1because the SSH tunnel makes the remote database appear as if it's local.DB_PORTshould match the local port you specified in the SSH tunnel command (3307in this example).
Step 3: Test the Connection
Run a simple database query or use Laravel's artisan command to ensure the connection is working:
php artisan migrate:status
If everything is set up correctly, you should see the status of your migrations without any connection errors.
Additional Tips
- SSH Key Authentication: Ensure your local machine can SSH into the Forge server without a password prompt by using SSH keys.
- Firewall Rules: Make sure your Forge server's firewall allows SSH connections from your IP address.
- Database User Permissions: Verify that the database user has the necessary permissions to access the database.
By following these steps, you should be able to connect to your Forge server's MySQL database from your local development environment securely.