How to Fix Nginx Connection Refused on AWS EC2
The Root Cause “Nginx Connection Refused” on AWS EC2 typically means the connection attempt successfully reached the EC2 instance, but the operating system actively rejected it because no process was listening on the target port. While AWS Security Groups act as network firewalls, they usually result in a “Connection Timed Out” error if traffic is blocked, not “Connection Refused.” The core issue is almost always that the Nginx service is not running or is misconfigured to listen on an inaccessible address.
Quick Fix (CLI)
# Check the status of the Nginx service
sudo systemctl status nginx
# If Nginx is not running, start it
sudo systemctl start nginx
# Enable Nginx to start on boot (ensures persistence after reboot)
sudo systemctl enable nginx
# If Nginx was running but misbehaving, restart it
sudo systemctl restart nginx
Configuration Check Examine your Nginx configuration to ensure it’s listening on the correct network interface and port.
-
File to Edit: Typically
/etc/nginx/nginx.confor a site-specific configuration file within/etc/nginx/sites-available/(then symlinked to/etc/nginx/sites-enabled/defaultor similar). -
Lines to Change/Verify: Ensure your
httpblock andserverblocks containlistendirectives that are not exclusively bound to127.0.0.1unless intended. For public access, you generally want Nginx to listen on all available interfaces.# Example within a server block or http block: server { listen 80; # Listen on port 80 for all IPv4 interfaces listen [::]:80; # Listen on port 80 for all IPv6 interfaces server_name your_domain.com www.your_domain.com; # ... other configurations }After any configuration changes, test the Nginx configuration syntax and then restart Nginx:
sudo nginx -t sudo systemctl restart nginx
Verification
# Verify Nginx service status again
sudo systemctl status nginx
# Verify Nginx is listening on the expected port (e.g., 80)
sudo ss -tulpn | grep 80 | grep nginx
# Expected output similar to: tcp LISTEN 0 511 *:80 *:* users:(("nginx",pid=1234,fd=6))
# Test connectivity from the EC2 instance itself
curl -v http://localhost
# Test connectivity from an external machine using the EC2 instance's public IP or DNS
# Replace YOUR_EC2_PUBLIC_IP_OR_DNS with the actual value
curl -v http://YOUR_EC2_PUBLIC_IP_OR_DNS