read-tech

Deploy Django in AWS Ec2

August 20, 2023

In this article we'll learn how to Deploy a Django Application on AWS EC2 using Gunicorn, Supervisor and Nginx.

Note: You should have an AWS account or EC2 login to proceed with this Article. If you have an EC2 login make sure you have the PEM file.

Log In to EC2 server

Let's start by logging into EC2 using ssh

ssh -i ~/path-to-pem-file user@public-ip-of-ec2

Clone Django Repository to EC2

Once you successfully log in to EC2, clone your Django repo to var/www/ folder. Make sure to have your Github login to Clone the Repository without any issues.

git clone https://github.com/example.git

Install Python and Setup virtual env

sudo apt update
sudo apt-get install python3.8 python3-virtualenv

Go to the Project folder and create a virtualenv

cd /var/www/Project
virtualenv venv -p python3

Active the virtual env

. venv/bin/activate 

Install the Project Requirements

After activating the env install the project requirements

pip install -r /path/to/requirement/file

Gunicorn and Supervisor Configuration

Install Gunicorn

Make sure Gunicorn is installed in your project env or your ec2 machine.

pip install gunicorn

Install and enable supervisor

sudo apt install supervisor
sudo systemctl enable --now supervisor

Create a supervisor config for your Django project

cd /etc/supervisor/conf.d/

Create a file with Nano or Vi and use this Configuration, you can update it according to your need

Number of workers should be (2*CPU) + 1

[program:django]
command=/path/to/project/.venv/bin/gunicorn --workers 3 --bind 127.0.0.1:8000 main.wsgi
directory=/path/to/project/main
autostart=true
autorestart=true
stderr_logfile=/var/log/myproject.err.log
stdout_logfile=/var/log/myproject.out.log

If all the Configurations are correct, you should be able to access your running Application in http://ec2-public-ip:8000

If port 8000 is not accessible make sure this port is opened in your security inbound rules, you can verify this in the AWS console.

Nginx Configuration

Now that our Application is up and running, Let's configure Nginx to proxy our request to Gunicorn.

Let's install Nginx and enable it

sudo apt install nginx
sudo systemctl enable --now nginx

Now create a config file for the project in /etc/nginx/sites-available/ folder

server {
    listen 80;

    location /static/ {
                alias /path/to/project/main/static/;
    }

    location / {
        proxy_pass 127.0.0.1:8000;
    }
}

Remove other enabled sites and create a symlink for our project

sudo rm -rf /etc/sites-enabled/*
sudo ln -s /etc/nginx/sites-available/project /etc/nginx/sites-enabled/project

Restart Nginx

sudo systemctl restart nginx

This will forward all requests to port 8000, which means you can now access your Application in http://ec2-public-ip

Thanks for reading!