How to Deploy a Django Project on DigitalOcean (Step-by-Step Guide with Nginx & Gunicorn)
Introduction
So, you have successfully created your DigitalOcean Droplet (if you haven't, check out our previous guide https://www.infosagar.in/blog/web-hosting/create-digitalocean-account-droplet-guide/). Now comes the exciting part: taking your Django project from your local computer and putting it live on the internet for the world to see.
Many developers find deployment intimidating because it involves the Linux command line and server configuration. But don't worry! In this guide, we will set up a Production-Ready environment using the industry-standard stack:
- Ubuntu: The Operating System.
- PostgreSQL: The Database (Robust and scalable).
- Gunicorn: The Application Server (It executes your Python code).
- Nginx: The Web Server (It handles traffic, security, and static files).
Let's dive in!
Prerequisites
- An active DigitalOcean Droplet (Ubuntu 22.04 or 24.04).
- Your Django project code uploaded to GitHub (or GitLab/Bitbucket).
A Domain Name (e.g.,
example.com) pointed to your Droplet's IP address.
Step 1: Login and Update the Server
First, open your terminal (Command Prompt or PowerShell) and log in to your server via SSH:
ssh root@YOUR_DROPLET_IPOnce inside, it is best practice to update the software repositories to ensure security:
sudo apt update
sudo apt upgrade -y
Step 2: Install Required Packages
We need to install Python, the PostgreSQL database, and Nginx. Run this command:
sudo apt install python3-pip python3-dev libpq-dev postgresql postgresql-contrib nginx curl git -y
Step 3: Configure PostgreSQL Database
Django works best with PostgreSQL in production. We need to create a database and a user.
- Log into the Postgres interactive session:
sudo -u postgres psql
2. Run the following SQL commands (Replace myproject and password with your own details):
CREATE DATABASE myproject;
CREATE USER myprojectuser WITH PASSWORD 'password123';
-- Recommended settings for Django
ALTER ROLE myprojectuser SET client_encoding TO 'utf8';
ALTER ROLE myprojectuser SET default_transaction_isolation TO 'read committed';
ALTER ROLE myprojectuser SET timezone TO 'UTC';
GRANT ALL PRIVILEGES ON DATABASE myproject TO myprojectuser;
3. Exit the database console:
\q
Step 4: Clone Project and Create Virtual Environment
- Navigate to the home directory and clone your code:
cd /home
git clone https://github.com/YOUR_GITHUB_USERNAME/YOUR_REPO_NAME.git
cd YOUR_REPO_NAME
2. Create and activate a virtual environment:
python3 -m venv venv
source venv/bin/activate
3. Install your project dependencies and Gunicorn:
pip install -r requirements.txt
pip install gunicorn psycopg2-binary
Step 5: Configure Django Settings
You need to tweak your settings.py file for production. Open it using the nano editor:
nano YOUR_PROJECT_NAME/settings.py
Make these changes:
- Allowed Hosts: Add your domain and server IP.
ALLOWED_HOSTS = ['your_domain.com', 'YOUR_SERVER_IP']
- Database: Update the
DATABASESsection with the Postgres details you created in Step 3. - Static Files: Add this line at the bottom to tell Django where to put static files:
STATIC_ROOT = os.path.join(BASE_DIR, 'static')- Debug: Set
DEBUG = False.
Save and exit (Ctrl+X, then Y, then Enter).
Now, apply migrations and collect static files:
python manage.py makemigrations
python manage.py migrate
python manage.py collectstatic
Step 6: Configure Gunicorn
Gunicorn acts as the bridge between the internet and your Python code. We will set it up as a system service so it runs in the background automatically.
Create a Socket File:
sudo nano /etc/systemd/system/gunicorn.socket
Paste this content:
Ini, TOML
[Unit]
Description=gunicorn socket
[Socket]
ListenStream=/run/gunicorn.sock
[Install]
WantedBy=sockets.target
2. Create a Service File:
sudo nano /etc/systemd/system/gunicorn.service
Paste this content (Make sure to check the paths!):
[Unit]
Description=gunicorn daemon
Requires=gunicorn.socket
After=network.target
[Service]
User=root
Group=www-data
WorkingDirectory=/home/YOUR_REPO_NAME
ExecStart=/home/YOUR_REPO_NAME/venv/bin/gunicorn \
--access-logfile - \
--workers 3 \
--bind unix:/run/gunicorn.sock \
YOUR_PROJECT_NAME.wsgi:application
[Install]
WantedBy=multi-user.target
3. Start and Enable Gunicorn:
sudo systemctl start gunicorn.socket
sudo systemctl enable gunicorn.socket
Step 7: Configure Nginx as a Reverse Proxy
Nginx will face the public internet, handle static files (CSS/Images), and pass requests to Gunicorn.
Create a new configuration file:
sudo nano /etc/nginx/sites-available/myproject
2. Paste the following configuration:
server {
listen 80;
server_name your_domain.com YOUR_SERVER_IP;
location = /favicon.ico { access_log off; log_not_found off; }
# Handling Static Files
location /static/ {
root /home/YOUR_REPO_NAME;
}
# Passing traffic to Gunicorn
location / {
include proxy_params;
proxy_pass http://unix:/run/gunicorn.sock;
}
}
3. Enable the site by creating a symbolic link:
sudo ln -s /etc/nginx/sites-available/myproject /etc/nginx/sites-enabled
4. Test Nginx for errors and restart:
sudo nginx -t
sudo systemctl restart nginx
Step 8: Security (Firewall & SSL)
Finally, let's secure the server.
- Firewall (UFW): Allow Nginx traffic and enable the firewall.
sudo ufw allow 'Nginx Full'
sudo ufw enable
2.SSL Certificate (HTTPS): We will use Certbot to get a free SSL certificate.
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d your_domain.com
Follow the prompts, and Certbot will automatically configure HTTPS for you.
Conclusion
Congratulations! ЁЯОЙ Your Django application is now successfully deployed on DigitalOcean. You can visit https://your_domain.com and see your live website.
Pro Tip: If you update your code in the future, just run git pull inside your project folder and restart Gunicorn using: sudo systemctl restart gunicorn
Troubleshooting
- 502 Bad Gateway: This usually means Gunicorn is not running. Check the logs:
sudo journalctl -u gunicorn. - Static files missing: Ensure
STATIC_ROOTis set correctly in settings.py and that you rancollectstatic. - Database connection error: Double-check your database name and password in
settings.py.
You Might Also Like
Web Development
Django Basic Commands: A Detailed Guide to manage.py (2026 Edition)
When you step into the world of Django, you quickly realize that you spend a lot of time in the terminal. Django comes with a powerful command-line utility that handles everything from starting a new project to interacting with your database.The heart of this utility is manage.pyтАФa thin wrapper around django-admin that automatically points to your project's settings.In this guide, we will break down the absolute essential Django commands every developer needs to know, categorized by their function. 1. Project Setup CommandsBefore you write a single line of Python, you need to set up the architecture of your project.django-admin startproject [project_name] This is the very first command you run. It generates the base folder structure, including your settings.py, urls.py, and the crucial manage.py file. django-admin startproject my_ecommerce python manage.py startapp [app_name] Django is based on the concept of "apps" (independent modules like users, blog, or cart). This command creates a new directory for your app with files for views, models, and tests python manage.py startapp productsNote: Don't forget to add your new app to the INSTALLED_APPS list in settings.py!2. The Development ServerTo see your work in a browser, you need a local web server. Django provides a lightweight server perfect for development.python manage.py runserver This command starts the local development server. By default, it runs on port 8000 (http://127.0.0.1:8000). It also automatically reloads whenever you save a Python file, so you don't need to restart it after every code change. python manage.py runserverTip: You can specify a custom port by adding it to the end: python manage.py runserver 8080. 3. Database & Migration CommandsDjango uses an ORM (Object-Relational Mapper), meaning you define your database structure using Python code. Migrations are how Django translates your Python code into actual SQL database tables.python manage.py makemigrations Think of this as "saving your changes." Whenever you create or modify a model in models.py, run this command. It creates a new migration file (a blueprint) of the changes. python manage.py makemigrations python manage.py migrate Think of this as "applying the changes." This command looks at the migration files created by makemigrations and actually executes the SQL to update your database. python manage.py migratepython manage.py showmigrations If you ever get confused about which migrations have been applied, this command lists all apps and shows an [X] next to migrations that are currently active in the database. 4. Admin & User ManagementDjango comes with a built-in admin panel, but to access it, you need an account.python manage.py createsuperuser This launches an interactive prompt to create an admin user with full permissions. You will be asked for a username, email, and password. python manage.py createsuperuser python manage.py changepassword [username] Forgot your admin password? No problem. This command allows you to reset the password for any user directly from the terminal. 5. Debugging & Interactive ToolsSometimes you need to test code snippets or query the database without writing a full view.python manage.py shell This command opens an interactive Python shell pre-loaded with your Django project's settings. It is the best way to test your ORM queries, debug functions, or manipulate data on the fly. python manage.py shell # Example inside the shell: # >>> from products.models import Product # >>> Product.objects.all() python manage.py dbshell This opens the command-line client of your configured database (like psql for PostgreSQL or sqlite3). You can write raw SQL queries here. 6. Deployment CommandsWhen you are ready to put your website on the internet, you will need this command.python manage.py collectstatic In development, Django serves static files (CSS, JS, images) automatically. In production, web servers like Nginx or Apache need these files in one specific folder. This command gathers all static files from your apps and puts them into the directory defined in STATIC_ROOT. python manage.py collectstatic Summary Table: Quick Reference CommandPurposestartprojectCreates a new Django project.startappCreates a new app module within the project.runserverStarts the local development server.makemigrationsPrepares database changes based on your models.migrateApplies database changes to your actual database.createsuperuserCreates an admin account.shellOpens a Python console loaded with your project environment.collectstaticGathers static files for production deployment. ConclusionMastering these basic manage.py commands is your first step toward becoming a proficient Django developer. They are the tools you will use every single day to build, test, and deploy your web applications.
Web Development
How to Add "Login with Google" to Django in 10 Minutes (The Easy Way)
Let's face it: nobody likes remembering passwords. If your website requires users to create a new account with a new password, 30% of them will just leave.The solution? Social Authentication.Allowing users to "Sign in with Google" improves User Experience (UX) and security instantly. In the Django world, the easiest way to do this is using a package called django-allauth.In this guide, we will implement a fully functional Google Login system in less than 10 minutes. Step 1: Install the PackageFirst, we need to install django-allauth. Open your terminal (or Docker container) and run: pip install django-allauth Step 2: Configure settings.pyThis is the most important step. Open your settings.py file and add the following configurations.1. Add Installed Apps: You need to add specific allauth apps to your INSTALLED_APPS list. INSTALLED_APPS = [ 'django.contrib.sites', # Required by allauth # Allauth apps 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', ] 2. Add Site ID: At the bottom of your settings file, add this line. This tells Django which "site" in the database corresponds to this settings file. SITE_ID = 1 3. Configure Middleware: Add the allauth middleware to your MIDDLEWARE list. MIDDLEWARE = [ 'allauth.account.middleware.AccountMiddleware', ] 4. Authentication Backends: Add this to allow users to log in via both the admin panel and Google. AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ] 5. Google Provider Settings: Add this configuration at the bottom of settings.py to define the scope (what data we want from Google) and redirect behavior. # Provider specific settings SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS': { 'access_type': 'online', } } } # Redirect users here after a successful login LOGIN_REDIRECT_URL = '/' # Redirect users here after logout LOGOUT_REDIRECT_URL = '/' Step 3: Update urls.pyOpen your main urls.py (the one where your admin path is). Add the allauth URLs. from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), # Add this line for Google Auth path('accounts/', include('allauth.urls')), ] Now, run migrations to create the necessary database tables: python manage.py migrate Step 4: Get API Keys from Google CloudNow we need to tell Google that our website exists.Go to the Google Cloud Console.Create a New Project (e.g., named "My Django Blog").Go to APIs & Services > OAuth consent screen.Select External.Fill in the App Name and Support Email.Click Save.Go to Credentials > Create Credentials > OAuth client ID.Application Type: Web application.Name: Django Localhost.Authorized JavaScript origins: http://127.0.0.1:8000 (or http://localhost:8000)Authorized redirect URIs: This is crucial! Enter exactly: http://127.0.0.1:8000/accounts/google/login/callback/Click Create.Copy your Client ID and Client Secret. Step 5: Connect Keys in Django AdminWe don't put keys in code (for security). We put them in the database.Run your server (python manage.py runserver) and go to http://127.0.0.1:8000/admin.Look for the Sites section.Edit the "example.com" entry.Change the Domain name to 127.0.0.1:8000 and Display Name to Localhost. Save it.Look for Social Accounts > Social applications.Click Add Social Application.Provider: Google.Name: Google API.Client id: Paste the ID you copied from Google.Secret key: Paste the Secret you copied from Google.Sites: Select your Localhost site and move it to the right side (Chosen sites).Click Save. Step 6: The "Login with Google" ButtonNow, let's put the button on your login page.In your HTML template (e.g., login.html), add this code: {% load socialaccount %} <!DOCTYPE html> <html> <head> <title>Login</title> </head> <body> <h2>Login Page</h2> <a href="{% provider_login_url 'google' %}"> <button style="background-color: #4285F4; color: white; padding: 10px; border: none; border-radius: 5px;"> Sign in with Google </button> </a> </body> </html> ConclusionThat's it! Restart your server and click the button. You will be redirected to Google, asked to select your account, and then redirected back to your website, logged in automatically.You have just saved your users the headache of remembering another password, and you did it in under 10 minutes. Happy coding!