使用Terraform部署AWS PHP Web服务器时遭遇连接拒绝问题的排查求助
Let's break down the likely issues causing your connection refusal, and walk through fixes for each:
1. Your init-script.sh is probably missing critical setup steps
This is the most common reason for this error. You're referencing the script via user_data = file("init-script.sh"), but if it doesn't install and start the Apache/PHP web server, there's nothing listening on port 80 to accept connections.
For Amazon Linux 2 (the AMI you're using), your script needs to look something like this:
#!/bin/bash # Update packages and install Apache + PHP yum update -y yum install -y httpd php # Start and enable the web service so it persists after reboot systemctl start httpd systemctl enable httpd # Create a test PHP page to verify functionality echo "<?php phpinfo(); ?>" > /var/www/html/index.php
If your script skips any of these steps—like not starting httpd—the server won't respond to requests on port 80.
2. Instance-level firewall is blocking port 80
Amazon Linux 2 uses firewalld by default, which might block incoming traffic on port 80 even if your AWS security group allows it. Add these lines to your init-script.sh to open the port permanently:
firewall-cmd --add-service=http --permanent firewall-cmd --reload
Alternatively, if you don't need the instance firewall, you can disable it entirely (not recommended for production, but useful for testing):
systemctl stop firewalld systemctl disable firewalld
3. Verify your instance has public network access
Even if all firewall rules are correct, you can't connect if your EC2 instance doesn't have a public IP:
- Check the AWS EC2 console for your instance's "Public IPv4 address"—if it's blank, either enable auto-assign public IP when launching the instance (Terraform does this by default in the default VPC, but custom VPCs might not), or attach an Elastic IP to the instance.
- Make sure you're accessing the public IP (or public DNS name) of the instance, not its private IP.
4. Double-check security group association
While Terraform usually handles dependencies correctly, it's worth confirming that your web-sg security group is actually attached to the instance:
- In the EC2 console, go to your instance's "Security groups" tab to verify
web-sgis listed. - Check the security group's inbound rules to confirm TCP port 80 is allowed from
0.0.0.0/0.
Quick Debugging Steps
If you're still stuck, connect to the instance via SSH and run these commands to diagnose:
- Check if the web server is running:
systemctl status httpd - Verify port 80 is being listened to:
netstat -tulpn | grep :80 - Test connectivity from inside the instance:
curl http://localhost
内容的提问来源于stack exchange,提问作者PySquirrel

