Deploying a Django app helps you run your web application on a live server. This guide shows step-by-step instructions how to set up Django, configure the Ubuntu server, and make the app accessible online.
1. Install required Software
sudo apt update && sudo apt install python3 python3-pip python3-venv git -y
2. Clone your Django App
- move to your home directory:
cd ~
- clone your repository:
git clone https://github.com/yourusername/your-django-project.git
cd your-django-project
. create a virtual environment:
python -m venv venv
- activate it:
source venv/bin/activate
- install dependencies:
pip install -r requirements.txt
3. Setup Gunicorn
Gunicorn is a Python WSGI server. WSGI (Web Server Gateway Interface) is a standard for connecting Python web applications (like Django) with web servers. It helps the server communicate with the app and handle user requests smoothly.
- install gunicorn:
pip install gunicorn
- test if gunicorn runs your app:
gunicorn --bind 0.0.0.0:8000 myproject.wsgi
The myproject.wsgi should point to the wsgi.py file in your project. This file helps connect Django to a web server.
4. Use Supervisor
Supervisor keeps your Django app running in the background. If the server restarts, Supervisor automatically restarts Gunicorn.
- install supervisor:
sudo apt install supervisor -y
- create a config file for your Django app:
sudo nano /etc/supervisor/conf.d/django.conf
- add this content:
[program:django]
command=/home/myuser/your-django-project/venv/bin/gunicorn --workers 3 --bind unix:/home/myuser/your-django-project/django.sock your_project.wsgi directory=/home/myuser/your-django-project user=myuser autostart=true autorestart=true stderr_logfile=/var/log/django_err.log stdout_logfile=/var/log/django_out.log
- restart supervisor:
sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start django
5. Setup Nginx
Nginx is a reverse proxy that works in front of Gunicorn. It handles incoming requests and forwards them to Gunicorn.
- install nginx:
sudo apt update && sudo apt install nginx -y
- create a new nginx config:
sudo nano /etc/nginx/sites-available/myproject
- add this content:
server {
listen 80;
server_name your_domain_or_IP;
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
location /static/ {
alias /path/to/your/project/static/;
}
location /media/ {
alias /path/to/your/project/media/;
}
}
- enable the config:
sudo ln -s /etc/nginx/sites-available/myproject /etc/nginx/sites-enabled/
- check for errors:
sudo nginx -t
- restart nginx:
sudo systemctl restart nginx
- allow nginx through firewall:
sudo ufw allow 'Nginx Full'
6. Verify the setup
Visit your server’s IP or domain in a browser. If everything is set up correctly, your Django app should be live!