# Deploying a Django DRF Backend to DigitalOcean's App Platform

### 1\. Preparing the Application for Deployment

#### a. Project Structure

Ensure your Django project follows a standard structure:

```markdown
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
```

#### b. Dependencies

Create a `requirements.txt` file with the following dependencies:

```python
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
```

#### c. Dockerfile

Create a `Dockerfile` to containerize your application:

```dockerfile
# 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"]
```

#### d. GitHub Setup

1. **Create a Repository**:
    
    * Go to GitHub and create a new repository.
        
    * Initialize it with a [`README.md`](http://README.md) file and a `.gitignore` for Python.
        
2. **Push Your Code**:
    
    * Clone the repository to your local machine:
        
        ```bash
        git clone https://github.com/yourusername/yourrepository.git
        ```
        
    * Add your Django project files to the repository:
        
        ```bash
        cd yourrepository
        git add .
        git commit -m "Initial commit"
        git push origin main
        ```
        

### 2\. Setting Up DigitalOcean for Deployment

#### a. Creating a DigitalOcean App Platform Project

1. **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.
        
2. **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.
        

#### b. Configuring Environment Variables

1. **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`
            

#### c. Setting Up PostgreSQL

1. **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).
        
2. **Configure Django for PostgreSQL**:
    
    * Update your [`settings.py`](http://settings.py):
        
        ```python
        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'),
            }
        }
        ```
        

#### d. Configuring DigitalOcean Spaces

1. **Create a Space**:
    
    * Go to the "Spaces" section and create a new Space.
        
    * Configure Django to use this Space in [`settings.py`](http://settings.py):
        
        ```python
        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'
        ```
        

### 3\. Monitoring and Alerts

#### a. Setting Up Alerts to Slack

1. **Create a Slack Webhook**:
    
    * Go to your Slack workspace and create an incoming webhook in the Slack App settings.
        
    * Copy the webhook URL.
        
2. **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).
        

#### b. Monitoring with New Relic

1. **Sign Up for New Relic**:
    
    * Go to New Relic's website and sign up for an account.
        
2. **Install New Relic Agent**:
    
    * Add the New Relic Python agent to your `requirements.txt`:
        
        ```bash
        newrelic==5.24.1.148
        ```
        
    * Update your `Dockerfile` to include the New Relic agent:
        
        ```dockerfile
        # Install New Relic agent
        RUN pip install newrelic
        ```
        
3. **Configure New Relic**:
    
    * Create a `newrelic.ini` file with your New Relic license key and application name:
        
        ```python
        [newrelic]
        license_key = YOUR_NEW_RELIC_LICENSE_KEY
        app_name = YOUR_APPLICATION_NAME
        ```
        
4. **Update Your Command**:
    
    * Update the `CMD` in your `Dockerfile` to include New Relic:
        
        ```dockerfile
        CMD ["newrelic-admin", "run-program", "gunicorn", "--workers", "3", "myproject.wsgi:application", "--bind", "0.0.0.0:8000"]
        ```
        

### 4\. Accessing and Managing the Application

#### a. Accessing the Database

1. **Direct Access**:
    
    * Use a PostgreSQL client like pgAdmin or DBeaver to connect to your database using the provided connection details.
        

#### b. SSH Access to the Server

1. **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.
        

#### c. Running Celery Tasks Manually

1. **Execute Tasks**:
    
    * Open the Console from the DigitalOcean App Platform dashboard.
        
    * Run Celery tasks manually using Django management commands:
        
        ```bash
        python manage.py shell
        from yourapp.tasks import your_task
        your_task.delay()
        ```
        

### 5\. Observability and Monitoring

#### a. Setting Up Observability

1. **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.
        
2. **Integrate with Sentry**:
    
    * Sign up for Sentry and configure it in your Django project for error tracking:
        
        ```python
        # 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
        )
        ```
        

### 6\. Benefits of Using DigitalOcean App Platform

#### a. Managed Infrastructure

* **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.
    

#### b. Comparison to Manual Deployment

* **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](https://AhmadWKhan.com)
