Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/diegolozadev/DataMed/llms.txt

Use this file to discover all available pages before exploring further.

Deployment Guide

DataMed is designed for easy deployment to modern cloud platforms. This guide covers deployment to Render (recommended), Docker, and traditional hosting.

Quick Deployment to Render

Render is the recommended platform for DataMed. The application includes pre-configured files for one-click deployment.
1

Prepare Repository

Ensure your DataMed repository is on GitHub, GitLab, or Bitbucket.
2

Create Render Account

Sign up at render.com if you don’t have an account.
3

Create Web Service

  • Click NewWeb Service
  • Connect your repository
  • Render auto-detects Django settings
4

Configure Service

Set these values:
  • Name: datamed
  • Environment: Python 3
  • Build Command: ./build.sh
  • Start Command: gunicorn config.wsgi
5

Add Environment Variables

Configure in Render dashboard:
  • SECRET_KEY: Generate with python -c "from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())"
  • PYTHON_VERSION: 3.11.0
  • DATABASE_URL: Auto-populated if you add PostgreSQL
6

Add PostgreSQL Database

  • Click NewPostgreSQL
  • Name: datamed-db
  • Link to your web service (auto-sets DATABASE_URL)
7

Deploy

Click Create Web Service. Render will:
  1. Install dependencies from requirements.txt
  2. Run collectstatic for static files
  3. Apply database migrations
  4. Start Gunicorn server

Build Script

DataMed includes build.sh for automated deployment:
build.sh
#!/usr/bin/env bash
set -o errexit

# Install dependencies
pip install -r requirements.txt

# Collect static files
python manage.py collectstatic --no-input

# Apply database migrations
python manage.py migrate

# Verify migrations
echo "LOG: Verificando estado de la base de datos..."
python manage.py showmigrations

echo "LOG: Intentando migrar..."
python manage.py migrate --noinput

echo "LOG: Verificando si las tablas se crearon..."
python manage.py inspectdb | head -n 20
Key Features:
  • set -o errexit: Stops on any error
  • Multiple migration attempts for reliability
  • Verification logs for debugging

Procfile Configuration

The Procfile defines how to run DataMed in production:
Procfile
web: python manage.py migrate --noinput && python manage.py collectstatic --noinput && gunicorn config.wsgi
Command Breakdown:
  1. migrate --noinput: Apply database migrations automatically
  2. collectstatic --noinput: Gather static files for WhiteNoise
  3. gunicorn config.wsgi: Start production WSGI server

Environment Configuration

Required Environment Variables

SECRET_KEY
string
required
Django secret key for cryptographic operations. Must be unique and kept secret.Generate: python -c "from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())"
DATABASE_URL
string
required
PostgreSQL connection string. Automatically set by Render when you attach a database.Format: postgresql://user:password@host:5432/database
RENDER
string
Triggers production mode when present (any value). Disables DEBUG and enables PostgreSQL.Value: true or any non-empty string

Production Settings Triggered by RENDER

When RENDER is set, DataMed automatically:
config/settings.py
DEBUG = 'RENDER' not in os.environ  # False in production

if not DEBUG:
    # Use PostgreSQL
    DATABASES = {
        'default': dj_database_url.config(
            default=os.environ.get('DATABASE_URL'),
            conn_max_age=600,
        )
    }
    
    # Configure static files
    STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
    STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

Docker Deployment

Deploy DataMed using Docker for containerized environments.

Dockerfile

Dockerfile
FROM python:3.11-slim

# Set environment variables
ENV PYTHONUNBUFFERED=1 \
    PYTHONDONTWRITEBYTECODE=1

# Set work directory
WORKDIR /app

