Deploying a Node 12 Function to Cloud Run

Deploying a Node 12 Function to Cloud Run

In this post, we’ll learn how to deploy a Node 12 application using the Functions Framework and Cloud Run.

Originally published by Grant Timmerman at https://medium.com

Let’s say this.

  • You learn that the Node Foundation releases cutting-edge
  • Node 12
  • .It includes cool new features like more performant async/await, faster HTTP parsing, and private fields. It’s still in development but you want to use it for your services.But Google Cloud Functions doesn’t support Node 12 yet.

So whatchagunnado?

  • Blog about it?

…Maybe

  • Or use Cloud Run

Let’s learn how to do that!

Deploying a Node 12 Function to Cloud Run

Node is a JavaScript runtime built on Chrome’s V8 engine.

Cloud Run (http://cloud.run) is a managed, serverless computing platform that abstracts away infrastructure management, so you can focus on building great applications.

Together, you can build scalable services atop Google Cloud in minutes.

First, Install Node 12

TJ has an incredibly simple Node module called n for managing Node versions (i.e. switching between 10 and 12). Install the global CLI called n:

sudo npm i n -g

Then switch your Node version to Node 12:

sudo n 12

Verify your Node version

node -v # v12.7.0
Create a Node 12 Function

Create a new package.json:

{
  "name": "ffnode12",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "start": "functions-framework"
  },
  "dependencies": {
    "@google-cloud/functions-framework": "^1.2.1"
  }
}

Hard to make it simpler than that!

Create a class in greeter.js that uses Node 12 private fields:

class Greeter {
  #name = 'Functions Framework';
  get name() {
    return this.#name;
  }
  set name(name) {
    this.#name = name;
  }
  sayHello() {
    return `Hello, ${this.#name}`;
  }
}

module.exports = Greeter;

#private field

Create an index.js file:

const Greeter = require('./greeter');

exports.function = (req, res) => {
const g = new Greeter();

// Can't access private fields
// greet.#name = 'NewName';

res.send(g.sayHello());
};

Private fields are inaccessible!

Test the Functions Framework locally

You’ll want to test your service locally to ensure you code works.

So we got things working locally. But how do we deploy this to Google Cloud? Read on!

Next, we’ll use Cloud Build + Cloud Run

Create a Dockerfile
OK. I’ll be honest. If you asked me 6 months ago what Docker was, I’d mumble something about boxes, container ships, and a blue whale. But…

Docker is really nothing to be afraid of. It is an open platform for developing and running applications. To run an application, you’ll need to create some instructions for Docker to set up your environment.

Create a file called Dockerfile (no file extension) as such:

# Use the official Node.js 12 image.

https://hub.docker.com/_/node

FROM node:12

Create and change to the app directory.

WORKDIR /usr/src/app

Copy application dependency manifests to the container image. A wildcard is used to ensure both package.json AND package-lock.json are copied. Copying this separately prevents re-running npm install on every code change.

COPY package*.json ./

Install production dependencies.

RUN npm install --only=production

Copy local code to the container image.

COPY . .

Run the web service on container startup.

CMD [ "npm", "start" ]

A basic Dockerfile for Node applications

We’ll tell Docker, use Node 12, copy our package.json we defined above, install, copy our files, then start our server!

Deploy to Cloud Run

To deploy to Google’s Cloud Run, follow these 3 steps:

1 - Setup gcloud

# Install gcloud beta services
gcloud components install beta# Set env var "GCP_PROJECT" to our project name
GCP_PROJECT=$(gcloud config list --format 'value(core.project)' 2>/dev/null)# Set our Cloud Run region (so we aren't prompted)
gcloud config set run/region us-central1

2 - Upload your code and build the container

# Build and upload your image in Google Container Registry
gcloud builds submit --tag gcr.io/$GCP_PROJECT/helloworld

Notice each command in the Dockerfile gets executed (~30s)

3 - Deploy to Cloud Run

# Deploy your container to Cloud Run
gcloud beta run deploy --image gcr.io/$GCP_PROJECT/helloworld --platform managed

Deploy our container to Cloud Run (~17s)

You’ll get a URL that looks like this:

https://helloworld-q7vieseilq-uc.a.run.app

Congrats! You deployed the Functions Framework to Cloud Run.



Dockerizing a Node.js web application

Dockerizing a Node.js web application

In this article, we will see how to dockerize a Node.js application. Dockerizing a Node.js web application

Originally published by  ganeshmani009 at  cloudnweb.dev

what is docker ?

Firstly, Docker is containerization platform where developers can package the application and run as a container.

