To connect to a MySQL database hosted on a Laravel Forge server remotely, there are a few things you need to set up, since Forge configures MySQL to only allow local connections by default. Here are the required steps:
1. Allow Remote Connections in MySQL
By default, MySQL on Forge listens only on 127.0.0.1 (localhost), which means external servers can’t connect directly.
- Change the MySQL bind address
SSH into your Forge server and edit the MySQL configuration file:
sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf
Find the line:
bind-address = 127.0.0.1
Change it to:
bind-address = 0.0.0.0
Warning: This makes MySQL accessible from any IP. Restrict access via firewall rules (see below).
Restart MySQL:
sudo service mysql restart
2. Create a Specific MySQL User For Remote Access
Login to MySQL on your Forge server:
mysql -u root -p
Create a user that is allowed to connect from the remote server's IP address:
CREATE USER 'your_user'@'remote_server_ip' IDENTIFIED BY 'your_password';
GRANT ALL PRIVILEGES ON db_name.* TO 'your_user'@'remote_server_ip';
FLUSH PRIVILEGES;
Replace 'your_user', 'your_password', 'db_name', and remote_server_ip accordingly.
3. Allow the Remote Server Through the Firewall (On Forge)
In the Forge dashboard, for your server:
- Go to "Network" > "Firewall".
- Add a rule to allow your remote server’s IP address access to port
3306(the MySQL port).
4. Connect From Your Remote Site
Now use the remote Forge server's public IP as the mysqli host:
$link_lms = new mysqli('forge_server_ip', 'your_user', 'your_password', 'db_name');
5. (Recommended) Use an SSH Tunnel (for Better Security)
Instead of making MySQL globally accessible, consider connecting through an SSH tunnel, which is more secure. On your remote server, set up the tunnel:
ssh -L 3307:127.0.0.1:3306 forge_user@forge_server_ip
Then, on your PHP site, connect to localhost:3307:
$link_lms = new mysqli('127.0.0.1', 'forge_db_user', 'password', 'db_name', 3307);
This forwards all traffic securely through SSH.
Summary
- For simplicity, open MySQL (
bind-address, user privileges, firewall). - For security, use an SSH tunnel (no changes to MySQL config or firewall).
Forge security best practice: Don’t open MySQL to the world; use tunneling/whitelist only necessary IPs.
Let me know if you need more specifics on any of these steps!