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

Plan of the post:

Create Node.js Web App

$ mkdir node-web-app
$ cd node-web-app/
$ npm init
$ npm install -save express
$ vim package.json
$ 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

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
$ gcloud config list
$ gcloud config set project <project-id>
$ gcloud config get-value project

Build and Deploy Docker Image with Google Cloud Commands

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

Build and Deploy Docker Image with Docker Commands

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

Create Firewall Rules

Deploy Docker Image to Compute Engine and Run

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