Forbes India Leader Recognition
e.preventDefault(); // Prevent form submission input.blur(); // remove focus input.value = ""; // optional: clear the input

How to create microservice in NodeJS with Docker?

How to create microservice in NodeJS with Docker?

Featured Image

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

Related Posts

Latest Posts

  • All Posts
  • AI Powered Knowledge
  • ai/ml
  • CEO India Magazine
  • CMMI level 5 Certification
  • e-learning
  • Fintech
  • gaming
  • Generative AI
  • healthcare
  • manufacturing
  • News
  • OTT
  • Portfolio
  • supply chain
  • travel and hospitality
  • Tudip's AI Hackathon
  • Voxlearn Enterprises
    •   Back
    • Android
    • iOS
    • Java
    • PHP
    • MEAN
    • Ruby
    • DotNet
    • IoT
    • Cloud
    • Testing
    • Roku
    • CMS
    • Python
The Future of Workplace Learning: AI-Powered Knowledge on Demand

The Future of Workplace Learning: AI-Powered Knowledge on Demand

June 12, 2026

A few months ago, I was sitting in a meeting with a team lead who looked genuinely frustrated. Not because…

Read More
We Did It Again: Tudip Successfully Renews Its CMMI Level 5 Certification

We Did It Again: Tudip Successfully Renews Its CMMI Level 5 Certification

June 9, 2026

Nobody around here needed a memo to know something worth celebrating had happened. The message from the CMMI Institute said…

Read More
CEO India Magazine Features Dipti Agrawal: The Woman Behind Intelligent Enterprise Solutions

CEO India Magazine Features Dipti Agrawal: The Woman Behind Intelligent Enterprise Solutions

June 9, 2026

There are moments at work that just stop you in your tracks. Not the big quarterly reviews or the product…

Read More

India

Plot No. 11/2, Phase 3, Hinjewadi Rajiv Gandhi Infotech Park, Pune, India – 411057.
info@tudip.com
+91-96-8990-0537

United States

1999 S. Bascom Ave Suite 700, Campbell CA. 95008, USA.
info@tudip.com
+1-408-216-8162

Canada

64 Caracas Road North York, Toronto Ontario M2K 1B1, Canada.
info@tudip.com

Mexico

Calle Amado Nervo #785 Interior B Colonia Ladron De Guevara 44600 Guadalajara, Jalisco, Mexico.
info@tudip.com

Singapore

77 High Street, #10-12B High Street Plaza, Singapore 179433.
info@tudip.com

Colombia

Cra. 9 # 113-53 Of. 1405 Bogotá D.C., Colombia.
info@tudip.com

UAE

Tudip Information Technologies L.L.C Office No 109, ABU HAIL BUILDING 13, Abu Hail, Dubai, UAE.
info@tudip.com

Nigeria

22 Kumasi Crescent, Wuse 2, Abuja, Nigeria.
info@tudip.com