How to Fix Nginx Timeout Error on AWS EC2


The Root Cause

Nginx timeout errors on AWS EC2 primarily occur when the backend application, often running on the same or an adjacent EC2 instance, fails to respond within the default proxy_read_timeout limit. This is frequently due to resource contention (CPU/memory exhaustion) on the EC2 instance slowing down the application, or underlying network latency and connection issues when Nginx is proxying to another service.

Quick Fix (CLI)

  1. Check Nginx Status and Restart:

    sudo systemctl status nginx
    sudo systemctl restart nginx
  2. Inspect Nginx Error Logs for Clues:

    sudo tail -f /var/log/nginx/error.log
  3. Check Backend Application Status (Example for a systemd service or Docker container):

    sudo systemctl status my-backend-service.service # Replace with your actual service name
    # OR
    sudo docker ps # To check if your containerized backend is running
    sudo docker logs <container_id_or_name> # To check logs of a specific container

Configuration Check

Edit the relevant Nginx configuration file. This is typically found at /etc/nginx/nginx.conf, within a site-specific configuration file in /etc/nginx/sites-available/ (e.g., default), or directly within a Dockerfile if Nginx is containerized.

File to Edit: /etc/nginx/nginx.conf or /etc/nginx/sites-available/your-site.conf

Lines to Change: Add or adjust the following directives within the http, server, or location block where the proxy is defined. Increase the timeout values as necessary. Values are in seconds.

http {
    # ... other http directives ...

    proxy_connect_timeout 60s; # Timeout for connecting to the upstream server
    proxy_send_timeout    60s; # Timeout for sending a request to the upstream server
    proxy_read_timeout    60s; # Timeout for reading a response from the upstream server

    # If you have large file uploads that time out
    client_max_body_size  20M; # Increase max body size if files are large (e.g., 20MB)

    server {
        # ... other server directives ...

        location / {
            proxy_pass http://your_backend_ip_or_domain:port;
            # You can override http-level timeouts here if needed for specific locations
            # proxy_connect_timeout 120s;
            # proxy_send_timeout    120s;
            # proxy_read_timeout    300s; # Example: allowing up to 5 minutes for response
            # ... other location directives ...
        }
    }
}

Verification

  1. Test Nginx Configuration Syntax:

    sudo nginx -t

    Ensure the output states syntax is ok and test is successful.

  2. Reload Nginx to Apply Changes:

    sudo systemctl reload nginx
  3. Test the Application Endpoint:

    curl -v http://your_domain_or_ec2_ip/your-affected-endpoint

    Monitor the Nginx access and error logs in a separate terminal:

    sudo tail -f /var/log/nginx/access.log /var/log/nginx/error.log