djangoubuntunginxamazon-ec2django-wsgi

nginx 502 bad gateway error with Django webapp hosted on AWS EC2


Ever since rebooting my Ubuntu EC2 instance, I have an issue with nginx giving a 502 error for my site. I didn't change any settings before the reboot and the site was working fine before then.

Error from /var/log/nginx/error.log:

2022/12/06 21:10:54 [error] 1503#1503: *4 connect() failed (111: Unknown error) while connecting to upstream, client: ###.##.##.###, server: ##.#.###.###, request: "GET /favicon.ico HTTP/1.1", upstream: "http://127.0.0.1:8000/favicon.ico", host: "##.#.###.###", referrer: "http://##.#.###.###/"

Here is my config in /etc/nginx/sites-available/:

server_tokens               off;
access_log                  /var/log/nginx/esms.access.log;
error_log                   /var/log/nginx/esms.error.log;

# This configuration will be changed to redirect to HTTPS later
server {
  server_name               .##.#.###.###;
  listen                    80;
  location / {
    proxy_pass              http://127.0.0.1:8000;
    proxy_set_header        Host $host;
  }
  location /static {
    autoindex on;
    alias /home/ubuntu/ESMS/esms/static/;
  }
}

And the output of netstat -plnt:

 sudo netstat -plnt
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      664/sshd: /usr/sbin 
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      1567/nginx: master  
tcp        0      0 127.0.0.53:53           0.0.0.0:*               LISTEN      420/systemd-resolve 
tcp6       0      0 :::22                   :::*                    LISTEN      664/sshd: /usr/sbin 
tcp6       0      0 :::80                   :::*                    LISTEN      1567/nginx: master  

Solution

  • The django server wasn't running after reboot because it is not set up to autostart after reboot. Running the command nohup python manage.py runserver 0.0.0.0:8000 & fixes it