CODITECT Cloud Backend - Deployment Guide
Complete deployment guide for Django 5.2.8 backend on Google Kubernetes Engine (GKE).
Table of Contents
- Prerequisites
- Initial Setup
- Configuration
- Deployment Methods
- Post-Deployment
- Monitoring
- Troubleshooting
- Rollback
Prerequisites
Required Tools
- Docker 20.10+ - Container build and runtime
- kubectl 1.24+ - Kubernetes CLI
- gcloud CLI - Google Cloud SDK
- Python 3.11+ - For local development
- PostgreSQL 15+ - Database (Cloud SQL)
GCP Setup
- GCP Project with billing enabled
- GKE Cluster (standard or autopilot)
- Cloud SQL PostgreSQL instance
- Container Registry enabled
- Service accounts with appropriate permissions
Required GCP APIs
# Enable required APIs
gcloud services enable \
container.googleapis.com \
containerregistry.googleapis.com \
sqladmin.googleapis.com \
secretmanager.googleapis.com \
cloudresourcemanager.googleapis.com
Initial Setup
1. Clone Repository
git clone https://github.com/coditect-ai/coditect-cloud-backend.git
cd coditect-cloud-backend
2. Configure GCP Project
# Set your project ID
export GCP_PROJECT_ID="your-project-id"
export GCP_REGION="us-central1"
export GKE_CLUSTER="coditect-cluster"
# Login to GCP
gcloud auth login
# Set default project
gcloud config set project ${GCP_PROJECT_ID}
3. Create Cloud SQL Instance
# Create PostgreSQL instance
gcloud sql instances create coditect-db \
--database-version=POSTGRES_15 \
--tier=db-n1-standard-2 \
--region=${GCP_REGION} \
--storage-type=SSD \
--storage-size=50GB \
--storage-auto-increase \
--backup \
--backup-start-time=03:00 \
--maintenance-window-day=SUN \
--maintenance-window-hour=04 \
--database-flags=max_connections=200
# Create database
gcloud sql databases create coditect_cloud \
--instance=coditect-db
# Create database user
gcloud sql users create django \
--instance=coditect-db \
--password=$(openssl rand -base64 32)
4. Create GKE Cluster (if needed)
# Create GKE cluster
gcloud container clusters create ${GKE_CLUSTER} \
--region=${GCP_REGION} \
--num-nodes=3 \
--machine-type=e2-standard-4 \
--enable-autoscaling \
--min-nodes=3 \
--max-nodes=10 \
--enable-autorepair \
--enable-autoupgrade \
--enable-ip-alias \
--workload-pool=${GCP_PROJECT_ID}.svc.id.goog
# Get credentials
gcloud container clusters get-credentials ${GKE_CLUSTER} \
--region=${GCP_REGION}
5. Configure Workload Identity
# Create GCP service account
gcloud iam service-accounts create django-backend \
--display-name="Django Backend Service Account"
# Grant Cloud SQL Client role
gcloud projects add-iam-policy-binding ${GCP_PROJECT_ID} \
--member="serviceAccount:django-backend@${GCP_PROJECT_ID}.iam.gserviceaccount.com" \
--role="roles/cloudsql.client"
# Bind Kubernetes SA to GCP SA
kubectl create namespace coditect-backend
kubectl create serviceaccount django-backend-sa -n coditect-backend
gcloud iam service-accounts add-iam-policy-binding \
django-backend@${GCP_PROJECT_ID}.iam.gserviceaccount.com \
--role roles/iam.workloadIdentityUser \
--member "serviceAccount:${GCP_PROJECT_ID}.svc.id.goog[coditect-backend/django-backend-sa]"
kubectl annotate serviceaccount django-backend-sa \
-n coditect-backend \
iam.gke.io/gcp-service-account=django-backend@${GCP_PROJECT_ID}.iam.gserviceaccount.com
Configuration
1. Generate Secrets
# Generate Django secret key
python -c "import secrets; print(secrets.token_urlsafe(50))"
# Generate JWT secret key
python -c "import secrets; print(secrets.token_urlsafe(50))"
2. Create Kubernetes Secrets
# Create namespace
kubectl apply -f k8s/namespace.yaml
# Create Django secrets
kubectl create secret generic django-secrets \
--from-literal=DJANGO_SECRET_KEY='<your-generated-secret-key>' \
--from-literal=DB_USER='django' \
--from-literal=DB_PASSWORD='<your-db-password>' \
--from-literal=JWT_SECRET_KEY='<your-jwt-secret-key>' \
--from-literal=EMAIL_HOST_USER='<your-email>' \
--from-literal=EMAIL_HOST_PASSWORD='<your-email-password>' \
-n coditect-backend
3. Update Kubernetes Manifests
Edit k8s/deployment.yaml and replace placeholders:
PROJECT_ID→ Your GCP project IDREGION→ Your GCP regionINSTANCE_NAME→ Your Cloud SQL instance name
Edit k8s/configmap.yaml if needed for your environment.
Deployment Methods
Method 1: Automated Deployment (Recommended)
# Set environment variables
export GCP_PROJECT_ID="your-project-id"
export GCP_REGION="us-central1"
export GKE_CLUSTER="coditect-cluster"
# Run deployment script
./deploy.sh
This will:
- Build Docker image
- Push to Google Container Registry
- Apply Kubernetes manifests
- Update deployment with new image
- Run database migrations
- Verify deployment
- Perform health checks
Method 2: Manual Deployment
Step 1: Build and Push Docker Image
# Build image
docker build -t gcr.io/${GCP_PROJECT_ID}/coditect-django-backend:v1 .
# Configure Docker for GCR
gcloud auth configure-docker
# Push to GCR
docker push gcr.io/${GCP_PROJECT_ID}/coditect-django-backend:v1
Step 2: Apply Kubernetes Manifests
# Apply all manifests
kubectl apply -f k8s/namespace.yaml
kubectl apply -f k8s/configmap.yaml
kubectl apply -f k8s/deployment.yaml
kubectl apply -f k8s/service.yaml
kubectl apply -f k8s/ingress.yaml
kubectl apply -f k8s/hpa.yaml
Step 3: Wait for Deployment
# Watch deployment rollout
kubectl rollout status deployment/django-backend -n coditect-backend
# Check pod status
kubectl get pods -n coditect-backend
Step 4: Run Database Migrations
# Get pod name
POD=$(kubectl get pods -n coditect-backend -l app=django-backend -o jsonpath='{.items[0].metadata.name}')
# Run migrations
kubectl exec -it ${POD} -n coditect-backend -- python manage.py migrate
# Create superuser (optional)
kubectl exec -it ${POD} -n coditect-backend -- python manage.py createsuperuser
Post-Deployment
1. Verify Health Checks
# Liveness endpoint
curl https://api.coditect.com/api/v1/health/
# Readiness endpoint
curl https://api.coditect.com/api/v1/health/ready/
# Expected response
{"status": "healthy", "timestamp": "2025-11-24T..."}
2. Check Service Status
# Pod status
kubectl get pods -n coditect-backend
# Service status
kubectl get service django-backend-service -n coditect-backend
# Ingress status
kubectl get ingress django-backend-ingress -n coditect-backend
# HPA status
kubectl get hpa django-backend-hpa -n coditect-backend
3. View Logs
# Stream logs from deployment
kubectl logs -f deployment/django-backend -n coditect-backend
# Logs from specific pod
kubectl logs -f ${POD} -n coditect-backend
# Logs from Cloud SQL Proxy sidecar
kubectl logs -f ${POD} -n coditect-backend -c cloud-sql-proxy
4. Access Django Shell
# Get interactive shell
kubectl exec -it ${POD} -n coditect-backend -- python manage.py shell
# Or bash shell
kubectl exec -it ${POD} -n coditect-backend -- /bin/bash
5. Configure DNS
Point your domain to the Ingress load balancer:
# Get Ingress IP
kubectl get ingress django-backend-ingress -n coditect-backend
# Create DNS A record
# api.coditect.com → <INGRESS_IP>
6. TLS Certificate (Automatic with cert-manager)
The ingress is configured for automatic TLS certificate provisioning via cert-manager. Ensure cert-manager is installed:
# Install cert-manager (if not already installed)
kubectl apply -f https://github.com/cert-manager/cert-manager/releases/download/v1.13.0/cert-manager.yaml
# Create ClusterIssuer for Let's Encrypt
cat <<EOF | kubectl apply -f -
apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata:
name: letsencrypt-prod
spec:
acme:
server: https://acme-v02.api.letsencrypt.org/directory
email: admin@coditect.com
privateKeySecretRef:
name: letsencrypt-prod
solvers:
- http01:
ingress:
class: nginx
EOF
Monitoring
1. Kubernetes Dashboard
# Install Kubernetes dashboard
kubectl apply -f https://raw.githubusercontent.com/kubernetes/dashboard/v2.7.0/aio/deploy/recommended.yaml
# Create admin user and get token
kubectl create serviceaccount admin-user -n kubernetes-dashboard
kubectl create clusterrolebinding admin-user-binding \
--clusterrole=cluster-admin \
--serviceaccount=kubernetes-dashboard:admin-user
# Get token
kubectl -n kubernetes-dashboard create token admin-user
# Access dashboard
kubectl proxy
2. Resource Metrics
# Pod resource usage
kubectl top pods -n coditect-backend
# Node resource usage
kubectl top nodes
# HPA status
kubectl get hpa django-backend-hpa -n coditect-backend --watch
3. Application Metrics
Django backend exposes Prometheus metrics at /api/v1/metrics (if configured).
Troubleshooting
Common Issues
1. Pods Not Starting
# Check pod events
kubectl describe pod ${POD} -n coditect-backend
# Check logs
kubectl logs ${POD} -n coditect-backend
# Common causes:
# - Image pull errors (check GCR permissions)
# - Secret not found (verify secrets exist)
# - Resource limits too low
2. Database Connection Failed
# Check Cloud SQL Proxy logs
kubectl logs ${POD} -n coditect-backend -c cloud-sql-proxy
# Verify Cloud SQL instance name in deployment.yaml
# Format: PROJECT_ID:REGION:INSTANCE_NAME
# Check service account permissions
gcloud projects get-iam-policy ${GCP_PROJECT_ID} \
--flatten="bindings[].members" \
--filter="bindings.members:serviceAccount:django-backend@*"
3. Health Check Failures
# Check health endpoint directly from pod
kubectl exec -it ${POD} -n coditect-backend -- curl http://localhost:8000/api/v1/health/
# If health endpoint works but probe fails:
# - Check initialDelaySeconds in deployment.yaml
# - Increase timeoutSeconds
# - Verify allowed hosts in Django settings
4. 502 Bad Gateway from Ingress
# Check service endpoints
kubectl get endpoints django-backend-service -n coditect-backend
# Check ingress controller logs
kubectl logs -n ingress-nginx -l app.kubernetes.io/name=ingress-nginx
# Verify service selector matches pod labels
kubectl get pods -n coditect-backend --show-labels
5. Static Files Not Loading
# Verify static files collected
kubectl exec -it ${POD} -n coditect-backend -- ls -la /app/staticfiles/
# Re-collect static files
kubectl exec -it ${POD} -n coditect-backend -- \
python manage.py collectstatic --noinput --clear
Debug Commands
# Get comprehensive pod information
kubectl describe pod ${POD} -n coditect-backend
# Check events in namespace
kubectl get events -n coditect-backend --sort-by='.lastTimestamp'
# Port forward to pod for direct access
kubectl port-forward ${POD} 8000:8000 -n coditect-backend
# Access via localhost
curl http://localhost:8000/api/v1/health/
# Check deployment history
kubectl rollout history deployment/django-backend -n coditect-backend
# Check resource quotas
kubectl describe resourcequota -n coditect-backend
Rollback
Automatic Rollback
# Rollback to previous revision
kubectl rollout undo deployment/django-backend -n coditect-backend
# Rollback to specific revision
kubectl rollout undo deployment/django-backend \
-n coditect-backend \
--to-revision=3
Manual Rollback
# View rollout history
kubectl rollout history deployment/django-backend -n coditect-backend
# Check specific revision
kubectl rollout history deployment/django-backend \
-n coditect-backend \
--revision=2
# Update to specific image version
kubectl set image deployment/django-backend \
django=gcr.io/${GCP_PROJECT_ID}/coditect-django-backend:v1 \
-n coditect-backend
Scaling
Manual Scaling
# Scale to specific replica count
kubectl scale deployment django-backend \
--replicas=5 \
-n coditect-backend
Auto-scaling (HPA)
HPA is configured to auto-scale between 3-10 replicas based on:
- CPU utilization target: 70%
- Memory utilization target: 80%
# View HPA status
kubectl get hpa django-backend-hpa -n coditect-backend
# Describe HPA for detailed metrics
kubectl describe hpa django-backend-hpa -n coditect-backend
Security Best Practices
- Never commit secrets to git (use GCP Secret Manager or Kubernetes secrets)
- Use Workload Identity for GCP service access (configured in deployment)
- Run as non-root user (configured in Dockerfile)
- Enable Pod Security Standards (consider PodSecurityPolicy or admission controllers)
- Regular security updates (keep base images and dependencies updated)
- Network policies (restrict pod-to-pod communication if needed)
- TLS everywhere (configured in ingress)
- Resource limits (configured in deployment)
Production Checklist
Before going to production, verify:
- Cloud SQL instance has automated backups enabled
- Secrets are stored in GCP Secret Manager (not directly in manifests)
- TLS certificates are configured and valid
- DNS records point to correct ingress IP
- HPA is configured with appropriate limits
- Resource requests/limits are tuned for your workload
- Logging is configured and accessible
- Monitoring dashboards are set up
- Alerting is configured for critical metrics
- Backup and disaster recovery plan is documented
- Database migrations are tested
- Load testing completed
- Security scan completed (container and code)
Support
For issues or questions:
- Documentation: See README.md and api-quick-reference.md
- Repository: https://github.com/coditect-ai/coditect-cloud-backend
- Owner: AZ1.AI INC
Last Updated: November 24, 2025 Version: 1.0.0 Status: Production Ready