Unleashing the Power of Microservices: A Comprehensive Guide for Web Developers 😎

Prerequisites 📋

  • Basic understanding of development with Node.js
  • Docker and Kubernetes installed on your local machine.
  • Kubernetes command-line tool, kubectl, installed.

Building a Microservice with Node.js and Express 🛠

Firstly, let's start by creating a simple microservice using Node.js and express. Create a new directory for your service and run the following command to initialize a new Node.js project.

mkdir my-service
cd my-service
npm init -y

Next, install express to create our web server.

npm install express

Once express is installed, create a new app.js file on the root directory and paste the following code:

const express = require('express');
const app = express();
const port = process.env.PORT || 3000; 

app.get('/', (req, res) => {
  res.send('Hello, Microservice!');
});

app.listen(port, () => {
  console.log(`App listening at http://localhost:${port}`);
});

This code creates a simple server that sends a 'Hello, Microservice!' message when you navigate to the homepage.

Now you should be able to run your service by executing this command:

node app.js

Navigate to http://localhost:3000 on your browser. You should see the 'Hello, Microservice!' message.

Dockerizing the Microservice 📦

To create a Docker container for our microservice, we need to write a Dockerfile. In your root directory, create a new file called Dockerfile and paste the following code:

FROM node:10-alpine
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["node", "app.js"]

This Dockerfile creates a lightweight Docker image based on Node.js 10. It copies your local files into the Docker image and installs our dependencies. Then, it exposes port 3000 and starts our microservice.

Build the Docker image using the following command:

docker build -t my-service .

Finally, run the Docker container:

docker run -p 3000:3000 my-service

Navigate to http://localhost:3000 on your browser again. You should still see the 'Hello, Microservice!' message, but this time it's served from a Docker container!

We have seen how to build, dockerize and run a single microservice. In the next blog post, I'll guide you on how to leverage Kubernetes to manage and orchestrate various such microservices.

Happy Coding! 💻

References:

P.S.: Technology evolves quickly. The information contained in these links may be outdated.