On this edition of Serverless Expeditions, we take a look at how to deploy more complex applications on Google Cloud, using Django as an example.
Check out the video version of this blog post.
When moving legacy applications into serverless infrastructure, there is going to be some sort of state involved: there will be a database, media, and other components. Traditionally these can all be run within the confines of a virtual machine, where all the services can talk to each other in that environment. But when moving to serverless, all these components need to be specifically provisioned and connected together.
In today's episode, we'll discuss containerizing and deploying a typical Django application using Cloud Run and other Google Cloud services. The steps described can be applied to any website whose CMS uses the Django web framework, such as Wagtail or Django CMS.
Django supports both PostgreSQL and MySQL, both of which are available in Cloud SQL, a managed database service. When connecting to a Cloud Run service, specifying
--add-cloudsql-instances allows the service and the database to communicate over an automatically encrypted connection. The authentication from the application to the database is achieved by specifying a connection URL, stored securely in Secret Manager, loaded using the Python API. The database can then be populated by running
Static and media assets can be migrated to use Cloud Storage, with help from the
django-storages package. By creating a new storage bucket and specifying the name in the django settings.py, then running
./manage.py collectstatic, the images and assets are uploaded to the bucket.
However, those two manage.py commands --
collectstatic -- are typically run within an interactive terminal. Cloud Run has no such terminal, so these commands need to be run elsewhere. One method is to run these commands as part of the continuous integration process with Cloud Build. Adding a 'migrate' step using the app-engine-exec-wrapper between the typical build and deploy steps allows migration to happen as part of deployment.
With a managed database, highly-available static assets, automated deployment pipelines and robust containerisation solutions, you can migrate your Django applications to Google Cloud with confidence.
If you want to get started with these concepts, check out the Django Codelabs:
You can also find a sample implementation of these concepts at GoogleCloudPlatform/django-demo-app-unicodex.
Serverless Expeditions is a fun and cheeky video series that looks at what serverless means and how to build serverless apps with Google Cloud.