# Install system dependencies
RUN apt-get update && apt-get install -y \
    postgresql-client \
    && rm -rf /var/lib/apt/lists/*

# Install Python dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Copy project
COPY . .

# Collect static files
RUN python manage.py collectstatic --noinput

# Run migrations and start server
CMD python manage.py migrate --noinput && \
    gunicorn config.wsgi:application --bind 0.0.0.0:8000

Docker Compose

docker-compose.yml
version: '3.8'

services:
  db:
    image: postgres:15
    environment:
      POSTGRES_DB: datamed
      POSTGRES_USER: datamed_user
      POSTGRES_PASSWORD: secure_password
    volumes:
      - postgres_data:/var/lib/postgresql/data
  
  web:
    build: .
    command: gunicorn config.wsgi:application --bind 0.0.0.0:8000
    volumes:
      - .:/app
      - static_volume:/app/staticfiles
    ports:
      - "8000:8000"
    environment:
      - SECRET_KEY=your-secret-key-here
      - DATABASE_URL=postgresql://datamed_user:secure_password@db:5432/datamed
      - RENDER=true
    depends_on:
      - db

volumes:
  postgres_data:
  static_volume:

Running with Docker Compose

# Build and start services
docker-compose up -d

# Create superuser
docker-compose exec web python manage.py createsuperuser

# View logs
docker-compose logs -f web

# Stop services
docker-compose down

Traditional Server Deployment

Deploy to a VPS or dedicated server with Ubuntu/Debian.
1

Install System Dependencies

sudo apt update
sudo apt install python3.11 python3.11-venv python3-pip postgresql nginx
2

Create Database

sudo -u postgres psql
CREATE DATABASE datamed;
CREATE USER datamed_user WITH PASSWORD 'secure_password';
GRANT ALL PRIVILEGES ON DATABASE datamed TO datamed_user;
\q
3

Clone and Setup Application

cd /opt
git clone https://github.com/diegolozadev/DataMed.git
cd DataMed
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
4

Configure Environment

Create .env file:
SECRET_KEY=your-secret-key
DATABASE_URL=postgresql://datamed_user:secure_password@localhost:5432/datamed
RENDER=true
5

Run Migrations and Collect Static

python manage.py migrate
python manage.py collectstatic --noinput
python manage.py createsuperuser
6

Configure Gunicorn Service

Create /etc/systemd/system/datamed.service:
[Unit]
Description=DataMed Gunicorn
After=network.target

[Service]
User=www-data
Group=www-data
WorkingDirectory=/opt/DataMed
Environment="PATH=/opt/DataMed/venv/bin"
ExecStart=/opt/DataMed/venv/bin/gunicorn \
          --workers 3 \
          --bind unix:/opt/DataMed/datamed.sock \
          config.wsgi:application

[Install]
WantedBy=multi-user.target
Enable and start:
sudo systemctl enable datamed
sudo systemctl start datamed
7

Configure Nginx

Create /etc/nginx/sites-available/datamed:
server {
    listen 80;
    server_name your-domain.com;
    
    location = /favicon.ico { access_log off; log_not_found off; }
    
    location /static/ {
        alias /opt/DataMed/staticfiles/;
    }
    
    location / {
        proxy_pass http://unix:/opt/DataMed/datamed.sock;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}
Enable and restart:
sudo ln -s /etc/nginx/sites-available/datamed /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx
8

Setup SSL with Let's Encrypt

sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d your-domain.com

Post-Deployment Tasks

1

Create Superuser

python manage.py createsuperuser
2

Verify Static Files

Visit https://your-domain.com/static/ and confirm CSS/JS loads.
3

Test Authentication

Log in with superuser credentials and verify dashboard access.
4

Create Test Patient

Register a test patient to verify all forms and workflows.
5

Setup Monitoring

Configure uptime monitoring and error tracking (see Monitoring section below).

Monitoring and Logging

Application Logs

Gunicorn logs requests and errors:
# View recent logs (Render)
render logs --service datamed

# View logs (systemd)
sudo journalctl -u datamed -f

# View Nginx logs
sudo tail -f /var/log/nginx/error.log

Health Checks

Implement health check endpoint:
config/urls.py
from django.http import JsonResponse

def health_check(request):
    return JsonResponse({'status': 'ok'})

urlpatterns = [
    path('health/', health_check, name='health'),
    # ... other patterns
]

Database Backups

# Backup PostgreSQL
pg_dump -h localhost -U datamed_user datamed > backup_$(date +%Y%m%d).sql

# Restore from backup
psql -h localhost -U datamed_user datamed < backup_20260305.sql

Troubleshooting

Symptom: CSS/JS missing, pages unstyledSolution:
python manage.py collectstatic --noinput
# Verify STATIC_ROOT in settings.py
# Check WhiteNoise middleware position
Symptom: OperationalError: could not connect to serverSolution:
  • Verify DATABASE_URL is set correctly
  • Check PostgreSQL is running: sudo systemctl status postgresql
  • Test connection: psql $DATABASE_URL
Symptom: Generic error pageSolution:
# Check logs for detailed error
render logs --tail
# or
sudo journalctl -u datamed -n 50
Symptom: Forms return CSRF errorSolution:
  • Add your domain to CSRF_TRUSTED_ORIGINS in settings.py
  • Ensure you’re using HTTPS in production

Scaling Considerations

Horizontal Scaling

  • Multiple Gunicorn Workers: Increase --workers flag (typically 2 * CPU_CORES + 1)
  • Load Balancer: Use Nginx or cloud load balancer for multiple application servers
  • Database Connection Pooling: Consider PgBouncer for high traffic

Vertical Scaling

  • Render: Upgrade to higher-tier plan for more RAM/CPU
  • VPS: Resize instance or migrate to more powerful server

Caching

Add Redis caching for improved performance:
settings.py
CACHES = {
    'default': {
        'BACKEND': 'django_redis.cache.RedisCache',
        'LOCATION': os.environ.get('REDIS_URL', 'redis://127.0.0.1:6379/1'),
    }
}

Next Steps

Configuration

Fine-tune environment and security settings

Database Schema

Understand the data model

Backup & Restore

Implement backup strategies

User Management

Create and manage user accounts