Skip to main content

Certification track: Professional Cloud Developer (PCD)

Django on Cloud Run

Django on Cloud Run

Django is a battle-tested Python web framework that encourages rapid development and clean, pragmatic design, powering some of the world's most demanding web applications. This module deploys Django on Cloud Run v2 on top of the App_CloudRun foundation, which provisions and manages the shared Google Cloud infrastructure.

This guide focuses on the cloud services Django uses and how to explore and operate them from the Google Cloud Console and the command line. For the mechanics that are common to every Cloud Run application — Workload Identity, ingress, autoscaling, CI/CD, Cloud Armor, IAP, Binary Authorization, VPC Service Controls, backups, and the deployment lifecycle — refer to the App_CloudRun foundation guide rather than repeating them here.


1. Overview

Django runs as a Python/Gunicorn container on Cloud Run v2. The deployment wires together a focused set of Google Cloud services:

CapabilityGoogle Cloud serviceNotes
ComputeCloud Run v2Python/Gunicorn container, 1 vCPU / 512 MiB by default; autoscaled to zero
DatabaseCloud SQL for PostgreSQL 15Required — Django's DB_ENGINE is fixed to django.db.backends.postgresql
Shared filesFilestore (NFS)Shared media across all container instances (requires gen2 execution environment)
Object storageCloud StorageA dedicated media bucket provisioned by Django_Common
SecretsSecret ManagerAuto-generated Django SECRET_KEY and database password
Cache (optional)Redis / Cloud MemorystoreDisabled by default; enable for session storage and caching
IngressCloud Load BalancingExternal HTTPS load balancer with optional custom domain + managed certificate

Sensible defaults worth knowing up front:

  • PostgreSQL 15 is fixed. Django_Common hard-wires DB_ENGINE to PostgreSQL; MySQL and NONE are not supported through this module.
  • The Django SECRET_KEY is auto-generated and stored in Secret Manager; it is injected at runtime and never set in plain text.
  • Four PostgreSQL extensions are installed automatically (pg_trgm, unaccent, hstore, citext) by the db-init job, so you do not need to configure them.
  • Two initialization jobs run by defaultdb-init (creates the database and user) and db-migrate (runs manage.py migrate and collectstatic). On Cloud Run these run as Cloud Run Jobs triggered on apply.
  • NFS is enabled by default. All container instances share the same Filestore volume for uploaded media files. NFS mounts require execution_environment = "gen2" (set automatically).
  • Redis is disabled by default. Enable with enable_redis = true and point at a Cloud Memorystore instance for production session storage and caching.
  • Scale to zero by default. min_instance_count defaults to 0; set to 1 for production to eliminate cold starts.

2. Google Cloud Services & How to Explore Them

All commands assume PROJECT, REGION, and SERVICE are set. The service name and other identifiers are reported in the deployment Outputs.

A. Cloud Run v2 — the Django service

Django runs as a Cloud Run service scaled automatically between min_instance_count and max_instance_count. Each instance runs a Cloud SQL Auth Proxy sidecar and, when NFS is enabled, mounts the Filestore share.

  • Console: Cloud Run → select the service to see revisions, traffic splits, logs, and metrics.
  • CLI:
    gcloud run services describe "$SERVICE" --region "$REGION" --project "$PROJECT"
    gcloud run services list --region "$REGION" --project "$PROJECT"
    # Stream live logs:
    gcloud logging read 'resource.type="cloud_run_revision" AND resource.labels.service_name="'"$SERVICE"'"' \
    --project "$PROJECT" --limit 50

See App_CloudRun for revision traffic splits, min/max instances, concurrency, and execution environment configuration.

B. Cloud SQL for PostgreSQL 15

Django stores all application data in a managed Cloud SQL for PostgreSQL 15 instance. Container instances reach it through the Cloud SQL Auth Proxy over a local Unix socket, so no public IP is exposed. On first deploy the db-init Cloud Run Job creates the application database and user, installs the required extensions, and grants privileges. The db-migrate job then runs manage.py migrate and manage.py collectstatic.

  • Console: SQL → select the instance for connections, backups, flags, and metrics.
  • CLI:
    gcloud sql instances list --project "$PROJECT"
    gcloud sql instances describe <instance-name> --project "$PROJECT"
    # Open an interactive shell to inspect schema/data:
    gcloud sql connect <instance-name> --user=<db-user> --project "$PROJECT"
    # List the initialization jobs:
    gcloud run jobs list --region "$REGION" --project "$PROJECT"

