Deploying Django App on Google Compute Engine

Aryan Garg Last Updated : 08 Jun, 2022
8 min read

This article was published as a part of the Data Science Blogathon.

Introduction on Compute Engine

Compute Engine is computing and hosting service that lets you create and run virtual machines on Google infrastructure.

It provides an IaaS (Infrastructure-as-a-Service) that allows clients to run their applications on Google’s physical hardware instead of their own hardware and resources. Google Compute Engine delivers availability, fault tolerance, and consistency, which can be used to scale several virtual machines (VMs) to serve as large compute clusters.

In this article, we will create a GUI with custom styling for our previous Django Application. Then we will deploy it on the Google Cloud Platform, using its Compute Engine Service.

Prerequisites

If you already have your Django application, you can directly jump on to Section-2.

Otherwise, if you don’t have an app to deploy, you must read my article titled “Using Google Cloud Services in Django Web Application”.

In this article, we have created a Django Application that uses Google Vision AI Services to perform various tasks like Sentiment Analysis and English to French Text Translation.

Let’s get started, 😉

1. Creating GUI

This section will discuss creating a GUI for the Django App we made in our previous blog post.

As this is not an HTML and CSS Tutorial, I will provide you with the steps and code to create the GUI and connect that with your existing Django Application.

a) Creating HTML Templates.

Clone that repo. It contains the code of the previously created Django Application. We will make edits to this existing Django App.

Go inside /APIApp directory and create a new directory named templates. This folder will contain our HTML Templates.

Further, we need to register this template folder in our settings.py file.

Go to the settings.py file inside the GCPTutorial directory, and make the following changes.

 

Compute Engine

Now, your templates folder is ready to create HTML Templates inside it.

Create an HTML file named index.html inside the templates directory and paste that code into it.

We will use Bootstrap Library to create styling for our webpage.

b) Creating URL to render the HTML Page

Go to urls.py file in the /APIApp directory, and change the existing code to this.

from django.urls import path
from .views import sentimentAnalysis, englishToFrench, index
urlpatterns = [
path(‘sentimentAnalysis’, sentimentAnalysis, name=”sentimentAnalysis”),
path(‘englishToFrench’, englishToFrench, name=”englishToFrench”),
path(”, index, name=”index”),
]

Now we create a function to render that HTML Page in the views.py file.

Inside your views.py file, insert the following code:

1. Import the library to render the HTML page.

from django.shortcuts import render

2. Create a function to render it.

def index(request):
    return render(request, "index.html")

Congrats✌, our HTML Template is now ready to serve.

To check that everything is working fine, do the following steps:

1. Run your development server

$ python .manage.py runserver

