Skip to content

Deploying in Ubuntu Machine Part 2

In this video, we will setup nginx for reverse proxy and for serving static assests.

Resources

Setting up Nginx

  • Install nginx
sudo apt install nginx
  • Check the status of nginx, if its inactive, start it
sudo systemctl status nginx
sudo systemctl start nginx
  • Move to sites available directory
sudo cd /etc/nginx/sites-available/
  • Delete the default file

  • Move to sites enabled directory

sudo cd /etc/nginx/sites-enabled/
  • Delete the default file

  • Now, move to sites-available folder and Create a file named django

sudo nano /etc/nginx/sites-available/django

I have attached nginx.txt file in the resources section. Please download it and paste its content.

server {
    listen 80;

    location / {
        proxy_pass http://unix:/run/gunicorn.sock;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}
  • Now, activate the configuration
sudo ln -s /etc/nginx/sites-available/django /etc/nginx/sites-enabled
  • Restart nginx
sudo systemctl restart nginx

Static files via Nginx

  • Generate a secret key
python manage.py shell
>>> from django.core.management.utils import get_random_secret_key
>>> get_random_secret_key()
  • Add the secret key to the .env file
  • Set debug to False in .env file

  • Restart the gunicorn service

[Test the app in private mode]

  • To serve static files by nginx, open /etc/nginx/sites-available/django and add
location /static/ {
        alias /home/ubuntu/Vaccination-Scheduling-App/mysite/staticfiles/;
    }

[Nginx will throw 403 Forbidden on serving files]

  • Open nginx.conf (from /etc/nginx/) and change the user
user ubuntu;

[Check whether nginx can serve the static files]

Also restart nginx

sudo systemctl restart nginx

Media files via Nginx

  • To serve media files by nginx, open /etc/nginx/sites-available/django and add
location /media/ {
        alias /home/ubuntu/Vaccination-Scheduling-App/mysite/media/;
}

Also restart nginx

sudo systemctl restart nginx