Deploying a Django DRF Backend to DigitalOcean's App Platform

Search for a command to run...

No comments yet. Be the first to comment.
There's a question that most people feel but almost nobody says out loud. Not because it's complicated. Because saying it threatens everything built on top of not saying it. The question is simple. Wh

Public discourse around personal finance in India increasingly relies on lifestyle narratives, absolute numbers, and loosely imported benchmarks. Concepts such as middle class, financial security, high income, or wealthy are often used without refere...

By Ahmad W Khan (interactive at https://ahmadwkhan.com/india-work-landscape) Summary (TL;DR): India’s labour market is vast, diversified, and uneven. Government roles remain tenure‑rich but hard to enter; healthcare and licensed professional practice...

Audience: Intermediate PHP devs (comfortable with OOP, Composer, basic MVC) who are new/rusty with SymfonyOS Assumptions: macOS/Linux primary; Windows notes included (PowerShell + WSL2)Target PHP & Symfony: PHP 8.2+ and Symfony 7.3.x (current stable ...

Money, unlike geography, is invisible.We know where a country starts and ends on a map. But wealth and income? They’re like air currents, everywhere, yet hard to see. Percentiles help make them visible: where do you sit compared to your neighbors, yo...

Ensure your Django project follows a standard structure:
myproject/
├── myproject/
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── app/
│ ├── migrations/
│ ├── __init__.py
│ ├── models.py
│ ├── views.py
│ └── serializers.py
├── manage.py
├── requirements.txt
└── Dockerfile
Create a requirements.txt file with the following dependencies:
Django==3.2
djangorestframework==3.12.4
gunicorn==20.0.4
psycopg2-binary==2.8.6
boto3==1.17.27
django-storages==1.11.1
Create a Dockerfile to containerize your application:
# Use the official Python image.
FROM python:3.8-slim
# Set the working directory.
WORKDIR /app
# Copy the requirements file.
COPY requirements.txt .
# Install dependencies.
RUN pip install --no-cache-dir -r requirements.txt
# Copy the rest of the application code.
COPY . .
# Collect static files.
RUN python manage.py collectstatic --noinput
# Expose port 8000 and run the application.
EXPOSE 8000
CMD ["gunicorn", "--workers", "3", "myproject.wsgi:application", "--bind", "0.0.0.0:8000"]
Create a Repository:
Go to GitHub and create a new repository.
Initialize it with a README.md file and a .gitignore for Python.
Push Your Code:
Clone the repository to your local machine:
git clone https://github.com/yourusername/yourrepository.git
Add your Django project files to the repository:
cd yourrepository
git add .
git commit -m "Initial commit"
git push origin main
Create a New Project:
Log in to your DigitalOcean account and navigate to the "Projects" section.
Click "New Project" and fill in the required details.
Deploy a New App:
Go to the App Platform and click "Launch Your App".
Select "GitHub" as your source repository and connect your GitHub account.
Choose the repository and branch (e.g., main) you want to deploy.
Add Environment Variables:
Go to your App in the App Platform.
Navigate to "Settings" and then "Environment Variables".
Add the following environment variables:
DJANGO_SECRET_KEY
DJANGO_DEBUG=False
DATABASE_URL=postgres://USER:PASSWORD@HOST:PORT/DBNAME
AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY
AWS_STORAGE_BUCKET_NAME
Create a PostgreSQL Database:
Go to the "Databases" section and create a new PostgreSQL database.
Note down the connection details (host, port, username, password, database name).
Configure Django for PostgreSQL:
Update your settings.py:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': os.getenv('DB_NAME'),
'USER': os.getenv('DB_USER'),
'PASSWORD': os.getenv('DB_PASSWORD'),
'HOST': os.getenv('DB_HOST'),
'PORT': os.getenv('DB_PORT'),
}
}
Create a Space:
Go to the "Spaces" section and create a new Space.
Configure Django to use this Space in settings.py:
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY')
AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME')
AWS_S3_ENDPOINT_URL = 'https://nyc3.digitaloceanspaces.com'
Create a Slack Webhook:
Go to your Slack workspace and create an incoming webhook in the Slack App settings.
Copy the webhook URL.
Configure DigitalOcean Alerts:
In your DigitalOcean App Platform project, go to "Monitoring & Alerts".
Create a new alert policy and set it to send alerts to your Slack webhook URL.
Choose the metrics you want to monitor (e.g., CPU usage, memory usage).
Sign Up for New Relic:
Install New Relic Agent:
Add the New Relic Python agent to your requirements.txt:
newrelic==5.24.1.148
Update your Dockerfile to include the New Relic agent:
# Install New Relic agent
RUN pip install newrelic
Configure New Relic:
Create a newrelic.ini file with your New Relic license key and application name:
[newrelic]
license_key = YOUR_NEW_RELIC_LICENSE_KEY
app_name = YOUR_APPLICATION_NAME
Update Your Command:
Update the CMD in your Dockerfile to include New Relic:
CMD ["newrelic-admin", "run-program", "gunicorn", "--workers", "3", "myproject.wsgi:application", "--bind", "0.0.0.0:8000"]
Direct Access:
Console Access:
DigitalOcean App Platform doesn't provide direct SSH access to managed app instances.
For tasks like running Celery manually, use the "Console" feature in the DigitalOcean dashboard.
Execute Tasks:
Open the Console from the DigitalOcean App Platform dashboard.
Run Celery tasks manually using Django management commands:
python manage.py shell
from yourapp.tasks import your_task
your_task.delay()
DigitalOcean Insights:
Enable application insights and monitoring in the DigitalOcean App Platform.
Configure logging and metrics to get detailed insights into your application's performance.
Integrate with Sentry:
Sign up for Sentry and configure it in your Django project for error tracking:
# settings.py
import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration
sentry_sdk.init(
dsn="YOUR_SENTRY_DSN",
integrations=[DjangoIntegration()],
traces_sample_rate=1.0,
send_default_pii=True
)
Ease of Use: Simplifies the deployment process by managing infrastructure for you.
Scalability: Easily scale applications up or down based on demand without manual intervention.
Built-in Monitoring: Integrated monitoring and alerting tools to keep track of application performance.
Time-Saving: Reduces the time spent on setting up and managing servers.
Reduced Complexity: Avoids the complexity of managing OS-level configurations and dependencies.
Enhanced Security: Ensures the latest security patches and updates are applied automatically.
This detailed guide covers the complete process of deploying a Python-DRF application to DigitalOcean's App Platform, including setup, monitoring, and management. By following these steps, you can ensure a smooth and efficient deployment process for your Django application.
For further help, you can visit me at AhmadWKhan.com