Prerequisites
sudo apt install -y python3 python3-pip python3-venv nginxDeploy Your Application
cd /var/www
git clone https://github.com/yourname/myapp.git
cd myapp
# Create virtual environment
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
pip install gunicornConfigure Django for Production
In settings.py:
DEBUG = False
ALLOWED_HOSTS = ["example.com", "www.example.com"]
STATIC_ROOT = "/var/www/myapp/staticfiles"
# Run collectstatic
python manage.py collectstatic --noinput
python manage.py migrateGunicorn Service
Create /etc/systemd/system/gunicorn.service:
[Unit]
Description=Gunicorn Django
After=network.target
[Service]
User=www-data
Group=www-data
WorkingDirectory=/var/www/myapp
ExecStart=/var/www/myapp/venv/bin/gunicorn --workers 3 --bind unix:/run/gunicorn.sock myapp.wsgi:application
[Install]
WantedBy=multi-user.targetsudo systemctl enable --now gunicornNginx Configuration
server {
listen 80;
server_name example.com;
location /static/ {
alias /var/www/myapp/staticfiles/;
}
location /media/ {
alias /var/www/myapp/media/;
}
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;
}
}SSL
sudo certbot --nginx -d example.comEnvironment Variables
Store secrets in an .env file or use systemd environment variables — never commit secrets to git:
# In gunicorn.service
Environment=DJANGO_SECRET_KEY=your-secret-key
Environment=DATABASE_URL=postgres://...