How to create microservice in NodeJS with Docker?

How to create microservice in NodeJS with Docker?

tudip-logo

Tudip

21 July 2020

Microservice architecture is a way to develop software systems that mainly try to focus on building single-function modules with well-defined interfaces, methods, and operations.

Initial Steps

First install Node.js using the OS specific commands.

Run the command npm init in the root folder for the project.

$ npm init

Let install packages initially required to run the service:

$ npm install express request body-parser cors dotenv nodemon --save

There are files and a folder created by the npm init command. These are package.json, package-lock.json, and node_modules.

Lets create a primary file in our project named server.js. And create folders  controllers, helpers, routes and services. As shown below:

microservice_in_nodeJS_with_Docker_01

To build this microservice, let’s assume that we have the title of a Movie or TV series. The requirement wants the service to configure external API calls to get all movies that match the title.

Let’s build our service!

Create a Server to Accept Requests

For this, you need to create the server.js file, which is the primary file of the project. The  following code are used to create server.js file goes like this:

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
require('dotenv').config();
const port = process.env.SERVER_PORT || 4000;
const routes = require('./routes/index');
const app = express();

app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true }));
// To enable CORS => (Cross Origin Resource Sharing)
app.use(cors());
// Starting points for the routes
app.use('/api/', routes);

app.listen(port, () => {
console.info(`Server started on port ${port}`);
});

Define Routes

Create index.js file inside the routes folder to add all routes for the service.Here get the instance of the express router to define route URL. Then use the router instance to define routes like(“/search”).

const express = require('express');
const searchRoutes = require('./search');
const router = express.Router();

router.use('/search', searchRoutes);

module.exports = router;

After that create specific routes file for the search route(search.js). Here add route to get the movies by their title.

const express = require('express');
const searchCtrl = require('../controllers/search');
const router = express.Router();
module.exports = router;

router.get('/movie/:title',  searchCtrl.searchMovie);

Build the Controller

Adding controller logic to the microservice equips it with some interesting functions.For this microservice, create a method that call the TMDB service to get movies based on the title in the request params.

const TMDBService = require(`../services/TMDBService`);

module.exports = {
   searchMovie: (req, res) => {
       if (!req.params.title) {
           res.send("Required information is missing");
       }else {
           TMDBService.searchTMDB('movie', req.params.title).then((data) => {
               res.send(data);
           }).catch((err) => {
               res.send(err.message);
           });
       }
   },
};

Create service for the External API Call

Now that the controllers are added, we need external service to get the data for movies. For that we are using the TMDB 3rd Party APIs. To get the API key, you can get it for free by registering from THEMOVIEDB.ORG.

const request = require(`request`);
const BASE_URL = 'https://api.themoviedb.org/3/';

const API_KEY = 'XXXXXXXXXXXXXXXXXXXXXXXXX';

module.exports = {
    searchTMDB: (type, searchQuery) => {
        let headers = {
            "content-type": "application/json"
        };
        return new Promise((resolve, reject) => {
            let URL = `${BASE_URL}search/${type}/?query=${searchQuery}&api_key=${API_KEY}`;
            request.get(URL, {
                headers,
            }, (err, response, body) => {
                 console.log(err, body, response);
                if (err) {
                    reject(err);
                } else if (response && response.statusCode === 200) {
                    resolve(body);
                } else {
                    reject(body);
                }
            })
        })

    },
};

Add DockerFile to build the service

To run the service as dockerize unit first we need to add Dockerfile in our project structure.

FROM node:8

# Create app directory and epgpub directory
RUN mkdir /src
WORKDIR /src

# Install app dependencies
ADD package.json /src/package.json
RUN npm install

#Bundle app source
COPY . /src

EXPOSE 4000

CMD npm start

Run the service using Docker

To run the microservice first we need to create a docker image using the following command.

To build image:

docker build -t image_name .

Then run the image by defining the container port.

To run container from image:

docker run -d -p {local_port}:{container_port} --name container_name image_name

Execution:
After running the microservice using docker. Test the service to by hitting the URL on the PostMan.For example: http://localhost:{container_port}/api/search/movie/avenger

Request a quote