In simple words, docker runs each application as a separate environment which shares only the resources such as os, memory, etc.

Virtual Machine vs Docker

Docker and node.js setup

Here, we can find the difference between the docker and virtual machines.

To read more about docker, Docker Docs

we are gonna see how to dockerize a node.js application. before that, docker has to be installed on the machine. Docker Installation

After installing the docker, we need to initialize the node application.

npm init --yes
npm install express body-parser

the first command initializes the package.json file which contains the details about the application and dependencies. the second one install the express and bodyParser

create a file called server.js and paste the following code

'use strict';

const express = require('express');

// Constants
const PORT = 8080;
const HOST = '0.0.0.0';

// App
const app = express();
app.get('/', (req, res) => {
res.send('You have done it !!!!!\n');
});

app.listen(PORT,()=>{
console.log(Running on http://${HOST}:${PORT});
});

this runs the basic express application server. now, we need to create the docker image file. create a file name called Dockerfile and add the following commands

FROM node:8

First we install the node image from the Docker hub to the image

WORKDIR /usr/src/app

Next, we set the /usr/src/app as the working directory in the docker image

COPY package*.json ./
RUN npm install

then copies the package.json from the local machine to docker image. It’s not an efficient way to copy the dependencies from local to docker image.

so we are just copying the package.json and install all the dependencies in the docker image

COPY . .
EXPOSE 8080

CMD [ "npm" , "start" ]

it copies all the source code from local to docker image, binds the app to port 8080 in the docker image. docker image port 8080 can be mapped with local machine port. then we run the command

Your Dockerfile should now look like:

# this install the node image from docker hub
FROM node:8

this is the current working directory in the docker image

WORKDIR /usr/src/app
#copy package.json from local to docker image
COPY package*.json ./
#run npm install commands
RUN npm install
#copy all the files from local directory to docker image
COPY . .
#this port exposed to the docker to map.
EXPOSE 8080

CMD [ "npm" , "start" ]

create a .dockerignore file with the following content:

node_modules
npm-debug.log

now, we need to build our image in the command line as :

$ docker build -t <your username>/node-web-app .

-t flag used to tag a name to image. so, it will be easy to identify with a name instead of id. Note : dot in the end of command is important(else it won’t work)

we could run the image using the following command :

docker run -p 49160:8080 -d <your username>/node-web-app

we can check it using

 curl -i localhost:49160

output should be:

HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: text/html; charset=utf-8
Content-Length: 23
ETag: W/"17-C2jfoqVpuUrcmNFogd/3pZ5xds8"
Date: Mon, 08 Apr 2019 17:29:12 GMT
Connection: keep-alive

You have done it !!!!!

To read more

https://github.com/nodejs/docker-node/blob/master/docs/BestPractices.md

Originally published by  ganeshmani009 at  cloudnweb.dev

=============================

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow me on Facebook | Twitter


Further reading

☞ The Complete Node.js Developer Course (3rd Edition)

☞ Angular & NodeJS - The MEAN Stack Guide

☞ NodeJS - The Complete Guide (incl. MVC, REST APIs, GraphQL)

☞ Best 50 Nodejs interview questions from Beginners to Advanced in 2019

☞ Node.js 12: The future of server-side JavaScript

☞ Docker for Absolute Beginners

☞ How to debug Node.js in a Docker container?

☞ Docker Containers for Beginners

☞ Deploy Docker Containers With AWS CodePipeline


Running Serverless Node.js on Google Cloud Functions

Running Serverless Node.js on Google Cloud Functions

Running Serverless Node.js on Google Cloud Functions

Google Cloud Functions is a service that allows you to run your code in the cloud. You don't need to manage server, just code for the application logic (serverless). It's also highly available and fault tolerant, as well as very automatically scales. There are some ways to trigger function execution, some of which are the result of integration with other Google Cloud services. In this tutorial, I'm going to show how to run serverless Node.js in Google Cloud Functions.

Preparation
  1. Create or select a Google Cloud project

A Google Cloud project is required to use this service. Open Google Cloud console, then create a new project or select existing project

  1. Enable billing for the project

Like other cloud platforms, Google requires you to enable billing for your project. If you haven't set up billing, open billing page.

  1. Enable Cloud Functions API

To use an API, you must enable it first. Open this page to enable Cloud Functions API.

  1. Set up service account for authentication

You need to install gcloud on your computer and get authenticated to access your account.

Writing a Function

First, create a folder for this project. Inside the folder, create a file with the following content.

index.js

  exports.helloWorld = (req, res) => res.send("Hello, World!");

Running Google Cloud Functions Emulator

Before running functions on the real Google Cloud servers, we can test whether the code works as expected by running Google Cloud Functions Emulator on your local machine.

  • First, you need to install the emulator using npm install -g @google-cloud/functions-emulator
  • Run it using functions start.
  • To deploy the helloWorld function we have created on the previous step, run functions deploy helloWorld --trigger-http
  • If the function successfully deployed, you will see a resource URL - open it to call the function
Deploying to Google Cloud Functions

Run the following command in order to deploy the functionn to Google Cloud Functions.

gcloud functions deploy helloAsync --trigger-http --project PROJECT_NAME

Below is the list of supported flags while running gcloud functions deploy command.

gcloud functions deploy (NAME : --region=REGION)
	        [--entry-point=ENTRY_POINT] [--memory=MEMORY] [--retry]
	        [--runtime=RUNTIME] [--source=SOURCE] [--stage-bucket=STAGE_BUCKET]
	        [--timeout=TIMEOUT] [--update-labels=[KEY=VALUE,...]]
	        [--clear-env-vars | --env-vars-file=FILE_PATH
	          | --set-env-vars=[KEY=VALUE,...]
	          | --remove-env-vars=[KEY,...] --update-env-vars=[KEY=VALUE,...]]
	        [--clear-labels | --remove-labels=[KEY,...]]
	        [--trigger-bucket=TRIGGER_BUCKET | --trigger-http
	          | --trigger-topic=TRIGGER_TOPIC
	          | --trigger-event=EVENT_TYPE --trigger-resource=RESOURCE]
	        [GCLOUD_WIDE_FLAG ...]

NAME is the ID of the function or fully qualified identifier for the function. Description for each flags is on the table below

Installing Dependencies

To install a module, add it to the dependencies of package.json. Google will automatically install all dependencies at the deployment.

Alternatively you can run npm install MODULE_NAME, which will update package.json content.

Using Node.js 8 Environment

Currently Google still uses Node.js 6 as the default version. With that version, you can't use some new features such as async/await. But Google makes it possible for use to use Node.js 8. First, add a function that won't run on Node.js 6, as examplified below.

index.js

 const request = require('request-promise');
 
  exports.helloAsync = async (req, res) => {
    const result = await request('https://www.example.com');
 
    return res.send(result);
  };

To use Node.js 8 runtime environment, add --runtime nodejs8 parameter to the command.

gcloud functions deploy helloAsync --trigger-http --project PROJECT_NAME --runtime nodejs8

Top Vue.js Developers in USA

Top Vue.js Developers in USA

Vue.js is an extensively popular JavaScript framework with which you can create powerful as well as interactive interfaces. Vue.js is the best framework when it comes to building a single web and mobile apps.

We, at HireFullStackDeveloperIndia, implement the right strategic approach to offer a wide variety through customized Vue.js development services to suit your requirements at most competitive prices.

Vue.js is an open-source JavaScript framework that is incredibly progressive and adoptive and majorly used to build a breathtaking user interface. Vue.js is efficient to create advanced web page applications.

Vue.js gets its strength from the flexible JavaScript library to build an enthralling user interface. As the core of Vue.js is concentrated which provides a variety of interactive components for the web and gives real-time implementation. It gives freedom to developers by giving fluidity and eases the integration process with existing projects and other libraries that enables to structure of a highly customizable application.

Vue.js is a scalable framework with a robust in-build stack that can extend itself to operate apps of any proportion. Moreover, vue.js is the best framework to seamlessly create astonishing single-page applications.

Our Vue.js developers have gained tremendous expertise by delivering services to clients worldwide over multiple industries in the area of front-end development. Our adept developers are experts in Vue development and can provide the best value-added user interfaces and web apps.

We assure our clients to have a prime user interface that reaches end-users and target the audience with the exceptional user experience across a variety of devices and platforms. Our expert team of developers serves your business to move ahead on the path of success, where your enterprise can have an advantage over others.

Here are some key benefits that you can avail when you decide to hire vue.js developers in USA from HireFullStackDeveloperIndia:

  • A team of Vue.js developers of your choice
  • 100% guaranteed client satisfaction
  • Integrity and Transparency
  • Free no-obligation quote
  • Portal development solutions
  • Interactive Dashboards over a wide array of devices
  • Vue.js music and video streaming apps
  • Flexible engagement model
  • A free project manager with your team
  • 24*7 communication with your preferred means

If you are looking to hire React Native developers in USA, then choosing HireFullStackDeveloperIndia would be the best as we offer some of the best talents when it comes to Vue.js.