How to Fix Nginx Connection Refused on Ubuntu 22.04


  1. The Root Cause The “Connection Refused” error on Ubuntu 22.04 typically indicates that no process is actively listening on the requested network port, or that a firewall is explicitly rejecting the connection attempt. Most commonly, this is due to the Nginx service not running, or Ubuntu’s default firewall (UFW) being enabled without rules to allow HTTP (port 80) and HTTPS (port 443) traffic.

  2. Quick Fix (CLI)

    # 1. Check Nginx service status. If not 'active (running)', start and enable it.
    sudo systemctl status nginx
    sudo systemctl start nginx
    sudo systemctl enable nginx
    
    # 2. Check UFW (Uncomplicated Firewall) status.
    # If UFW is active and Nginx ports (80/443) are not explicitly allowed.
    sudo ufw status verbose
    
    # Allow Nginx Full profile (opens both 80 and 443).
    # Choose 'Nginx HTTP' for port 80 only, 'Nginx HTTPS' for port 443 only.
    sudo ufw allow 'Nginx Full'
    
    # If UFW was previously inactive and you enabled it, ensure SSH is allowed.
    # sudo ufw allow ssh
    
    # If UFW was disabled, enable it (this step is critical if UFW was off).
    # sudo ufw enable
    
    # Reload UFW to apply new rules immediately if UFW was already active.
    sudo ufw reload
  3. Configuration Check

    • File to edit: /etc/nginx/sites-available/default or your specific site’s configuration file (e.g., /etc/nginx/sites-available/your_domain.conf).
    • Lines to change: Verify that Nginx is configured to listen on the correct IP addresses and ports within your server blocks. Ensure listen 80; and potentially listen [::]:80; (for IPv6) are present. For HTTPS, check for listen 443 ssl; and listen [::]:443 ssl;.
    # Example snippet from an Nginx server block:
    server {
        listen 80;              # Listen for IPv4 HTTP connections
        listen [::]:80;         # Listen for IPv6 HTTP connections
        # listen 443 ssl;       # For HTTPS (uncomment and configure SSL if needed)
        # listen [::]:443 ssl;  # For IPv6 HTTPS
    
        # ... other server configurations ...
    }

    After modifying any Nginx configuration file:

    sudo nginx -t                  # Test Nginx configuration for syntax errors
    sudo systemctl reload nginx    # Apply changes without stopping the service
  4. Verification

    # Verify Nginx is listening on the expected ports (80, 443)
    sudo ss -tuln | grep -E "80|443"
    
    # Test connectivity from the server itself using curl
    curl -I http://localhost
    
    # Test connectivity from a remote machine (replace with your server's IP or domain)
    # Open a terminal on a *different* machine and run:
    # curl -I http://your_server_ip_or_domain