Google Cloud App Engine — Platform as a service

Google App Engine is a cloud computing platform as a service for developing and hosting web applications in Google-managed data centers. Based on the requests volume, the engine allocates resources for the web application to accommodate the increasing demand. It lets you focus on the development, making you free from worrying about infrastructure concerns like hardware, operating system, or physical location of the server. It also lets users choose language of their choice for development like Go, Python, Java, NodeJS, PHP, .NET, Ruby or other language (through custom runtime in the App Engine flexible environment)

The App Engine provides support for two environments — App Engine Flexible Environment and App Engine Standard Environment. For this post, we will see the demo for Standard Environment.

Demo — Web Application hosted on App Engine relying on Google Cloud MySQL for data storage

Create a App Engine using Google Cloud CLI or Google Cloud Shell

Once you have activated your google cloud account with a project created(billing enabled), follow the below steps. I used Google Cloud shell to create an App Engine for this demo.

Create Cloud SQL Instance

Step 1:, Create Cloud SQL Instance

Give the specifications you wish to give for your SQL instance and choose “Create Instance”

Step 2: Get the instance connection name to use it in the application for connecting with SQL instance

In the overview page of the SQL instance, you can find the Instance Connection Name. Copy it.

Note down the instance connection name, database user, and database password that you create.

Create a database in the above created MySQL instance based on your requirements.

Database name: medium_demo

In the overview page of the MySQL instance, click databases and create one by giving the name for the database.

Create a table in the database created

Step 1: In the overview page, click the “open cloud shell” option to connect to the SQL instance using gcloud. Using the shell, you can perform SQL operations on the database created.

Give the following gcloud sql command to establish the connection

gcloud sql connect myinstance — user=root — project=medium-354300

A table “users” is created with USER_ID, firstName, lastName columns.

Enable Cloud Build API

Url to enable:

https://console.cloud.google.com/flows/enableapi?apiid=cloudbuild.googleapis.com&_ga=2.80460049.769930725.1656028579-569780488.1654628170

Verify if Git is installed in the shell

Set up a Node.js development environment

  • Install Node Version Manager (NVM).
  • Install Node.js and npm (Node Package Manager).
  • Install an editor.
  • Install the Google Cloud CLI.
  • Install the Cloud Client Libraries for Node.js.

Install NVM

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash

Verify nvm installation:

command -v nvm // It should output nvm

Install Node.js and npm

Edit the default service account (that App Engine uses) with “Cloud SQL Client” permission

A service account is a special kind of account used by an application, rather than a person. Applications use service accounts to make authorized API calls. In our case, it helps to authenticate our connection to the google cloud SQL Instance.

Step 1: Go to the IAM & Admin section in your google cloud console and select the Service Account that has the name as “App Engine default service account”.

Step 2: Click Edit and Make sure you give one of the following roles for the service account by choosing under “Select a Role”

  • Cloud SQL > Cloud SQL Client
  • Cloud SQL > Cloud SQL Editor
  • Cloud SQL > Cloud SQL Admin

By end of this step, the default service account that your App Engine uses, is authenticated to make calls to the Cloud SQL instance.

Connect with Unix sockets

Make sure you have the following files in your directory for app deployment,

package.json // Specifying the dependenciesapp.yaml // Specifying the runtime environmentYour-application-code.js // Application code with cloud_sql_instances

Please find the code I used for deployment below and edit them with your values

INSTANCE_CONNECTION_NAME=’<MY-PROJECT>:<INSTANCE-REGION>:<INSTANCE-NAME>’DB_USER=’my-db-user’DB_PASS=’my-db-pass’DB_NAME=’my_db’

package.json

