Deploy dJango app on AWS using EC2, RDS, S3 !

Deploy dJango app on AWS using EC2, RDS, S3 !

🚀 Launch Django Project on AWS with EC2, S3, RDS, Nginx, Gunicorn! 🌐


What is EC2 Instance ? :

EC2 allows us to provision virtual servers in the cloud.

Security groups :

They are essentially virtual firewalls comprising inbound and outbound rules. These rules dictate how internet traffic is routed both inward and outward, adhering to security principles and defining constraints on internet traffic.

1. Create inbound rules & Security Groups:

- 🔒 Security Groups: Virtual firewall with inbound and outbound rules.

- ✨ Create Inbound Rules: SSH IPv4: 0.0.0.0/0 & HTTP IPv4 and IPv6: All Addresses

inbound rules

2. Create EC2 Instance

- 🚀 Ubuntu t3.micro (Free Tier eligible).

- 🔑 No key pair needed.

- 🛡️ Select existing security group.( created in first step )

- 🌐 Connect using Amazon EC2 Instance Connect.

EC2 Instance

3. Setup and Connect to Your EC2 Instance

- 🔄 Update: sudo apt-get update

- 🚀 Upgrade: sudo apt-get upgrade

- 🐍 Check Python version: python3 --version

- 📦 Install virtual env package: sudo apt-get install python3-venv

- 🏗️ Create virtual env: python -m venv env

- 📥 Install Django and clone the repo:

sudo apt-get update
sudo apt-get upgrade
python3 --version
sudo apt-get install python3-venv
python -m venv env
pip3 install django
git clone {{repo_url}}        

- 💡 Important: Project name and repo name should be same .

- 🧐 Check project name in settings.py: main.wsgi.application

4. Web Server Setup - NGINX & Gunicorn

How does Gunicorn work? It allows the Django application to communicate with our webserver and facilitates the bridging of the connection.

Supervisor : It ensures that out application is running smoothly in the background.

What is Nginx ? Nginx is a web server that can also be used as a reverse proxy, load balancer, mail proxy and HTTP cache.

- 📥 Install NGINX: sudo apt-get install -y nginx

- 🚀 Install Gunicorn: pip install gunicorn

- 🌐 Click on your EC2 IP, see 'Welcome to NGINX'.

- 🚀 Install Supervisor: sudo apt-get install supervisor

- 📝 Create Gunicorn config: sudo nano /etc/supervisor/conf.d/gunicorn.conf

- 📄 Add configuration details.

- 🔄 Confirm by checking sudo supervisorctl status. ( you must see status as RUNNING , else you have messed up in setting gunicorn configuration).

Gunicorn conf
cd /etc/supervisor/conf.d/
sudo touch gunicorn.conf
sudo nano gunicorn.conf 

[program:gunicorn]
directory = /home/ubuntu/{your_project_name}
command = /home/ubuntu/env/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/{your_project_name}/app.sock {your_project_name}.wsgi:application

autostart = true
autorestart = true
stderr_logfile = /var/log/gunicorn/gunicorn.err.log
stdout_logfile = /var/log/gunicorn/gunicorn.out.log

[group:guni]
programs = gunicorn        
sudo apt-get install -y nginx
pip install gunicorn
sudo apt-get install supervisor
sudo nano /etc/supervisor/conf.d/gunicorn.conf
sudo mkdir /var/log/gunicorn #Tells supervisor to read gunicorn conf
sudo supervisorctl reread : #output : guni available
sudo supervisorctl update : #op: guni: added process group
sudo supervisorctl status : #op: guni:gunicorn running pid 4178 uptime 0:00:17 

// make sure you dont see anything fatal only running means you have setup it correctly         

5. Configure NGINX

- 📝 Edit NGINX config: sudo nano /etc/nginx/nginx.conf

- ✏️ Change user to root.

- 📝 Create Django config: sudo nano /etc/nginx/sites-available/django.conf

- ✏️ Add server details.

- 🔄 Test NGINX syntax: sudo nginx -t

- 🔄 Enable Django config: sudo ln django.conf /etc/nginx/sites-enabled

