Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Deploying Your Serverless Functions to Google Cloud Platform

DZone's Guide to

Deploying Your Serverless Functions to Google Cloud Platform

AWS and Microsoft aren't the only serverless games in town. Google Cloud Platform supports serverless functions, so let's set one up that responds to HTTP GET requests.

· Cloud Zone
Free Resource

What if you could learn how to use MongoDB directly from the experts, on your schedule, for free? We've put together the ultimate guide for learning MongoDB. Sign up and you'll receive instructions for how to get started!

In this tutorial, we are going to cover how to host a minified HTTP GET-based serverless application on Google Cloud Platform. Such a typical app is an excellent serverless side to an Ionic mobile app. When we say serverless platforms, it doesn't mean it's running on no server, so while the term serverless is good, it's a bit misleading. The following is taken from Google Firebase serverless platform

"Cloud Functions is a hosted, private, and scalable Node.js environment where you can run JavaScript code. The Firebase SDK for Cloud Functions integrates the Firebase platform by letting you write code that responds to events and invokes functionality exposed by other Firebase features."

Martin Fowler, in his great serverless blog, also mentions that serverless is a slightly misleading term:

"The term ‘Serverless’ is confusing since with such applications there are both server hardware and server processes running somewhere, but the difference to normal approaches is that the organization building and supporting a ‘Serverless’ application is not looking after the hardware or the processes - they are outsourcing this to a vendor."

So with that understanding in hand, we are going to write a small server implementation, ehh, that is a serverless implementation hosted on Google Cloud Platform.

Our plan:

  • Step 1: Make sure you have an up-to-date gcloud.

  • Step 2: Enable gcloud beta components.

  • Step 3: Code the serverless function.

  • Step 4: Prepare GCP to host your function.

  • Step 5: Upload your function to GCP.

  • Step 6: Test your function with an HTTP GET request!

Step 1: Make Sure You Have an Up-to-Date gcloud

gcloud is a great command line utility for manipulating — you guessed it — Google Cloud Platform.

I already have gcloud installed, so that means I don't need to install it — but I would need to update it.

If you don't already have gcloud installed, then download Google Cloud Platform and install it. If you already have it installed, then make sure you update it with:

 $ gcloud components update 

The result should be similar to:

Your current Cloud SDK version is: 113.0.0
You will be upgraded to version: 150.0.0

Performing post processing steps...done.

Start a new shell for the changes to take effect.


Update done!

To revert your SDK to the previously installed version, you may run:
$ gcloud components update --version 113.0.0


Note: You need to start a new shell, as mentioned, for the changes to take effect!

Step 2: Enable gcloud Beta Components

This step is extremely short — just enable the beta components for gcloud.

 gcloud components install beta 

And the result would be similar to this:

Your current Cloud SDK version is: 150.0.0
Installing components from version: 150.0.0

┌─────────────────────────────────────────────┐
│ These components will be installed. │
├──────────────────────┬────────────┬─────────┤
│ Name │ Version │ Size │
├──────────────────────┼────────────┼─────────┤
│ gcloud Beta Commands │ 2017.03.24 │ < 1 MiB │
└──────────────────────┴────────────┴─────────┘
.

.

.

Performing post processing steps...done.
Update done!

Step 3: Code the Serverless Function!

We are going to have a simple function that will return 'hello world'.

$ mkdir serverless-example
tomerb@tomerb-mac.local:~/tmp$ cd serverless-example/
tomerb@tomerb-mac.local:~/tmp/serverless-example$


 vi index.js 

exports.helloWorld = function helloWorld (req, res) {
  if (req.body.message === undefined) {
    res.status(400).send('err error');
  } else {
    console.log(req.body.message);
    res.status(200).send('Hello World!');
  }
};


Step 4: Prepare GCP to Host Your Function

Now we are going to create a project and a bucket inside GCP in order to host our function there:

  1. Log into the Google Cloud Console.

  2. Click "create project".

  3. Enter the name "serverless-example" and hit ENTER.

  4. Enable billing if not enabled (you will see a message in GCP).  (Don't worry).

  5. Now for the important command in that section, relate your function folder to your Google Cloud Storage project and bucket  gsutil mb -p [PROJECT_ID] gs://[BUCKET_NAME] 

In our case:

$ gsutil mb -p serverless-example gs://serverless-example-bucket
Creating gs://serverless-example-bucket/...


In this step, we are going to enable functions on GCP.  That's easy.

  1. On Google Cloud Console's left menu...

  2. Click "cloud functions"

  3. Click "Enable"

Set the current project to "serverless-example".

$ gcloud config set project serverless-example
Updated property [core/project].

Step 5: Upload (Deploy) the Function!

$ gcloud beta functions deploy helloWorld --stage-bucket serverless-example-bucket --trigger-http

# Result:
Copying file:///var/folders/cj/9m49dzl57nv1wtnt01nzt291k56hj5/T/tmpvL2tU7/fun.zip [Content-Type=application/zip]...
\ [1 files][  304.0 B/  304.0 B]
Operation completed over 1 objects/304.0 B.
Waiting for operation to finish...done.
Deploying function (may take a while - up to 2 minutes)...done.
availableMemoryMb: 256
entryPoint: helloWorld
httpsTrigger:
  url: https://us-central1-serverless-example.cloudfunctions.net/helloWorld
latestOperation: operations/c2VydmVybGVzcy1leGFtcGxlL3VzLWNlbnRyYWwxL2hlbGxvV29ybGQvWWdhT2FkZ2Y0dXc
name: projects/serverless-example/locations/us-central1/functions/helloWorld
serviceAccount: serverless-example@appspot.gserviceaccount.com
sourceArchiveUrl: gs://serverless-example-bucket/us-central1-helloWorld-nnwxgbodbtkh.zip
status: READY
timeout: 60s
updateTime: '2017-04-10T16:42:30Z'

Step 6: Run Your Function!

Run a similar URL to: https://us-central1-serverless-example.cloudfunctions.net/helloWorld, and it should return 200 OK. If you check out the logs on your GCP console, you should see:

I  {"@type":"type.googleapis.com/google.cloud.audit.AuditLog","status":{},"serviceName":"cloudfunctions.googleapis.com","methodName":"google.cloud.functions.v1beta2.CloudFunctionsService.UpdateFunction","resourceName":"projects/serverless-example/locations/us-central1/functions/helloWorld"} 
D  helloWorld i72z9gnkulsh Function execution started helloWorld i72z9gnkulsh 
D  helloWorld i72z9gnkulsh Function execution took 197 ms, finished with status code: 400 helloWorld i72z9gnkulsh 
D  helloWorld i72zp0x2d46t Function execution started helloWorld i72zp0x2d46t 
D  helloWorld i72zp0x2d46t Function execution took 7 ms, finished with status code: 400 helloWorld i72zp0x2d46t 


Summary

We have deployed a Google Cloud function with a few easy steps. We have enabled billing, created a bucket, created a short function that responds to HTTP GET requests, deployed it, and then simply ran it. We have also briefly mentioned the fact that serverless functions are also kind of servers, only not managed by you.

What if you could learn how to use MongoDB directly from the experts, on your schedule, for free? We've put together the ultimate guide for learning MongoDBSign up and you'll receive instructions for how to get started!

Topics:
google cloud platform ,cloud ,tutorial ,serverless architecture ,serverless functions

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}