{“name”: “cloudsql-mysql-mysql”,“description”: “Node.js Cloud SQL MySQL Connectivity Sample”,“private”: true,“license”: “Apache-2.0”,“author”: “Google Inc.”,“repository”: {“type”: “git”,“url”: “https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git"},“engines”: {“node”: “>=10.0.0”},“scripts”: {“start”: “node check_deployement.js”,“deploy”: “gcloud app deploy”,“lint”: “samples lint”,“pretest”: “npm run lint”,“test”: “samples test app”},“dependencies”: {“@google-cloud/logging-winston”: “⁴.0.0”,“express”: “⁴.17.1”,“promise-mysql”: “⁵.0.0”,“prompt”: “¹.0.0”,“pug”: “³.0.0”,“winston”: “³.1.0”},“devDependencies”: {“mocha”: “⁸.0.0”,“proxyquire”: “².1.0”,“sinon”: “¹⁰.0.0”,“supertest”: “⁶.0.0”}}

app.yaml

runtime: nodejs16beta_settings:# The connection name of your instance, available by using# ‘gcloud beta sql instances describe [INSTANCE_NAME]’ or from# the Instance details page in the Google Cloud Platform Console.cloud_sql_instances: medium-354300:us-west2:myinstanceruntime: nodejs16beta_settings:# The connection name of your instance, available by using# ‘gcloud beta sql instances describe [INSTANCE_NAME]’ or from# the Instance details page in the Google Cloud Platform Console.cloud_sql_instances: medium-354300:us-west2:myinstance

check_deployment.js

‘use strict’;const express = require(‘express’);const mysql = require(‘promise-mysql’);const app = express();app.set(‘view engine’, ‘pug’);app.enable(‘trust proxy’);app.use(express.urlencoded({extended: false}));app.use(express.json());app.use((req, res, next) => {res.set(‘Content-Type’, ‘text/html’);next();});const winston = require(‘winston’);const {LoggingWinston} = require(‘@google-cloud/logging-winston’);const loggingWinston = new LoggingWinston();const logger = winston.createLogger({level: ‘info’,transports: [new winston.transports.Console(), loggingWinston],});const createUnixSocketPool = async config => {console.log(“Inside Socket”)return await mysql.createPool({user: ‘root’, // e.g. ‘my-db-user’password: ‘root’, // e.g. ‘my-db-password’database: ‘medium_demo’, // e.g. ‘my-database’socketPath: ‘/cloudsql/medium-354300:us-west2:myinstance’,…config,});};const createPool = async () => {const config = {connectionLimit: 5,connectTimeout: 10000, // 10 secondsacquireTimeout: 10000, // 10 secondswaitForConnections: true, // Default: truequeueLimit: 0, // Default: 0};return await createUnixSocketPool(config);};const ensureSchema = async pool => {console.log(“Ensured that table ‘users’ exists”);};const createPoolAndEnsureSchema = async () =>await createPool().then(async pool => {await ensureSchema(pool);return pool;}).catch(err => {throw err;});let pool;app.use(async (req, res, next) => {if (pool) {return next();}try {pool = await createPoolAndEnsureSchema();next();} catch (err) {logger.error(err);return next(err);}});app.get(‘/’, async (req, res) => {res.json({status: “All Good here!!”});});app.get(‘/users’, async (req, res) => {try {const tabsQuery = pool.query(“SELECT * FROM medium_demo.users;”);let x = await tabsQuery;res.json(x);} catch (err) {console.error(err);res.status(500).send(‘Unable to load page. Please check the application logs for more details.’).end();}});const PORT = process.env.PORT || 8080;const server = app.listen(PORT, () => {console.log(`App listening on port ${PORT}`);console.log(‘Press Ctrl+C to quit.’);});process.on(‘uncaughtException’, function (err) {console.log(err);throw err;});module.exports = server;

Test the application

RUN the following command in the cloud shell

gcloud app deploy app.yaml

Post request to the deployed url to see the results,

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Teepika R M

Teepika R M

AWS Certified Big Data Specialty| Linux Certified Kubernetes Application Developer| Hortonworks Certified Spark Developer|Hortonworks Certified Hadoop Developer