Microservices Using Docker and Nodejs

Microservices Using Docker and Nodejs

Learn how to use Nodejs with docker to build microservice applications

Let's Understand what is a microservice?

Microservices – or microservices architecture – are applications that are arranged or structured as a collection of loosely coupled services. Microservices promise quicker and easier software changes compared to traditional monolithic architectures by modularizing complex applications. Developers then compose applications from the resulting interchangeable, upgradable, and scalable parts. After identifying the individual services, developers refactor the monolith so that each service runs autonomously as a separate "microservice". In an ideal world, this modular architectural style accelerates business growth by enabling the agile deployment of innovative functionality.

Why you should use Microservice Architecture?

  1. Scalable one of the strongest advantages of microservices architecture is unparalleled scalability and capacity to grow. The capacity of each microservice to run autonomously makes it relatively easy to add, remove, update, and scale individual microservices.

  2. Eases Fault Isolation for More Resilient Applications With a microservices architecture, the failure of one service is less likely to negatively impact other parts of the application because each microservice runs autonomously from the other applications. Microservices enable developers to conduct unit testing more efficiently than in monolithic applications because they can isolate decoupled components. This can help speed up the Minimum Time To Recovery (MTTR), which is the time to repair and recover from a system failure—in case it happens.

  3. Microservices work well with containers You can run a simple network of containers and assign them proper ports and your microservice architecture will be ready in no time. The big benefit here is that using microservices with containers reduces the complexity of managing up to hundreds of microservices per application.

After containerizing your application, you can use a container tool such as Docker or Kubernetes to optimally manage most aspects of running microservices.

Lets Make a Simple Nodesjs Application

First, let's learn how to create a docker image of a Nodejs application.

We will create a docker image for our Nodejs application. A Docker image is a self-contained unit that bundles the app with the environment required to run it. No more installing libraries, dependencies, downloading packages, messing with config files, etc. If your machine supports Docker, you can run a Dockerized app, period.

For this tutorial let's first create a new simple Node Js application.

Create a simple Node.js app

User the commands below to create a simple nodejs application.

mkdir nodejs_docker
cd nodejs_docker
npm init

set the name to nodejs_docker. For other options, just confirm the default values with enter.

Npm will create a package.json file that will hold the dependencies of the app. Let's add the Express framework as the first dependency:

npm install express --save

The file should look like this now:

{
  "name": "nodejs_docker",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1"
  }
}

Now create an index.js file with a simple HTTP server that will serve the nodejs_docker app, this code will just run the server and will give a confirmation message that the server is running:

//Load express module with `require` directive
var express = require('express')
var app = express()

//Define request response in root URL (/)
app.get('/', function (req, res) {
  res.send('Hello World!')
})

//Launch listening server on port 8081
app.listen(8081, function () {
  console.log('app listening on port 8081!')
})

Run the app

The application is ready to launch:

node index.js

Go to localhost:8081 in your browser to view it.

Dockerize Node.js application

Once the node applicaiton is up and running the next step we can take is to dockerize this application. To do this go ahead and install Docker on your system. After this create an empty file called DockerFile in our codebase.

Open the DockerFile in any code editor. Now let's create the docker file.

  • Line 1: We have to mention which version of node do we want and image we want to build from.
FROM node:16
  • Line 2: making a working directory in the contaier to /app. This will create a folder inside the docker container.
WORKDIR /app
  • Line 3-4-5: Copy the application to the /app directory and install dependencies. If you add the package.json first and run npm install later, Docker won't have to install the dependencies again if you change the package.json file.
COPY package.json /app
RUN npm ci --only=production && npm cache clean --force
COPY . /app
  • Line 6: This line describes what should be executed when the Node Docker image is launching. What we want to do is to run our application:
CMD node index.js
  • Line 7: Now all things are being done inside the container and no one can access it until we expose the port.
EXPOSE 8081
  • Final Docker File
Summing up, the whole Dockerfile should look like this:

FROM node:12-alpine3.14
WORKDIR /app
COPY package.json /app
RUN npm ci --only=production && npm cache clean --force
COPY . /app
CMD node index.js
EXPOSE 8081

Build Docker image

With the instructions ready, all that remains is to run the docker build command, set the name of your image with -t parameter, and choose the directory where the Dockerfile is located:

docker build -t nodejs_docker .

Run Docker container

The application has been baked into the image. Dinner time! Execute the following command to launch the container and publish it on the host with the same port 8081:

docker run -p 8081:8081 nodejs_docker

#Thank You