Deploying a Django application on DigitalOcean is one of the most reliable and cost-effective ways to host your web projects in a production environment. DigitalOcean provides powerful, easy-to-use virtual servers called Droplets that make it possible to deploy a Django app from development to production with full control over your environment.
In this comprehensive 3000-word guide, we will go step by step through every detail of deploying Django on DigitalOcean — including Droplet setup, server configuration, Gunicorn and Nginx integration, database configuration, static file management, SSL setup, and more.
By the end, you will have a fully deployed, production-grade Django application running on a DigitalOcean server.
Table of Contents
- Introduction to DigitalOcean and Django Deployment
- Why Use DigitalOcean for Django Projects
- Prerequisites
- Creating a DigitalOcean Account and Droplet
- Connecting to Your Droplet via SSH
- Setting Up the Server Environment
- Installing System Packages
- Creating a Python Virtual Environment
- Cloning Your Django Project
- Installing Project Dependencies
- Configuring Environment Variables
- Running Django Migrations
- Collecting Static Files
- Testing the Django Application Locally
- Installing and Configuring Gunicorn
- Setting Up Gunicorn as a Systemd Service
- Installing and Configuring Nginx
- Setting Up Nginx to Proxy Requests to Gunicorn
- Configuring Static and Media Files in Nginx
- Testing the Deployment
- Setting Up a PostgreSQL Database (Optional)
- Enabling HTTPS with Let’s Encrypt
- Using DigitalOcean Firewall for Security
- Automating Deployment with Git
- Using the DigitalOcean App Platform
- Troubleshooting Common Issues
- Maintenance, Monitoring, and Scaling
- Best Practices for Production
- Summary and Final Thoughts
1. Introduction to DigitalOcean and Django Deployment
Django is a powerful, full-featured web framework designed for rapid development and clean, maintainable code. Once your Django application is ready for production, the next challenge is to host it securely and efficiently.
DigitalOcean is a cloud platform that provides scalable virtual machines, called Droplets, which are ideal for hosting Django applications. Each Droplet is an independent Linux-based server with full root access, giving developers complete control over configuration, performance, and security.
This guide focuses on manual deployment using Gunicorn (as the WSGI HTTP server) and Nginx (as the reverse proxy). You’ll also learn how to automate and simplify deployment using the DigitalOcean App Platform.
2. Why Use DigitalOcean for Django Projects
DigitalOcean is especially popular among developers for the following reasons:
- Simplicity: The interface is clean and easy to use, even for beginners.
- Affordability: Plans start as low as $5/month.
- Performance: SSD-based servers ensure fast response times.
- Scalability: You can resize your Droplet anytime.
- Documentation: DigitalOcean provides extensive developer-friendly tutorials.
- Full Control: Unlike managed platforms, you get root access to customize your environment.
For Django developers, this means total flexibility to configure, optimize, and scale your application based on your needs.
3. Prerequisites
Before starting, ensure that you have:
- A working Django project ready for deployment.
- A DigitalOcean account.
- Basic knowledge of using the command line and SSH.
- A domain name (optional, but recommended).
- Local environment variables and database configurations already set up.
You should also make sure your Django project runs correctly locally before deploying.
4. Creating a DigitalOcean Account and Droplet
The first step is to create a Droplet, which is a cloud-based Ubuntu server.
Steps to Create a Droplet
- Log in to your DigitalOcean account.
- Click Create → Droplets.
- Choose an Ubuntu image (for example, Ubuntu 22.04 LTS).
- Select a plan — the $5/month plan is sufficient for most small Django apps.
- Choose a data center region close to your users.
- Add an SSH key for secure login (recommended).
- Name your Droplet (e.g.,
django-server). - Click Create Droplet.
After a few minutes, your Droplet will be live. Note the public IP address assigned to it — you’ll use it to connect via SSH.
5. Connecting to Your Droplet via SSH
Use your terminal or command prompt to connect:
ssh root@your_server_ip
Replace your_server_ip with your actual Droplet’s IP address.
If you set up an SSH key, authentication will happen automatically. Otherwise, you’ll be prompted for your root password.
Once logged in, update your server:
sudo apt update && sudo apt upgrade -y
This ensures your system packages are up to date and secure.
6. Setting Up the Server Environment
It’s best practice to create a dedicated user for your Django project rather than running everything as root.
adduser django
usermod -aG sudo django
Now log in as the new user:
su - django
This user will handle all operations related to your Django application.
7. Installing System Packages
Install essential system packages required for Python, Git, and Nginx.
sudo apt install python3-venv python3-pip nginx git -y
This command installs:
- python3-venv — for creating isolated environments
- python3-pip — for installing Python packages
- nginx — for serving web traffic
- git — for pulling your project code
8. Creating a Python Virtual Environment
Inside your home directory, create a virtual environment for your Django app.
python3 -m venv myenv
source myenv/bin/activate
You’ll now see (myenv) in your shell prompt, indicating that the virtual environment is active. All Python packages installed will now stay isolated within this environment.
9. Cloning Your Django Project
Next, clone your project from GitHub or any Git repository.
git clone https://github.com/yourusername/yourproject.git
cd yourproject
You now have your Django source code inside the server.
10. Installing Project Dependencies
With your virtual environment activated, install all required dependencies.
pip install -r requirements.txt
If your project doesn’t have a requirements.txt yet, create one locally by running:
pip freeze > requirements.txt
and push it to your repository.
11. Configuring Environment Variables
In production, never store sensitive data like secret keys or database passwords in your code.
Use a .env file or environment variables.
Example .env:
SECRET_KEY=your-secret-key
DEBUG=False
ALLOWED_HOSTS=your_server_ip, yourdomain.com
DATABASE_URL=postgres://user:password@localhost/dbname
In settings.py, load environment variables using os.environ or a library like python-decouple.
12. Running Django Migrations
Run database migrations to prepare your database schema:
python manage.py migrate
This creates necessary database tables for your Django apps.
13. Collecting Static Files
Before deployment, gather all static files into one directory.
python manage.py collectstatic
Confirm that your STATIC_ROOT is properly defined in settings.py:
STATIC_ROOT = BASE_DIR / 'static/'
After this command, all your CSS, JS, and image files will be collected in /static/.
14. Testing the Django Application Locally
To verify that everything works:
python manage.py runserver 0.0.0.0:8000
Visit http://your_server_ip:8000 in your browser.
If your Django homepage appears, your app is running correctly.
15. Installing and Configuring Gunicorn
Gunicorn acts as the WSGI server between Nginx and Django.
Install Gunicorn:
pip install gunicorn
Test it with:
gunicorn --bind 0.0.0.0:8000 projectname.wsgi
If your app loads successfully, stop it with CTRL+C.
You’ll soon configure Gunicorn to run automatically.
16. Setting Up Gunicorn as a Systemd Service
Create a Gunicorn service file:
sudo nano /etc/systemd/system/gunicorn.service
Add this content:
[Unit]
Description=gunicorn daemon
After=network.target
[Service]
User=django
Group=www-data
WorkingDirectory=/home/django/yourproject
ExecStart=/home/django/myenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/django/yourproject/gunicorn.sock projectname.wsgi:application
[Install]
WantedBy=multi-user.target
Save and close.
Start and enable Gunicorn:
sudo systemctl start gunicorn
sudo systemctl enable gunicorn
Check status:
sudo systemctl status gunicorn
If active, your Django app is now being served internally via Gunicorn.
17. Installing and Configuring Nginx
Install Nginx (if not already done):
sudo apt install nginx -y
Start and enable the service:
sudo systemctl start nginx
sudo systemctl enable nginx
Nginx will act as a reverse proxy, passing web traffic to Gunicorn.
18. Setting Up Nginx to Proxy Requests to Gunicorn
Create a new Nginx configuration file:
sudo nano /etc/nginx/sites-available/yourproject
Add the following:
server {
listen 80;
server_name yourdomain.com your_server_ip;
location /static/ {
alias /home/django/yourproject/static/;
}
location /media/ {
alias /home/django/yourproject/media/;
}
location / {
include proxy_params;
proxy_pass http://unix:/home/django/yourproject/gunicorn.sock;
}
}
Enable the configuration:
sudo ln -s /etc/nginx/sites-available/yourproject /etc/nginx/sites-enabled
Test and reload Nginx:
sudo nginx -t
sudo systemctl restart nginx
Now visit http://your_server_ip — your Django site should load using Nginx and Gunicorn.
19. Configuring Static and Media Files in Nginx
Ensure Nginx can access your static and media directories. Permissions must allow the www-data group (used by Nginx) to read files.
sudo chown -R django:www-data /home/django/yourproject/static
sudo chown -R django:www-data /home/django/yourproject/media
Nginx now serves these files efficiently without passing requests to Django.
20. Testing the Deployment
Visit your domain or IP in the browser.
If you see your Django site running, the deployment is successful.
You can check logs for debugging:
sudo journalctl -u gunicorn
sudo tail -f /var/log/nginx/error.log
21. Setting Up a PostgreSQL Database (Optional)
If your project uses PostgreSQL, install and configure it:
sudo apt install postgresql postgresql-contrib -y
Switch to the postgres user:
sudo -i -u postgres
Create a database and user:
createdb mydb
createuser myuser -P
Grant privileges:
psql
GRANT ALL PRIVILEGES ON DATABASE mydb TO myuser;
\q
Update settings.py:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'mydb',
'USER': 'myuser',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': '',
}
}
Run migrations again:
python manage.py migrate
22. Enabling HTTPS with Let’s Encrypt
To secure your site with SSL, use Certbot:
sudo apt install certbot python3-certbot-nginx -y
Run the setup:
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
Certbot automatically configures Nginx and renews SSL certificates.
Check renewal:
sudo certbot renew --dry-run
Your Django app now runs securely over HTTPS.
23. Using DigitalOcean Firewall for Security
Enable the built-in firewall for your Droplet:
sudo ufw allow OpenSSH
sudo ufw allow 'Nginx Full'
sudo ufw enable
Check status:
sudo ufw status
This ensures only necessary ports (22, 80, 443) are open.
24. Automating Deployment with Git
You can automate updates using Git hooks.
Example:
cd /home/django/yourproject
git pull origin main
sudo systemctl restart gunicorn
sudo systemctl reload nginx
This allows you to push changes from your local machine and redeploy in seconds.
25. Using the DigitalOcean App Platform
If you prefer managed hosting, DigitalOcean’s App Platform simplifies everything:
- Go to Apps in your dashboard.
- Connect your GitHub repository.
- Select your Django app.
- Configure environment variables and build commands.
- Click Deploy.
DigitalOcean handles scaling, HTTPS, and deployment automatically — no manual setup required.
26. Troubleshooting Common Issues
Issue 1: 502 Bad Gateway
- Gunicorn may not be running. Restart it:
sudo systemctl restart gunicorn
Issue 2: Static Files Missing
- Ensure
collectstaticwas run and Nginx has access.
Issue 3: Permission Errors
- Adjust ownership:
sudo chown -R django:www-data /home/django/yourproject
Issue 4: Gunicorn Fails on Boot
- Check logs:
sudo journalctl -u gunicorn
27. Maintenance, Monitoring, and Scaling
For long-term maintenance:
- Keep packages updated:
sudo apt update && sudo apt upgrade - Monitor logs:
journalctland/var/log/nginx/ - Use tools like DigitalOcean Monitoring for real-time metrics
- Scale by resizing your Droplet or using Load Balancers
28. Best Practices for Production
- Always set
DEBUG=False. - Use environment variables for secrets.
- Keep your system packages updated.
- Enable automatic SSL renewal.
- Use Git for deployment control.
- Regularly back up your database and media files.
- Set up error logging and monitoring.
- Restrict file permissions strictly.
Leave a Reply