The instance name, database name, user, and the Secret Manager secret holding the password are all surfaced in the Outputs. For the connection model, automated backups, and password rotation, see App_CloudRun.

C. Filestore (NFS) and Cloud Storage

Uploaded media is written to a Filestore (NFS) share mounted into every container instance so all replicas see the same files. A dedicated Cloud Storage media bucket is also provisioned automatically by Django_Common; the workload service account is granted access. NFS mounts on Cloud Run require the gen2 execution environment, which this module sets by default.

  • Console: Filestore → Instances for the NFS share; Cloud Storage → Buckets for the media bucket.
  • CLI:
    gcloud filestore instances list --project "$PROJECT"
    gcloud storage buckets list --project "$PROJECT"
    gcloud storage ls gs://<media-bucket>/ # bucket name is in the Outputs

See App_CloudRun for NFS provisioning, GCS Fuse volumes, and CMEK options.

D. Redis cache

Redis is disabled by default. When enable_redis = true, Django receives REDIS_HOST and REDIS_PORT as environment variables. Configure settings.py to use these for CACHES and SESSION_ENGINE. The module does not provision a Redis instance — use a Cloud Memorystore instance and set redis_host to its private IP.

  • Console: Memorystore → Redis (if using a managed instance).
  • CLI:
    redis-cli -h <redis-host> ping        # from a host with network access
    # Confirm REDIS_HOST and REDIS_PORT are in the service environment:
    gcloud run services describe "$SERVICE" --region "$REGION" --project "$PROJECT" \
    --format="json" | jq '.spec.template.spec.containers[0].env[]|select(.name|startswith("REDIS"))'

E. Secret Manager

The Django SECRET_KEY and the database password are stored as Secret Manager secrets and injected into container instances at runtime; plaintext never appears in configuration. The superuser password (if you create one via DJANGO_SUPERUSER_PASSWORD) should also be stored here.

  • Console: Security → Secret Manager.
  • CLI:
    gcloud secrets list --project "$PROJECT"
    gcloud secrets versions access latest --secret=<secret-name> --project "$PROJECT"
    # The database password secret name is in the Outputs:
    gcloud secrets versions access latest --secret=<database_password_secret> --project "$PROJECT"

See App_CloudRun for the secret mounting model, volume mounts versus env-var references, and rotation.

F. Networking & ingress

By default the service is exposed directly at its run.app HTTPS URL (ingress_settings = "all"). Ingress can be restricted to internal or internal-and-cloud-load-balancing via ingress_settings, and VPC egress can be controlled via vpc_egress_setting. Hostnames for the load-balanced path are configured via application_domains.

  • Console: Network services → Load balancing; Cloud Run → service → Networking tab.
  • CLI:
    gcloud run services describe "$SERVICE" --region "$REGION" --project "$PROJECT" \
    --format="value(status.url)"
    gcloud compute addresses list --project "$PROJECT"

See App_CloudRun for custom domains, Cloud CDN, static IP, and VPC egress details.

G. Cloud Logging & Monitoring

Container stdout/stderr flow to Cloud Logging; Cloud Run and Cloud SQL metrics flow to Cloud Monitoring. Optional uptime checks and alert policies are available.

  • Console: Logging → Logs Explorer; Monitoring → Dashboards / Alerting.
  • CLI:
    gcloud logging read \
    'resource.type="cloud_run_revision" AND resource.labels.service_name="'"$SERVICE"'"' \
    --project "$PROJECT" --limit 50