2. Type that URL (http://localhost:8000/) inside your web browser.

If everything works fine, you will see this in your web browser.

You can test this application. The output looks like this.

Yeah😊, our Django App is now completed and ready to be deployed.

 

2. Creating a Virtual Machine

1. Log in to your Google Developer’s Console. You can also refer to that link, GCP.

Note: To use Google Compute Engine, you must have a billing account on Google Cloud. Google also provide some free credits in a trial version. You can refer to the Google Cloud website for more information about it.

2. Create a Project

You can use your existing project also if you have any. Or, you can create a new one.

3. Navigate to Compute Engine >> VM Instances.

Virtual Machine

4. Click on Create Instance button.

Virtual Machine

 

5. Name your VM and choose appropriate settings according to your budget and location.

Note: Settings chosen in the below image are sufficient to host our application

Virtual Machine3

6. You can also choose the disk size. But 10GB is sufficient for this project. Leave the other settings as it is.

Virtual Machine 4

7. You can choose your existing service account or use the default one. Also, allow both HTTP and HTTPS traffic to the website.

Finally, after checking all the parameters, click on the Create button.

 

Virtual Machine 5

8. Your created VM looks like this

Virtual Machine 7

Save your External IP Address. We can access the website in the public domain by using that IP address.

Our VM Instance is now ready to Host Websites✌.

3. Configuring Firewall Settings

We will use the default Django Port 8000, so we need to open that PORT in the Firewall Settings of Google Cloud Platform. But you can also open any PORT you want, but your application must run on the same PORT that you have opened.

1. Navigate to VPC Network >> Firewall.

Firewall Settings

2. Click on Create Firewall Rule button.

 

Create Firewall Rule

3. Enter the name of your Firewall Rule and leave other settings as it is as shown in the below image.

Create Firewall Rule

4. Select Targets as All instances in the network and Source IPv4 ranges as 0.0.0.0/0

Create Firewall Rule

5. Select TCP Protocol and open PORT 8000, then click on Create button.

Create Firewall Rule

6. Your firewall rule is now visible here.

Create Firewall Rule

Your Firewall Rule is now created successfully, and your VM is ready to receive requests on the PORT 8000.

4. Deploying Django Application

In this section, we will host the Django Application on our freshly created VM Instance.

1. Uploading the app to GitHub

You need to upload your Django App to GitHub. You can refer to this article to know to upload a project on GitHub.

Note: Be sure to add your Google API Secret Key in gitignore. We will directly add that JSON key later in the VM. Refer to the prerequisites blogs if you don’t have a Secret Key. This secret key is used to access Google Vision APIs.

You can create a public repo or a private repo as per your choice.

2. Open the Virtual Machine Terminal

Go to your VM Instance, and click on SSH Connect.

 

Virtual Machine Terminal

Now, this type of terminal is open.

Virtual Machine Terminal

As this is a Linux Machine, so we will use Linux commands.

3. Installing Necessary Libraries

Check for the existing python installation

$ python3 --version

You can install these libraries if they are not already installed.

$ sudo apt-get install python3

Installing pip by using that command

$ sudo apt-get install python3-pip python-dev

Installing virtual environment

$ pip install virtualenv

Installing Git

$ sudo apt-get update
$ sudo apt-get install git

Clone the GitHub Repo

Go to your GitHub repo, and copy the URL of your Repo.

Installing Necessary Libraries

Now, go to your GCP Terminal and type the following command:

$ git clone

You can clone my repository also

$ git clone https://github.com/aryan0141/GCPTutorial.git
$ cd GCPTutorial

Create a Virtual Environment

$ python3 -m virtualenv virtualenv_name

Activate your virtual environment

$ source virtualenv_name/bin/activate

Install all the required libraries for this application.

$ pip install -r requirements.txt

4. Creating a JSON File for the Google API Secret Key

Earlier, we put the Secret Key in gitignore, but now we need this key to access our APIs.

Create a JSON file in the main directory

$ vim Google_Vision_API_Key.json

Paste the content of your Secret Key in this JSON File.

Installing Necessary Libraries 2

To save this file, press ESC + colon + w + q, then press enter.

Apply migrations in the database

$ python manage.py makemigrations
$ python manage.py migrate

Start the Server

$ python manage.py runserver 0.0.0.0:8000

Now hit that URL on your web browser

URL – http://:8000/

You will see an error which looks like this

Start the server

5. Error of Allowed Hosts

This error is because Django does not allow any unknown HOST IP address.

So we need to add our HOST IP Address in ALLOWED_HOSTS of Django.

Open GCPTutorial/settings.py file

$ vim GCPTutorial/settings.py

When the vim editor opens, press the I button to edit it.

Now, enter your IP address in the ALLOWED_HOSTS list, as shown in this figure. It also sets DEGUB to False. It will not allow anyone to the error if any failure occurs.

Now, starts your server again and enter the URL in the web browser. If everything went fine, you will see the screen like this.

The webpage is running on the public IP address and can be accessed from any part of the world.

Currently, your server is only running until your terminal is open. To keep it running all the time, follow these commands.

6. Creating a Separate Screen to Run the Application

We will create a different screen for the terminal, which keeps the server running all the time.

Installing screen package on Linux

sudo apt-get install screen
screen

Rerun the server in the new screen

$ python manage.py runserver 0.0.0.0:8000

Congrats, now you have deployed your web app👏. 

GitHub link to the complete code here.

Conclusion

It is all for today. In this article, we have deployed a Django application on the Google Cloud Platform using its Compute Engine Services.

The key takeaways of this article are:
1. We have GUI for our previous Django App.
2. After that, we created our VM Instance.
3. We created firewall rules to allow the application to listen on PORT 8000.
4. Then, we deployed our application onto that VM.
5. Finally, we have solved the error of Allowed Hosts and created a separate screen to keep the server running.

You can also use famous web servers like Apache or Nginx while deploying your application. These web servers provide diverse workloads and are also compatible with other software. Also, you can point your static IP address to a domain name. So, when you enter your domain name, you will be automatically redirected to your IP address.

The media shown in this article is not owned by Analytics Vidhya and is used at the Author’s discretion.

Responses From Readers

Clear

Congratulations, You Did It!
Well Done on Completing Your Learning Journey. Stay curious and keep exploring!

We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.

Show details