Google Cloud Platform(GCP) — Dockerize a Node.js Web App and Deploy to Compute Engine Instance

Image for post
Image for post

Plan of the post:

Create Node.js Web App

$ mkdir node-web-app
$ cd node-web-app/
$ npm init
Image for post
Image for post
$ npm install -save express
$ vim package.json
Image for post
Image for post
$ touch app.js
$ vim app.js
'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('Hello World');
});

app.listen(PORT, HOST);
console.log(`Running on http://${HOST}:${PORT}`);
$ npm start
Image for post
Image for post
Image for post
Image for post

Create a Dockerfile

$ touch Dockerfile
FROM node:10

# Create app directory
WORKDIR /usr/src/app

# Install app dependencies
# A wildcard is used to ensure both package.json AND package-lock.json are copied
# where available (npm@5+)
COPY package*.json ./

RUN npm install
# If you are building your code for production
# RUN npm ci --only=production

# Bundle app source
COPY . .

EXPOSE 8080
CMD [ "node", "server.js" ]
node_modules
npm-debug.log

Install Google Cloud SDK

Create Google Cloud Project and Configure Local Environment

$ gcloud projects create compute-engine-docker-nodejs
$ gcloud projects list
Image for post
Image for post
$ gcloud config list
Image for post
Image for post
$ gcloud config set project <project-id>
Image for post
Image for post
$ gcloud config get-value project
Image for post
Image for post

Build and Deploy Docker Image with Google Cloud Commands

$ gcloud builds submit --tag gcr.io/<project-id>/docker-image
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post

Build and Deploy Docker Image with Docker Commands

$gcloud auth configure-docker
$docker build -t gcr.io/compute-engine-docker-nodejs/nodejs-local-build .
Image for post
Image for post
$docker images -a | grep gcr.io
Image for post
Image for post
$docker push  gcr.io/compute-engine-docker-nodejs/nodejs-local-build
Image for post
Image for post
Image for post
Image for post

Create Firewall Rules

Image for post
Image for post
Image for post
Image for post
Image for post
Image for post

Deploy Docker Image to Compute Engine and Run

Image for post
Image for post
Image for post
Image for post
Image for post
Image for post

Junior Full-Stack Developer

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