Overview
This guide walks you through deploying a Django app on an Amazon EC2 Linux instance using both Apache (httpd) and Nginx + Gunicorn. Choose what fits your stack best!
1. Launch EC2 & Connect via SSH
- Launch Amazon Linux 2 or Ubuntu 22.04 instance
- Open ports: 22 (SSH), 80 (HTTP), 443 (HTTPS)
- SSH into EC2:
ssh -i "your-key.pem" ec2-user@your-ec2-ip
2. Install Python & Django
sudo yum update -y
sudo yum install python3 git -y
pip3 install virtualenv
3. Clone Your Django App
git clone https://github.com/yourusername/yourproject.git
cd yourproject
virtualenv venv
source venv/bin/activate
pip install -r requirements.txt
python manage.py migrate
Option 1: Use Apache (httpd) with mod_wsgi
🔧 Install Apache & mod_wsgi
sudo yum install httpd httpd-devel gcc python3-devel -y
pip install mod_wsgi
mod_wsgi-express install-module | sudo tee /etc/httpd/conf.modules.d/02-wsgi.conf
🛠️ Create Apache VirtualHost
sudo nano /etc/httpd/conf.d/yourproject.conf
Add this:
WSGIDaemonProcess yourproject python-path=/home/ec2-user/yourproject:/home/ec2-user/yourproject/venv/lib/python3.7/site-packages
WSGIProcessGroup yourproject
WSGIScriptAlias / /home/ec2-user/yourproject/yourproject/wsgi.py
Require all granted
Alias /static/ /home/ec2-user/yourproject/static/
Require all granted
📦 Collect Static Files
python manage.py collectstatic
🚀 Start Apache
sudo systemctl start httpd
sudo systemctl enable httpd
Option 2: Use Gunicorn with Nginx
📦 Install Dependencies
sudo yum install nginx -y
pip install gunicorn
🚀 Run Gunicorn
gunicorn --workers 3 yourproject.wsgi:application --bind 127.0.0.1:8000
🔧 Nginx Config
sudo nano /etc/nginx/conf.d/yourproject.conf
Add:
server {
listen 80;
server_name your-ec2-ip;
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
location /static/ {
alias /home/ec2-user/yourproject/static/;
}
}
sudo systemctl restart nginx
sudo systemctl enable nginx
Optional: Enable HTTPS with Certbot
sudo yum install epel-release
sudo yum install certbot python3-certbot-nginx -y
sudo certbot --nginx -d yourdomain.com
Final Tips
- Set
DEBUG = False
insettings.py
- Use environment variables for secrets
- Configure
ALLOWED_HOSTS
properly
That's it! Your Django app is now live on an EC2 instance using either Apache or Nginx. 🥳