3. Django Application Behaviour

  • First-deploy database setup. A db-init Cloud Run Job creates the PostgreSQL database and user, grants privileges, and installs the four required extensions (pg_trgm, unaccent, hstore, citext) using the ROOT_PASSWORD superuser secret. The job is idempotent and safe to re-run.
  • Migrations on first deploy. A db-migrate Cloud Run Job runs manage.py migrate and manage.py collectstatic --noinput --clear after db-init completes. Both jobs are triggered automatically on apply (execute_on_apply = true). Override initialization_jobs with a non-empty list to replace them with custom jobs.
  • SECRET_KEY management. A 50-character random key is generated by Django_Common and stored in Secret Manager. It is injected as SECRET_KEY. Do not set SECRET_KEY in environment_variables.
  • Superuser creation. If DJANGO_SUPERUSER_USERNAME, DJANGO_SUPERUSER_EMAIL, and DJANGO_SUPERUSER_PASSWORD are present as environment variables when the container starts, entrypoint.sh creates a Django superuser on first boot. Use secret_environment_variables for the password:
    # Retrieve the superuser password from Secret Manager:
    gcloud secrets versions access latest --secret=<superuser-secret> --project "$PROJECT"
  • Health probes. The startup probe targets GET /healthz on port 8080 with a 60-second initial delay. The liveness probe also targets GET /healthz with a 30-second initial delay. Implement a lightweight /healthz/ view that returns HTTP 200 with no redirects. Note that Cloud Run health probe traffic arrives over HTTP; avoid setting SECURE_SSL_REDIRECT = True in settings.py or the probe will receive a 301 redirect and the service will never become healthy.
  • Scheduled tasks. Django management commands (e.g., clearsessions) can be scheduled as Cloud Run Jobs via the cron_jobs variable:
    gcloud run jobs list --region "$REGION" --project "$PROJECT"
    gcloud run jobs execute <job-name> --region "$REGION" --project "$PROJECT"
  • gen2 execution environment. NFS mounts require Cloud Run gen2 containers. This is set automatically when enable_nfs = true. If you disable NFS you may override execution_environment to "gen1", but gen2 is strongly recommended.

4. Configuration Variables

Variables are grouped exactly as they appear on the deployment platform. Only settings specific to or notable for Django are listed; every other input is inherited from App_CloudRun with its standard behaviour and defaults.

Group 1 — Project & Identity

VariableDefaultDescription
project_id(required)Target Google Cloud project.
regionus-central1Region for the Cloud Run service and regional resources.

Group 2 — Deployment Environment

VariableDefaultDescription
tenant_deployment_iddemoShort suffix that makes resource names unique per environment.
support_users[]Emails granted project access and monitoring alerts.
resource_labels{}Labels applied to all resources for cost/ownership tracking.

Group 3 — Application Identity

VariableDefaultDescription
application_namedjangoBase name for resources. Do not change after first deploy.
application_display_nameDjango ApplicationFriendly name shown in the Console.
application_descriptionDjango Application - High-level Python Web frameworkService description annotation.
application_versionlatestImage version tag; increment to roll out a new revision. Pin to a specific tag in production.

Group 4 — Runtime & Scaling

VariableDefaultDescription
deploy_applicationtrueSet false to provision infrastructure only.
container_image_sourcecustomcustom builds via Cloud Build; prebuilt deploys an existing image URI.
container_imageus-docker.pkg.dev/cloudrun/container/helloOverride container image URI.
container_resources{ cpu_limit = "1000m", memory_limit = "512Mi" }CPU and memory limits per instance.
min_instance_count0Minimum warm instances. Set ≥ 1 to eliminate cold starts in production.
max_instance_count1Maximum concurrently active instances.
container_port8080Django/Gunicorn listens on port 8080.
enable_cloudsql_volumetrueCloud SQL Auth Proxy sidecar for socket connections.
execution_environmentgen2Required for NFS mounts. Do not change unless NFS is disabled.

Group 5 — Traffic Management & IAP

VariableDefaultDescription
ingress_settingsallCloud Run ingress: all, internal, or internal-and-cloud-load-balancing.
vpc_egress_settingPRIVATE_RANGES_ONLYEgress through the serverless VPC connector.
enable_iapfalseRequire Google sign-in in front of Django.
iap_authorized_users / iap_authorized_groups[]Who may access when IAP is enabled.

Group 6 — Environment Variables & Secrets

VariableDefaultDescription
environment_variables{}Extra non-secret settings. Do not include SECRET_KEY or DB_* here.
secret_environment_variables{}Map of env var → Secret Manager secret name (e.g., DJANGO_SUPERUSER_PASSWORD).
secret_propagation_delay30Seconds to wait after secret creation before proceeding.
secret_rotation_period2592000sSecret Manager rotation notification frequency.

