On your new server (with the Laravel application), run the following commands to generate an SSH key pair:
ssh-keygen -t rsa -b 4096
By default, this will create two files in the ~/.ssh
directory:
id_rsa
: your private key. Keep it secret!id_rsa.pub
: your public key. You'll share this with other servers/services.
On the new Laravel server, run:
ssh-copy-id [username]@[old_server_ip]
This will copy the public key (id_rsa.pub
) to the ~/.ssh/authorized_keys
file on the old server.
Replace [username]
with the username on the old server and [old_server_ip]
with the old server's IP address.
To setup SSH tunneling, you'd use the following structure:
ssh -f -N -L [local_port]:127.0.0.1:[remote_mysql_port] [username]@[old_server_ip]
For example, if you're using the default MySQL port (3306):
ssh -f -N -L 3307:127.0.0.1:3306 [username]@[old_server_ip]
Now, the local server (Laravel) will forward any traffic on its port 3307 to the old server's MySQL port (3306).
In your .env
file or wherever you're setting your environment variables, you'd set up the DATABASE_URL
like this:
DATABASE_URL=mysql://[mysql_user]:[mysql_password]@127.0.0.1:3307/[database_name]
OR
SSH username: username SSH server IP: [old_server_ip] MySQL username: [mysql_user] MySQL database name: [database_name] The connection string format would be:
DATABASE_URL=mysql+ssh://username@[old_server_ip]/[mysql_user]@127.0.0.1/[database_name]?usePrivateKey=true
- Replace
[mysql_user]
with your MySQL username. - Replace
[mysql_password]
with your MySQL password. - Replace
[database_name]
with the name of your MySQL database.
The key point here is that you're connecting to 127.0.0.1
on port 3307
, which will be tunneled to the old server's MySQL through SSH.
-
Security: Ensure that you don't expose MySQL to the internet on your old server. Ideally, it should only listen to localhost (127.0.0.1).
-
SSH Key Security: Make sure your private key (
id_rsa
) remains private. Never share it, and always secure your server environments. -
MySQL Users: Ensure the MySQL user you're connecting with has the necessary permissions for your Laravel application (e.g., SELECT, INSERT, UPDATE, DELETE).
-
Tunneling: The SSH tunnel command given above is for a one-time setup. If the connection drops or the server reboots, you'd need to set it up again. Consider using a tool or service that can ensure the tunnel is always active or look into automated solutions if it becomes a problem.
-
SSH Client Configuration: You can also use
~/.ssh/config
to make SSH connections (and tunneling) easier with shortcuts. -
Database Configuration in Laravel: While you can use the
DATABASE_URL
for configurations, Laravel's.env
also provides individual configuration options likeDB_HOST
,DB_PORT
,DB_DATABASE
,DB_USERNAME
, andDB_PASSWORD
which you can use in place of or in conjunction with theDATABASE_URL
.