How do I deploy a cloud code? Let’s see the steps in this article. Bobcares, as a part of our Google Cloud Platform Support Services, offers solutions to every query that comes our way.
How do I deploy a cloud code?
With the Cloud code, there is no need to manage and scale our own servers. It allows apps to automatically run javascript-based functions on the server side in response to events triggered by Parse and HTTP requests. The JavaScript code is run in a managed environment and is stored on the Back4App servers.
Common use cases for Cloud Code include database triggers, request validators, and integrations.
We’ve to deploy the container on a GCE VM once the image has been added to the registry. The automatic provisioning of a Container-Optimized OS with a Docker installer is a cool feature of GCE. This indicates that the container will start running as soon as the VM starts.
Google Cloud Billing Support offers solutions to GCE-pricing-related queries.
Deploying a container on a GCE VM
Let’s see the steps to deploy a container on a GCE VM:
- On GCE, we’ve to create a VM. Then set the required Region & Zone.
- Check “Deploy a container image to this VM instance” in the container section.
- Enter the container image. This is the actual location of the container imager.
- Now change Restart Policy to *On failure* and Run as privileged as * True*.
- Finally, check the boxes next to Allocate a pseudo-TTY and Allocate a buffer for STDIN because we needed these options to link to the container.
The above steps successfully host a container on a GCE VM. Now to deploy the cloud code, we need to use two GCP components, Cloud Scheduler
and Cloud Functions
.
Creating Cloud Functions
- Visit the page for Cloud Functions.
- Now create the Function.
- Modify Function Nae to startInstancePubSub.
- Keep Region’s default setting in place.
- Choose Cloud Pub/Sub as the trigger type.
- Choose “Create a topic” under “Select a Cloud Pub/Sub topic”.
- There should be a New pub/sub topic dialogue box.
- Enter start-instance-event under Topic ID.
- In order to complete the dialogue box, click Create Topic.
- At the bottom of the Trigger box, click Save.
- At the bottom of the page, click Next.
- Choose Node.js 10 under Runtime.
- Enter startInstancePubSub as the entry point.
- Select index.js from the code editor’s left side.
- Replace the starter code with the following code:
functions/scheduleinstance/index.js
const compute = require('@google-cloud/compute'); const instancesClient = new compute.InstancesClient(); const operationsClient = new compute.ZoneOperationsClient();
asyncfunction waitForOperation(projectId, operation) { while (operation.status !== 'DONE') { [operation] = await operationsClient.wait({ operation: operation.name, project: projectId, zone: operation.zone.split('/').pop(), }); } }
/** * Starts Compute Engine instances. * * Expects a PubSub message with JSON-formatted event data containing the * following attributes: * zone - the GCP zone the instances are located in. * label - the label of instances to start. * * @param {!object} event Cloud Function PubSub message event. * @param {!object} callback Cloud Function PubSub callback indicating * completion. */ exports.startInstancePubSub = async (event, context, callback) => { try { const project = await instancesClient.getProjectId(); const payload = _validatePayload(event); const options = { filter: `labels.${payload.label}`, project, zone: payload.zone, };
const [instances] = await instancesClient.list(options);
awaitPromise.all( instances.map(async instance => { const [response] = await instancesClient.start({ project, zone: payload.zone, instance: instance.name, });
return waitForOperation(project, response.latestResponse); }) );
// Operation complete. Instance successfully started. const message = 'Successfully started instance(s)'; console.log(message); callback(null, message); } catch (err) { console.log(err); callback(err); } };
/** * Validates that a request payload contains the expected fields. * * @param {!object} payload the request payload to validate. * @return {!object} the payload object. */ const _validatePayload = event => { let payload; try { payload = JSON.parse(Buffer.from(event.data, 'base64').toString()); } catch (err) { throw new Error('Invalid Pub/Sub message: ' + err); } if (!payload.zone) { throw new Error("Attribute 'zone' missing from payload"); } else if (!payload.label) { throw new Error("Attribute 'label' missing from payload"); } return payload; };
- Choose package.json on the left side of the code editor.
- Replace the starter code with the following code:
functions/scheduleinstance/package.json
{ "name": "cloud-functions-schedule-instance", "version": "0.1.0", "private": true, "license": "Apache-2.0", "author": "Google Inc.", "repository": { "type": "git", "url": "https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git" }, "engines": { "node": ">=12.0.0" }, "scripts": { "test": "mocha test/*.test.js --timeout=20000" }, "devDependencies": { "mocha": "^9.0.0", "proxyquire": "^2.0.0", "sinon": "^14.0.0" }, "dependencies": { "@google-cloud/compute": "^3.1.0" } }
- Finally, click on the “Deploy” option.
We can also create a stop function using the same steps as above. For the correct code snippet, visit the Google Cloud Support page.
We can see both functions in the main pane after we create the two functions. By entering the function and selecting Test mode, we can verify that the VM is launched properly by the function.
[Need help with another query? We’re just a click away.]
Conclusion
In this article, we provided the steps to deploy a cloud code, including the steps to deploy a container on a GCE VM and to create cloud functions.
PREVENT YOUR SERVER FROM CRASHING!
Never again lose customers to poor server speed! Let us help you.
Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.
var google_conversion_label = "owonCMyG5nEQ0aD71QM";
0 Comments