Group 7 — Backup & Maintenance

VariableDefaultDescription
backup_schedule0 2 * * *Automated backup cron (UTC).
backup_retention_days7Retention; raise to 30–90 for production/compliance.
enable_backup_import / backup_source / backup_urirestore optionsRestore from a backup on deploy. Set enable_backup_import = false after a successful import.

Group 8 — CI/CD & GitHub Integration

Standard App_CloudRun Cloud Build / Cloud Deploy integration — see App_CloudRun. Key inputs: enable_cicd_trigger, github_repository_url, github_token, enable_cloud_deploy.

Group 9 — Custom SQL Scripts

enable_custom_sql_scripts, custom_sql_scripts_bucket, custom_sql_scripts_path, custom_sql_scripts_use_root — run SQL from a GCS bucket after provisioning. See App_CloudRun.

Group 10 — Cloud Armor & CDN

VariableDefaultDescription
enable_cloud_armorfalseAttach a Cloud Armor (WAF) policy to the backend.
admin_ip_ranges[]CIDRs allowed privileged access.
enable_cdnfalseEnable Cloud CDN on the load balancer.
application_domains[]Hostnames to serve (also used for custom domain).

Group 11 — Filesystem (NFS) & Cloud Storage

VariableDefaultDescription
enable_nfstrueShared Filestore volume for Django media (keep enabled for multi-instance).
nfs_mount_path/mnt/nfsMount path inside the container. Must match MEDIA_ROOT in settings.py.
create_cloud_storagetrueProvision the additional data bucket. The media bucket is always provisioned by Django_Common.
storage_buckets[{ name_suffix = "data" }]Additional buckets beyond the auto-provisioned media bucket.
gcs_volumes[]GCS Fuse mounts.

Group 12 — Database Backend

VariableDefaultDescription
database_typePOSTGRES_15PostgreSQL 15 required. Django does not support MySQL through this module.
application_database_namedjango_dbDatabase name. Immutable after first deploy.
application_database_userdjango_userApplication user. Immutable after first deploy.
database_password_length32Generated password length (16–64).
db_user_env_var_name / db_name_env_var_name""Override the env var name used to inject the DB user/name.
enable_auto_password_rotationfalseZero-downtime DB password rotation.

The four required extensions (pg_trgm, unaccent, hstore, citext) are installed automatically by the built-in db-init job — no variable is needed for them.

Group 13 — Jobs & Scheduled Tasks

VariableDefaultDescription
initialization_jobs(built-in db-init)By default, one db-init Cloud Run Job is defined. The db-migrate job is always added by Django_Common. Provide a non-empty list to replace the default db-init with custom jobs.
cron_jobs[]Scheduled Cloud Run Jobs (e.g., clearsessions, cleartokens).

Group 14 — Observability & Health

VariableDefaultDescription
startup_probeHTTP GET /healthz, 60s initial delayStartup probe passed to Django_Common. Increase delay for large migration sets. Do not use a redirect path.
liveness_probeHTTP GET /healthz, 30s initial delayLiveness probe. Use a lightweight endpoint that returns 200 with no body.
startup_probe_configenabled, HTTP /healthzApp_CloudRun-level infrastructure startup probe.
health_check_configenabled, HTTP /healthzApp_CloudRun-level infrastructure health check.
uptime_check_configdisabled (enabled = false, path /)Optional Cloud Monitoring uptime check.

Group 21 — Redis Cache

VariableDefaultDescription
enable_redisfalseEnable Redis for session storage and caching.
redis_host""Redis host IP or hostname.
redis_port6379Redis port.
redis_auth""Optional Redis auth password (sensitive).

Group 22 — VPC Service Controls & Audit Logging

VariableDefaultDescription
enable_vpc_scfalseEnforce a VPC-SC perimeter (requires organization_id).
vpc_cidr_ranges / vpc_sc_dry_run(set)Access level CIDRs / dry-run mode.
enable_audit_loggingfalseDetailed Cloud Audit Logs.

5. Outputs

These values are returned on a successful deployment and are the quickest way to locate and explore the running resources.

