» Node.js: Building Event-Driven Microservices with Kafka » 5. Deployment » 5.1 Dockerfile

Dockerfile

Docker allows developers to package their applications along with all dependencies into a single unit called a container. This ensures consistency across different environments, such as development, testing, and production, reducing the "it works on my machine" problem.

Install Docker: https://docs.docker.com/engine/install/

Dockerfile for the web service

Add src/web/Dockerfile:

# Use the official Node.js image with specified version
FROM node:20.11-alpine3.18

# Set the working directory inside the container
WORKDIR /usr/src/app

# Copy package.json and package-lock.json to the working directory
COPY package*.json ./

# Install project dependencies
RUN npm install

# Copy the rest of the application code to the working directory
COPY src/ /usr/src/app/src
COPY tsconfig.json ./

# Build TypeScript code
RUN npm run build

# Command to run the application
CMD ["node", "dist/web/app.js"]

Add src/web/.dockerignore:

config.json

Alpine Linux is a lightweight and secure Linux distribution that is particularly well-suited for containerized environments, embedded systems, and resource-constrained environments where efficiency and security are paramount.

Build the docker image for the web service:

docker build -t lrbooks_web_node:latest -f src/web/Dockerfile .

Similarly, add 2 more Dockerfiles:

Dockerfile for the trend service

Add src/trend/Dockerfile:

# Use the official Node.js image with specified version
FROM node:20.11-alpine3.18

# Set the working directory inside the container
WORKDIR /usr/src/app

# Copy package.json and package-lock.json to the working directory
COPY package*.json ./

# Install project dependencies
RUN npm install

# Copy the rest of the application code to the working directory
COPY src/ /usr/src/app/src
COPY tsconfig.json ./

# Build TypeScript code
RUN npm run build

# Command to run the application
CMD ["node", "dist/trend/app.js"]

Add src/trend/.dockerignore:

config.json

Dockerfile for the recommendation service

Add src/recommendation/Dockerfile:

# Use the official Node.js image with specified version
FROM node:20.11-alpine3.18

# Set the working directory inside the container
WORKDIR /usr/src/app

# Copy package.json and package-lock.json to the working directory
COPY package*.json ./

# Install project dependencies
RUN npm install

# Copy the rest of the application code to the working directory
COPY src/ /usr/src/app/src
COPY tsconfig.json ./

# Build TypeScript code
RUN npm run build

# Command to run the application
CMD ["node", "dist/recommendation/app.js"]

Add src/recommendation/.dockerignore:

config.json

With all the Dockerfiles, we‘re well prepared to run them all together in the Docker Compose.

PrevNext