Deploy Django on Google Compute Engine with Nginx, Gunicorn and Postgresql (Google Cloud SQL)

Published on May 18,2020 by Maulik

Google Cloud Platform is one of the favorite platforms to deploy web applications. In order to deploy Django Application, we need a Virtual Machine and a managed Virtual Database Machine – in our case we use Google Cloud SQL. It is advisable to have separately managed database machines provided by cloud providers. In the worst case, it helps to keep your data safe if your virtual machine fails for any reason.

Okay, now let’s get started.

Steps to deploy Django on Compute Engine using Nginx, Gunicorn, and PostgreSQL (Google Cloud SQL)

Create Google Compute Engine instance.

What is Google Compute Engine?

It is Google Cloud Platform Product. Google Compute Engine is a managed VM product you can customize various configurations like selecting Operating System Image, CPU, Firewall Rules, Hard disk capacity, memory capacity. Google Compute Engine supports to create a virtual machine with a custom Image as well.

What is the cost of Google Compute Engine?

Costing of the Google Compute Engine product depends on our CPU, Memory, and Hardisk allocation. Google Compute Engine product charges with “pay as you go” policy. If we create a machine with 1 CPU, 0.6 GB Memory, and 10 GB SSD harddisk for 730 hours a month, it will cost $3.88 ( for VM) and $1.7 ( 10 GB SSD ), the total is $5.58. This configuration is enough to run the Django CMS website application. This should make all Digital Marketing Agencies and Website Designing Agencies re-think their traditional server costs and quality of servers.

django-cms-compute-engine-cost

Steps to create Compute Engine Virtual Machine.

  1. Create Google Cloud Project from Google Cloud Console.
  2. Create a billing account and enable billing for the project.
  3. Create a Virtual Machine instance.
  4. Configure the machine to have 0.6 GB Ram and 1 shared CPU.
    • copmute-engine-configuration-django
  5. Configure the machine to have Ubuntu OS and Harddisk size and set allow HTTP and HTTPS traffic:
  6. We can see a VM created on the VM list page:
  • google compute engine vm console

Create Google Cloud SQL instance.

What is Google Cloud SQL?

Google Cloud Platform serves managed Database Instances. Google Cloud SQL is a product of Google Cloud Platform. It is a service to create relational databases like MySQL, PostgreSQL, and SQL servers.

Why shall we use Google Cloud SQL?

It is possible and simpler to have the database server installed on the same VM, still, the Django application can run. But you need to take extra care for setting up the backups of the database. So ideally when you are running an application for your real users, the data is of prime importance in that case. So managed database instance is a reliable and sensible option rather than managing database servers on your own.

What is the cost of Google Cloud SQL?

A single instance of PostgreSQL having 0.6 GB memory and 10 GB hard disk costs $9.37.django-google-cloud-sql-cost

Steps to create Google Cloud SQL instance.

  1. Create Google Cloud SQL instance from Google Cloud Console.
  2. Choose the Database Engine:
    • google-cloud-database-engine-options
  3. Configure the instance name and generate default user password, if you wish may configure zone as well:
    • google-cloud-sql-instance-basic-details
  4. Whitelist your VM IP which we just created so VM can establish the Google Cloud SQL instance connection
    • google-cloud-sql-white-list-vm-ip
  5. Select machine CPU and memory configurations
    • google-cloud-sql-cpu-memory-configurations

Install Nginx on Google Compute Engine

    1. Do ssh login by pressing on the ssh button as shown in the below screenshot.compute-engine-vm-list-console-1
    2. Run sudo apt-get install nginx to install Nginx Server.
    3. On successful installation, we can notice nginx.conf file at /etc/nginx/nginx.conf
    4. We need to upload our custom nginx.conf file
    5. With the below configurations, the Gunicorn server will get traffic from the Nginx server and all static and media files will be served via the Nginx server. That reduces the load on the python Gunicorn server.
    6. user www-data;
      worker_processes auto;
      pid /run/nginx.pid;
      include /etc/nginx/modules-enabled/*.conf;
      
      events {
          worker_connections 768;
          # multi_accept on;
      }
      
      http {
      
          include /etc/nginx/mime.types;
          default_type application/octet-stream;
          
          ##
          # Django server settings, This points to our Gunicorn server.
          ##
          upstream django_optimized {
              server localhost:8080;
          }
      
          server {
      
          listen 80;
              server_name <compute engine VM IP>
      
      
              # routing all request which includes url static to /static/ so this traffic can be served by nginx
              location /static/ {
                 alias /home/<user>/<project_directory>/static/;           
              }
      
              # routing all request which includes url meda to /media/ so this traffic can be served by nginx
              location /media/ {
                 alias /home/<user>/<project_directory>/media/;
              }
      
              location / {
                  # checks for static file, if not found proxy to Gunicorn Django app
                  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                  proxy_set_header Host $http_host;
                  proxy_redirect off;
      
                  # passing request to reverse proxy server
                  proxy_pass http://django_optimized;
      
              }
          }
      }

       

    7. upload this file to our Compute VM ( right side of our ssh screen open a menu on click of settings icon, you can find upload file option there) and replace a file at this location /etc/nginx/nginx.conf
    8. sudo mv /home/nginx.conf /etc/nginx/
    9. Run Nginx config test by executing the following command: sudo nginx -t , it should pass.
    10. To stop Nginx sudo nginx -s stop
    11. To start Nginx server again sudo nginx

Setup the Gunicorn server as a reverse proxy with Nginx

  1. I am assuming you already know git and will be able to pull source code from the repository to Compute Engine VM.
  2. Start the gunicorn server using the following command: gunicorn <django project directory>.wsgi -b 0.0.0.0:8080 --timeout 900 --log-level debug --log-file -
    • -b 0.0.0.0:8080 – it will start the server on port 8080
    • --timeout 900– It sets request time out time.
    • --log-level debug –  it sets log record level for server
    • --log-file –  it emits log on console
  3. We have already configured our Nginx server to pass all request to Gunicorn server except /static/ and /media/ URL.
  4. Restart Nginx server.

Use the Django application via our compute engine IP

  1. We can now check http://<compute engine VM IP>, you should be able to load the Django application.

Conclusion:

Django application running via Gunicorn server with Nginx as reverse proxy gives the best performance for your Django application. This process should take 30 minutes of your time. We can automate this process as well, I am going to write another article which demonstrates how we can automate this deployment process. But it is good to know this whole process before knowing any automation process.

0 Comments

copied to clipboard

Sign up for our newsletter

Please join our news letter which we share every month, you would love interesting python and django news letters.

We understand no one like spamming, your emails are safe with us.

Copyright © Django Circle All Rights Reserved.