OutputDescription
service_nameCloud Run service name.
service_urlHTTPS URL to reach Django.
service_locationRegion the service is deployed in.
stage_servicesMap of Cloud Deploy stage service names and URLs.
load_balancer_ip / load_balancer_urlExternal IP and HTTPS URL (when a static IP is reserved).
database_instance_nameCloud SQL instance name.
database_nameApplication database name.
database_userApplication database user.
database_password_secretSecret Manager secret holding the DB password.
database_host / database_portDB endpoint (sensitive) / port.
storage_bucketsCreated Cloud Storage buckets.
network_name / network_exists / regionsVPC network, presence, available regions.
container_image / container_registryDeployed image and Artifact Registry repo.
monitoring_enabled / monitoring_notification_channelsMonitoring status and channels.
initialization_jobsNames of the setup Cloud Run Jobs.
deployment_id / tenant_id / resource_prefixNaming identifiers.
project_id / project_numberProject identifiers.
cicd_enabled / cicd_configurationCI/CD status and details (repo, trigger, registry).
github_repository_url / github_repository_owner / github_repository_nameCI/CD repo details.
artifact_registry_repository / cloudbuild_trigger_name / cloudbuild_trigger_idRegistry and build trigger.
uptime_check_namesNames of provisioned Cloud Monitoring uptime checks.
vpc_sc_enabled / vpc_sc_perimeter_name / vpc_sc_dry_run_modeVPC-SC status.
audit_logging_enabled / artifact_registry_cmek_enabledAudit logging and CMEK status.

6. Configuration Pitfalls & Sensible Defaults

Risk: Critical (data loss / outage / security) — High (service degraded) — Medium (cost or partial degradation) — Low (minor).

SettingSensible valueRiskConsequence if wrong
database_typePOSTGRES_15CriticalDjango requires PostgreSQL; MySQL or NONE will fail the db-init job.
application_name / tenant_deployment_idset onceCriticalEmbedded in resource names; changing recreates all named resources and destroys data.
application_database_name / _userset onceCriticalImmutable after first deploy; renaming recreates the DB/user and destroys data.
startup_probe path/healthz (no redirect)CriticalCloud Run probe traffic is plain HTTP; a redirect returns 301, Cloud Run never sees 200, service never starts.
SECURE_SSL_REDIRECT in settings.pyFalse or exempt /healthzCriticalTrue redirects every HTTP request including the startup probe; service stuck in STARTING.
enable_backup_importfalse after restoreHighLeaving true re-runs the import on every apply, overwriting live data with stale backup.
enable_nfstrue (default)HighDisabling with max_instance_count > 1 means each instance has isolated ephemeral storage; uploads are lost on instance teardown.
execution_environmentgen2 (default when NFS enabled)Highgen1 does not support NFS volume mounts; service fails to start.
nfs_mount_path/mnt/nfs — must match MEDIA_ROOTHighMismatch causes Django to write media to ephemeral storage; files lost on instance teardown.
container_resources memory512Mi; raise for ORM-heavy workloadsHighToo little memory: instance exits with OOM (exit 137) on large querysets or file processing.
min_instance_count1 for productionMedium0 causes cold starts (>60 s) on first request after idle; cron jobs may find no warm instance.
application_versionpinned tag, not latestMediumlatest makes rollback ambiguous; Cloud Run cannot tell two latest pulls apart.
enable_redistrue when using Redis-backed sessionsMediumLeft false with Redis-configured settings.py: ConnectionRefusedError on every cache/session access.
ingress_settingsinternal-and-cloud-load-balancing for load-balanced private servicesMediumall allows direct invocation of the Cloud Run endpoint URL bypassing Cloud Armor/IAP.
enable_iap / enable_cloud_armorenable for admin-facingMediumDjango admin UI is otherwise publicly reachable at the service URL.
backup_retention_days7 (raise for prod)MediumToo short for compliance retention.

For the foundation behaviour referenced throughout — IAM and Workload Identity, autoscaling, ingress and certificates, CI/CD, Cloud Armor, IAP, Binary Authorization, VPC-SC, backups, and image mirroring — see App_CloudRun. Django-specific application configuration shared with the GKE variant is described in Django_Common.