PHP连接AWS EC2时出现Unknown MySQL server host错误求助
Fixing "Unknown MySQL server host" Error When Connecting to Amazon EC2 MySQL
Hey there, let's work through this MySQL connection issue step by step! The error you're seeing is triggered by a straightforward mistake in your connection string, but we'll also cover other common pitfalls to make sure everything runs smoothly.
The Immediate Fix: Remove the HTTP Protocol from Your Host String
MySQL uses TCP/IP for remote connections, not HTTP—so including http:// in your DB_SERVER value is what's causing the "Unknown host" error. Here's your corrected code (I also added the database name to the mysqli_connect call to save you a separate mysqli_select_db step):
define('DB_SERVER', 'ec2-54-86-44-206.compute-1.amazonaws.com'); // No http:// needed define('DB_USERNAME', 'root'); define('DB_PASSWORD', 'PW'); define('DB_DATABASE', 'DB'); // Connect with the database name included $connection = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE); // Add error checking to confirm success if (!$connection) { die("Connection failed: " . mysqli_connect_error()); } echo "Connected successfully!";
Additional Troubleshooting Steps (If the Fix Above Doesn't Work)
If you still run into errors after removing the HTTP prefix, check these common issues:
- EC2 Security Group Port Access: Make sure your EC2 instance's security group allows inbound traffic on port 3306 (MySQL's default port) from your local machine's IP. For testing, you can temporarily allow
0.0.0.0/0(all IPs), but remember to restrict it to your specific IP for production. - MySQL Bind Address Configuration: On your EC2 server, open your MySQL config file (usually located at
/etc/mysql/my.cnfor/etc/mysql/mysql.conf.d/mysqld.cnf) and check thebind-addresssetting. It should be set to0.0.0.0to allow remote connections (if it's127.0.0.1, MySQL will only accept local connections). After updating, restart MySQL withsudo systemctl restart mysql. - MySQL User Remote Permissions: By default, the
rootuser might only be allowed to connect fromlocalhost. Log into MySQL on your EC2 instance and run these commands to grant remote access (replacePWwith your actual password):
For production, replaceGRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'PW' WITH GRANT OPTION; FLUSH PRIVILEGES;%with your specific client IP instead of allowing all addresses. - Test Connectivity Locally: From your own machine, use
telnet ec2-54-86-44-206.compute-1.amazonaws.com 3306to check if the port is reachable. If it fails, double-check your security group and MySQL settings.
内容的提问来源于stack exchange,提问作者PLau Peter
相关产品推荐
相关产品推荐

