Running Django on the Google Kubernetes Engine Stay organized with collections Save and categorize content based on your preferences.
Django apps that run onGKE scale dynamically according to traffic.
This tutorial assumes that you're familiar with Django web development. Ifyou're new to Django development, it's a good idea to work throughwriting your first Django app before continuing.
While this tutorial demonstrates Django specifically, you can use this deployment processwith other Django-based frameworks, such asWagtail andDjango CMS.
This tutorial uses Django 5,which requires at least Python 3.10.You also need to haveDocker installed.
Objectives
In this tutorial, you will:
- Create and connect a Cloud SQL database.
- Create and use Kubernetes secret values.
- Deploy a Django app to Google Kubernetes Engine.
Costs
In this document, you use the following billable components of Google Cloud:
To generate a cost estimate based on your projected usage, use thepricing calculator.
Before you begin
- Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Note: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
- Create a project: To create a project, you need the Project Creator role (
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission.Learn how to grant roles.
Verify that billing is enabled for your Google Cloud project.
Enable the Cloud SQL, GKE and Compute Engine APIs.
Roles required to enable APIs
To enable APIs, you need the Service Usage Admin IAM role (
roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enablepermission.Learn how to grant roles.Install thegcloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Toinitialize the gcloud CLI, run the following command:
Note: You can run the gcloud CLI in the Google Cloud console without installing thegcloud CLI. To run the gcloud CLI in the Google Cloud console,use Cloud Shell.gcloudinit
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Note: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
- Create a project: To create a project, you need the Project Creator role (
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission.Learn how to grant roles.
Verify that billing is enabled for your Google Cloud project.
Enable the Cloud SQL, GKE and Compute Engine APIs.
Roles required to enable APIs
To enable APIs, you need the Service Usage Admin IAM role (
roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enablepermission.Learn how to grant roles.Install thegcloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Toinitialize the gcloud CLI, run the following command:
Note: You can run the gcloud CLI in the Google Cloud console without installing thegcloud CLI. To run the gcloud CLI in the Google Cloud console,use Cloud Shell.gcloudinit
Prepare your environment
Clone a sample app
The code for the Django sample app is in theGoogleCloudPlatform/python-docs-samples repository on GitHub.
You can eitherdownload the sample as a ZIP file and extract it or clone the repository to your local machine:
gitclonehttps://github.com/GoogleCloudPlatform/python-docs-samples.gitGo to the directory that contains the sample code:
Linux/macOS
cdpython-docs-samples/kubernetes_engine/django_tutorialWindows
cdpython-docs-samples\kubernetes_engine\django_tutorial
Confirm your Python setup
This tutorial relies on Python to run the sample application on your machine. The sample code also requires installing dependencies
For more details, refer to thePython development environment guide.
Confirm your Python is at least version 3.10.
python-VYou should see
Note: If you see a version number starting with "2", you may need to runPython 3.10.0or higher.python3instead ofpython. If so, remember to reference your chosen Python installation when runningpythoncommands.Create a Python virtual environment and install dependencies:
Linux/macOS
python-mvenvvenvsourcevenv/bin/activatepipinstall--upgradepippipinstall-rrequirements.txtWindows
python-mvenvvenvvenv\scripts\activatepipinstall--upgradepippipinstall-rrequirements.txt
Download Cloud SQL Auth Proxy to connect to Cloud SQL from your local machine
Note: If you are completing this tutorial from Cloud Shell, this section is not required.When deployed, your app uses the Cloud SQL Auth Proxy that is built intothe Google Kubernetes Engine environment to communicate with your Cloud SQLinstance. However, to test your app locally, you must install and use a localcopy of the proxy in your development environment. For more details, refer to theCloud SQL Auth Proxy guide.
The Cloud SQL Auth Proxy uses the Cloud SQL API to interact with your SQL instance. To do this, it requires application authentication through thegcloud CLI.
Authenticate and acquire credentials for the API:
gcloudauthapplication-defaultloginDownload and install the Cloud SQL Auth Proxy to your local machine.
Linux 64-bit
- Download the Cloud SQL Auth Proxy:
curl-ocloud-sql-proxyhttps://storage.googleapis.com/cloud-sql-connectors/cloud-sql-proxy/v2.21.0/cloud-sql-proxy.linux.amd64
- Make the Cloud SQL Auth Proxy executable:
chmod+xcloud-sql-proxy
Linux 32-bit
- Download the Cloud SQL Auth Proxy:
curl-ocloud-sql-proxyhttps://storage.googleapis.com/cloud-sql-connectors/cloud-sql-proxy/v2.21.0/cloud-sql-proxy.linux.386
- If the
curlcommand is not found, runsudo apt install curland repeat the download command. - Make the Cloud SQL Auth Proxy executable:
chmod+xcloud-sql-proxy
macOS 64-bit
- Download the Cloud SQL Auth Proxy:
curl-ocloud-sql-proxyhttps://storage.googleapis.com/cloud-sql-connectors/cloud-sql-proxy/v2.21.0/cloud-sql-proxy.darwin.amd64
- Make the Cloud SQL Auth Proxy executable:
chmod+xcloud-sql-proxy
Mac M1
- Download the Cloud SQL Auth Proxy:
curl-ocloud-sql-proxyhttps://storage.googleapis.com/cloud-sql-connectors/cloud-sql-proxy/v2.21.0/cloud-sql-proxy.darwin.arm64
- Make the Cloud SQL Auth Proxy executable:
chmod+xcloud-sql-proxy
Windows 64-bit
Right-clickhttps://storage.googleapis.com/cloud-sql-connectors/cloud-sql-proxy/v2.21.0/cloud-sql-proxy.x64.exe and selectSave Link As to download the Cloud SQL Auth Proxy. Rename the file tocloud-sql-proxy.exe.Windows 32-bit
Right-clickhttps://storage.googleapis.com/cloud-sql-connectors/cloud-sql-proxy/v2.21.0/cloud-sql-proxy.x86.exe and selectSave Link As to download the Cloud SQL Auth Proxy. Rename the file tocloud-sql-proxy.exe.Cloud SQL Auth Proxy Docker image
The Cloud SQL Auth Proxy has different container images, such as
distroless,alpine,andbuster. The default Cloud SQL Auth Proxy container image usesdistroless, whichcontains no shell. If you need a shell or related tools, then download an image based onalpineorbuster.For more information, seeCloud SQL Auth Proxy Container Images.You can pull the latest image to your local machine using Docker by using the following command:
docker pull gcr.io/cloud-sql-connectors/cloud-sql-proxy:2.21.0
Note: The Cloud SQL Auth Proxy uses a repository that supports the
gcr.iodomain but serves images from Artifact Registry. For more information, seeTransition from Container Registry.Other OS
For other operating systems not included here, you cancompile the Cloud SQL Auth Proxy from source.You can choose to move the download to somewhere common, such as a location on your
PATH, or your home directory. If you choose to do this, when you start the Cloud SQL Auth Proxy later on in the tutorial, remember to reference your chosen location when usingcloud-sql-proxycommands.- Download the Cloud SQL Auth Proxy:
Create backing services
This tutorial uses several Google Cloud services to provide thedatabase, media storage, and secret storage that support the deployed Djangoproject. These services are deployed in a specific region. For efficiency betweenservices, all services should be deployed in the same region.For more information about the closest region to you, seeProducts available by region.
Set up a Cloud SQL for PostgreSQL instance
Django officially supports multiple relational databases, but offers the mostsupport for PostgreSQL. PostgreSQL is supported by Cloud SQL, so thistutorial chooses to use that type of database.
The following section describes the creation of a PostgreSQL instance, database, and database user for the app.
Create the PostgreSQL instance:
Console
In the Google Cloud console, go to theCloud SQL Instances page.
ClickCreate Instance.
ClickChoose PostgreSQL.
ForSQL Edition, choose "Enterprise".
ForEdition Preset, choose "Sandbox".
In theInstance ID field, enter
INSTANCE_NAME.Enter a password for the postgres user.
Keep the default values for the other fields.
ClickCreate Instance.
It takes a few minutes for the instance to be ready for use.
gcloud
Create the PostgreSQL instance:
gcloudsqlinstancescreateINSTANCE_NAME \--projectPROJECT_ID \--database-versionPOSTGRES_16 \--tierdb-n1-standard-2 \--regionREGION
Replace the following:
INSTANCE_NAME: the Cloud SQL instance namePROJECT_ID: the Google Cloud project IDREGION: theGoogle Cloud region
It takes a few minutes to create the instance and for it to be ready for use.
Within the created instance, create a database:
Console
- Within your instance page, go to theDatabases tab.
- ClickCreate database.
- In theDatabase Name dialog, enter
DATABASE_NAME. - ClickCreate.
gcloud
Create the database within the recently created instance:
gcloudsqldatabasescreateDATABASE_NAME \--instanceINSTANCE_NAMEReplace
DATABASE_NAMEwith a name for the database inside the instance.
Create a database user:
Note: Users created this way get additional database rights. SeeLimit the database user privileges for an alternative method.Console
- Within your instance page, go to theUsers tab.
- ClickAdd User Account.
- In theChoose how to authenticate dialog under "Built-in Authentication":
- Enter the username
DATABASE_USERNAME. - Enter the password
DATABASE_PASSWORD - ClickAdd.
gcloud
Create the user within the recently created instance:
gcloudsqluserscreateDATABASE_USERNAME \--instanceINSTANCE_NAME \--passwordDATABASE_PASSWORDReplace
PASSWORDwith a secure password.
Create a service account
The proxy requires a service account with Editor privileges for yourCloud SQL instance. For more information about service accounts, seetheGoogle Cloud authentication overview.
If you are connecting from Compute Engine, make sureyour VM has the properscope to connect using the Cloud SQL Admin API.Configure the service account to have either of the following access scopes:
- https://www.googleapis.com/auth/sqlservice.admin
- https://www.googleapis.com/auth/cloud-platform
- In the Google Cloud console, go to theService accounts page.
- Select the project that contains your Cloud SQL instance.
- ClickCreate service account.
- In theService account name field, enter a descriptive name for the service account.
- Change theService account ID to a unique, recognizable value and then clickCreate and continue.
- Click theSelect a role field and select one of the following roles:
- Cloud SQL > Cloud SQL Client
- Cloud SQL > Cloud SQL Editor
- Cloud SQL > Cloud SQL Admin
- ClickDone to finish creating the service account.
- Click the action menu for your new service account and then selectManage keys.
- Click theAdd key drop-down menu and then clickCreate new key.
- Confirm that the key type is JSON and then clickCreate.
The private key file is downloaded to your machine. You can move it to another location. Keep the key file secure.
Configure the database settings
Use the following commands to set environment variables for database access.These environment variables are used for local testing.
Linux/MacOS
exportDATABASE_NAME=DATABASE_NAMEexportDATABASE_USER=DATABASE_USERNAMEexportDATABASE_PASSWORD=DATABASE_PASSWORDWindows
setDATABASE_USER=DATABASE_USERNAMEsetDATABASE_PASSWORD=DATABASE_PASSWORDSet up your GKE configuration
This application is represented in a single Kubernetes configuration called
polls. Inpolls.yamlreplace<your-project-id>with yourGoogle Cloud project ID (PROJECT_ID).Run the following command and note the value of
connectionName:gcloudsqlinstancesdescribeINSTANCE_NAME--format"value(connectionName)"In the
polls.yamlfile, replace<your-cloudsql-connection-string>withtheconnectionNamevalue.
Run the app on your local computer
With the backing services configured, you can now run the app on your computer. This setup allows for local development, creating a superuser, and applying database migrations.
In a separate terminal, start the Cloud SQL Auth Proxy:
Linux/macOS
./cloud-sql-proxyPROJECT_ID:REGION:INSTANCE_NAMEWindows
cloud-sql-proxy.exePROJECT_ID:REGION:INSTANCE_NAMEThis step establishes a connection from your local computer to yourCloud SQL instance for local testing purposes. Keep theCloud SQL Auth Proxy running the entire time you test your app locally. Runningthis process in a separate terminal allows you to keep working whilethis process runs.
In the original terminal, set the Project ID locally:
Linux/macOS
exportGOOGLE_CLOUD_PROJECT=PROJECT_IDWindows
setGOOGLE_CLOUD_PROJECT=PROJECT_IDRun the Django migrations to set up your models and assets:
pythonmanage.pymakemigrationspythonmanage.pymakemigrationspollspythonmanage.pymigratepythonmanage.pycollectstaticStart the Django web server:
pythonmanage.pyrunserver8080In your browser, go tohttp://localhost:8080.
If you are in Cloud Shell, click theWeb Preview button, and selectPreview on port 8080.
The page displays the following text: "Hello, world. You'reat the polls index." The Django web server running on your computer deliversthe sample app pages.
Press
Ctrl/Cmd+Cto stop the local web server.
Use the Django admin console
In order to log into Django's admin console, you need to create asuperuser. Since you have a locally accessible connection to the database, you can run management commands:
Create a superuser. You will be prompted to enter a username, email, and password.
pythonmanage.pycreatesuperuserStart a local web server:
pythonmanage.pyrunserverIn your browser, go tohttp://localhost:8000/admin.
Log in to the admin site using the username and password you used whenyou ran
createsuperuser.
Deploy the app to GKE
When the app is deployed to Google Cloud, it uses the Gunicornserver. Gunicorn doesn't serve static content, so the app uses Cloud Storageto serve static content.
Collect and upload static resources
Create a Cloud Storage bucket and make it publicly readable.
gcloudstoragebucketscreategs://PROJECT_ID_MEDIA_BUCKETgcloudstoragebucketsadd-iam-policy-bindinggs://PROJECT_ID_MEDIA_BUCKET--member=allUsersrole=roles/storage.legacyObjectReaderGather all the static content locally into one folder:
pythonmanage.pycollectstaticUpload the static content to Cloud Storage:
gcloudstoragersync./staticgs://PROJECT_ID_MEDIA_BUCKET/static--recursiveIn
mysite/settings.py, set the value ofSTATIC_URLto the following URL,replacing[YOUR_GCS_BUCKET]with your bucket name:http://storage.googleapis.com/PROJECT_ID_MEDIA_BUCKET/static/
Set up GKE
To initialize GKE, go to theClusters page.
When you use GKE for the first time in a project, youneed to wait for the "Kubernetes Engine is getting ready. This may take aminute or more" message to disappear.
gcloudcontainerclusterscreatepolls \--scopes"https://www.googleapis.com/auth/userinfo.email","cloud-platform" \--num-nodes4--zone"us-central1-a"If an error message similar to
Project is not fully initialized with the default service accountsappears, you might need toinitialize Google Kubernetes Engine.Initialize GKE
If you received an error, go to the Google Cloud console to initializeGKE in your project.
Wait for the "Kubernetes Engine is getting ready. This can take a minute ormore" message to disappear.
After the cluster is created, use the
kubectlcommand-line tool, whichis integrated with thegcloud CLI, to interact with yourGKE cluster. Becausegcloudandkubectlare separatetools, make surekubectlis configured to interact with the right cluster.gcloudcontainerclustersget-credentialspolls--zone"us-central1-a"
Set up Cloud SQL
You need severalsecrets to enable your GKE app to connect with yourCloud SQL instance. One is required for instance-level access(connection), while the other two are required for database access. For moreinformation about the two levels of access control, seeInstance access control.
To create the secret for instance-level access, provide the location,
PATH_TO_CREDENTIAL_FILE, of the JSON service accountkey that you downloaded when you created your service account (seeCreating a service account):kubectlcreatesecretgenericcloudsql-oauth-credentials \--from-file=credentials.json=PATH_TO_CREDENTIAL_FILETo create the secrets for database access, use the SQL database,username, and password defined when you created backing services.SeeSet up a Cloud SQL for PostgreSQL instance:
kubectlcreatesecretgenericcloudsql \--from-literal=database=DATABASE_NAME \--from-literal=username=DATABASE_USERNAME \--from-literal=password=DATABASE_PASSWORD
Retrieve the public Docker image for the Cloud SQL proxy.
dockerpullb.gcr.io/cloudsql-docker/gce-proxyBuild a Docker image, replacing
<your-project-id>with your project ID.dockerbuild-tgcr.io/PROJECT_ID/polls.Configure Docker to use
gcloudas a credential helper, so that you canpush the image toContainer Registry:gcloudauthconfigure-dockerPush the Docker image. Replace
<your-project-id>with your project ID. Note: This command requires write access to Cloud Storage. If yourun this tutorial on a Compute Engine instance, youraccess to Cloud Storage might be read-only. To get write access,create a service account anduse the service account to authenticate on your instance.dockerpushgcr.io/PROJECT_ID/pollsCreate the GKE resource:
Note: If you used different names(other thancloudsql-oauth-credentialsandcloudsql) when creating the secrets in the previous commands, then youneed to update thekubectlcreate-fpolls.yamlpolls.yamlfile to match those new names.
Deploy the app to GKE
After the resources are created, there are threepolls pods on the cluster.Check the status of your pods:
kubectlgetpodsWait a few minutes for the pod statuses to display asRunning. If the podsaren't ready or if you see restarts, you can get the logs for a particular podto figure out the issue.[YOUR-POD-ID] is a part of the output returned by thepreviouskubectl get pods command.
kubectllogs[YOUR_POD_ID]See the app run in Google Cloud
After the pods are ready, you can get the external IP address of the loadbalancer:
kubectlgetservicespollsNote theEXTERNAL-IP address, and go tohttp://[EXTERNAL-IP] in your browser to see the Django pollslanding page and access the administrator console.
Understand the code
Sample application
The Django sample app was created using standard Django tooling. The following commands create the project and the polls app:
django-adminstartprojectmysitepythonmanage.pystartapppollsThe base views, models, and route configurations were copied fromWriting your first Django app (Part 1 andPart 2).
Database configuration
Thesettings.py contains the configuration for your SQL database:
DATABASES={"default":{# If you are using Cloud SQL for MySQL rather than PostgreSQL, set# 'ENGINE': 'django.db.backends.mysql' instead of the following."ENGINE":"django.db.backends.postgresql","NAME":os.getenv("DATABASE_NAME"),"USER":os.getenv("DATABASE_USER"),"PASSWORD":os.getenv("DATABASE_PASSWORD"),"HOST":"127.0.0.1","PORT":"5432",}}Kubernetes pod configurations
Thepolls.yaml file specifies two Kubernetes resources. The first is theService,which defines a consistent name and internal IP address for the Django web app.The second is anHTTP load balancer with a public-facing external IP address.
# The polls service provides a load-balancing proxy over the polls app# pods. By specifying the type as a 'LoadBalancer', Kubernetes Engine will# create an external HTTP load balancer.# For more information about Services see:# https://kubernetes.io/docs/concepts/services-networking/service/# For more information about external HTTP load balancing see:# https://kubernetes.io/docs/tasks/access-application-cluster/create-external-load-balancer/apiVersion:v1kind:Servicemetadata:name:pollslabels:app:pollsspec:type:LoadBalancerports:-port:80targetPort:8080selector:app:pollsThe service provides a network name and IP address, andGKE pods run the app's code behind the service.Thepolls.yaml file specifies adeployment that provides declarative updates for GKE pods. The servicedirects traffic to the deployment by matching the service's selector to thedeployment's label. In this case, the selectorpolls is matched to the labelpolls.
apiVersion:apps/v1kind:Deploymentmetadata:name:pollslabels:app:pollsspec:replicas:3selector:matchLabels:app:pollstemplate:metadata:labels:app:pollsspec:containers:-name:polls-app# Replace with your project ID or use `make template`image:gcr.io/<your-project-id>/polls# This setting makes nodes pull the docker image every time before# starting the pod. This is useful when debugging, but should be turned# off in production.imagePullPolicy:Alwaysenv:-name:DATABASE_NAMEvalueFrom:secretKeyRef:name:cloudsqlkey:database-name:DATABASE_USERvalueFrom:secretKeyRef:name:cloudsqlkey:username-name:DATABASE_PASSWORDvalueFrom:secretKeyRef:name:cloudsqlkey:passwordports:-containerPort:8080-image:gcr.io/cloudsql-docker/gce-proxy:1.16name:cloudsql-proxycommand:["/cloud_sql_proxy","--dir=/cloudsql","-instances=<your-cloudsql-connection-string>=tcp:5432","-credential_file=/secrets/cloudsql/credentials.json"]volumeMounts:-name:cloudsql-oauth-credentialsmountPath:/secrets/cloudsqlreadOnly:true-name:ssl-certsmountPath:/etc/ssl/certs-name:cloudsqlmountPath:/cloudsqlvolumes:-name:cloudsql-oauth-credentialssecret:secretName:cloudsql-oauth-credentials-name:ssl-certshostPath:path:/etc/ssl/certs-name:cloudsqlemptyDir:{}Clean up
To avoid incurring charges to your Google Cloud account for the resources used in this tutorial, either delete the project that contains the resources, or keep the project and delete the individual resources.
Delete the project
Delete the individual resources
If you don't want to delete the project, delete the individual resources.
Delete the Google Kubernetes Engine cluster:
gcloudcontainerclustersdeletepollsDelete the Docker image that you pushed to Container Registry:
gcloudcontainerimagesdeletegcr.io/PROJECT_ID/pollsDelete the Cloud SQL instance:
gcloudsqlinstancesdeleteINSTANCE_NAME
What's next
- Learn how toconfigure PostgreSQL for production
- Learn more aboutDjango on Google Cloud
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2026-02-18 UTC.