You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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.cnf or /etc/mysql/mysql.conf.d/mysqld.cnf) and check the bind-address setting. It should be set to 0.0.0.0 to allow remote connections (if it's 127.0.0.1, MySQL will only accept local connections). After updating, restart MySQL with sudo systemctl restart mysql.
  • MySQL User Remote Permissions: By default, the root user might only be allowed to connect from localhost. Log into MySQL on your EC2 instance and run these commands to grant remote access (replace PW with your actual password):
    GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'PW' WITH GRANT OPTION;
    FLUSH PRIVILEGES;
    
    For production, replace % 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 3306 to check if the port is reachable. If it fails, double-check your security group and MySQL settings.

内容的提问来源于stack exchange,提问作者PLau Peter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:17:11