- 🚀 Restart NGINX: sudo service nginx restart

server{

	listen 80; //80 for ipv4 and 443 for domain.com
	server_name {{ your_ipv4_address}} or domain ;

	
	location / {

		include proxy_params;
		proxy_pass http://unix:/home/ubuntu/{project}/app.sock;

	}

}

sudo nginx -t
sudo ln django.conf /etc/nginx/sites-enabled
sudo service nginx restart        

🚀 Setting Up S3 Bucket for Django: 🌐

What is S3 Bucket ?

Ans : Amazon S3 is an object storage service that offers industry-leading scalability, data availability, security, and performance.

Features :

  • Data performance and durability & Granular data control
  • Backup and restore
  • Disaster recovery
  • Security, compliance, and auditing & Flexible Storage

1. Create Your S3 Bucket

- 🌐 Head to your AWS S3 Console.

- 🎯 Scroll down to 'Public access' - Turn it OFF.

- 🔐 Enable server-side encryption.

- 🚀 Create your bucket.

- 🌍 Set public access: Create a JSON bucket policy.

     {

         "Version": "2012-10-17",

         "Statement": [

             {

                 "Effect": "Allow",

                 "Principal": "*",

                 "Action": "s3:GetObject",

                 "Resource": "arn:aws:s3:::your-bucket-name/*"

             }

         ]

     }        

- 🔥 Add statement and save.

2. Install Django Storages

- 💻 Open your command prompt.

- 🚀 Install required packages in your virtual environment:

     pip install boto3

     pip install django-storages        

3. Configure CORS Headers

- 🚀 Add CORS headers to your S3 bucket.

 [

         {

             "AllowedHeaders": [

                 "Authorization",

                 "Cross-Origin-Opener-Policy"

             ],

             "AllowedMethods": ["GET", "HEAD", "PUT","POST","DELETE],

      
             "AllowedOrigins": [

                 "http://your-ec2-ip-or-domain"

             ],

             "ExposeHeaders": [

                 "Cross-Origin-Opener-Policy"

             ],

             "MaxAgeSeconds": 3000

         }

     ]        
s3 config


And there you go! 🚀 Your Django project is now seamlessly connected to the power of Amazon S3! 🌟 Ready to handle all your static files effortlessly. 🚀💻


🌐 Django RDS Setup

1. Install Postgres Adapter

- 🚀 Open your terminal.

- 💻 Run:

pip install psycopg2-binary        

2. Create RDS Database Instance

- 🌐 Head to your AWS RDS Console.

- 🚀 Create a database instance:

- Engine: PostgreSQL

- Version: Latest (e.g., 15.4 r1)

- Instance Type: t3.micro (Free Tier eligible)

- Storage: 20GB General Purpose SSD

- Enable Auto Scaling

- Public Access: Yes (for now)

- Database Name: your-db-name

- Inbound Rules: Allow traffic from IPv4 and IPv6 addresses.

- Attach to security group mentioned at the start.

- Set a password.

RDS details


3. Update Django Settings

- 🚀 Open your settings.py.

- 🔧 Replace your database settings:

 #setting.py AWS RDS Configuration
 DATABASES = {

         'default': {

             'ENGINE': 'django.db.backends.postgresql',

             'NAME': 'your-db-name',

             'USER': 'username',

             'PASSWORD': 'password',

             'HOST': '%dblink%',

             'PORT': '5432',

         }

     }        

4. Migrate Your Models to PostgreSQL

- 🚀 Run in your terminal:

     python manage.py makemigrations

     python manage.py migrate        

5. Test the Integration

- 🚀 If it takes a moment, it's working!

- 💻 Create a superuser:

     python manage.py createsuperuser        

- 🌐 Test it! You've seamlessly integrated your Django project with AWS PostgreSQL.

That's it from my side thank you for reading feel free to reach me out if faced any problems related to aws + django :) .



Sahil Sagwekar

Python Developer | AWS & GCP Certified

11mo

Helpful article!

To view or add a comment, sign in

Insights from the community

Others also viewed

Explore topics