Crafting Custom Docker Images for a Node.js Service

A Node.js application can be packaged into a self-contained Docker image by defining a Dockerfile and building it with standard commands. The following steps walk through the process using a lightweight Express-based service.

First, scaffold a minimal server. Create a file named server.js with the following logic:

const express = require('express');
const app = express();
const LISTEN_PORT = 8080;

app.get('/', (request, response) => response.send('Greetings from Docker!'));

app.listen(LISTEN_PORT, () => {
  console.log(`App listening on port ${LISTEN_PORT}`);
});

Initilaize the project with npm init -y and install the dependency:

npm install express

Next, craft the Dockerfile in the project root. The example below uses a slim Alpine base, runs as a non‑root user, and installs only production dependencies:

FROM node:18-alpine
WORKDIR /usr/src/app

COPY package*.json ./
RUN npm ci --omit=dev

COPY . .
EXPOSE 8080
USER node

CMD ["node", "server.js"]

Build the image, tagging it as node-service:latest:

docker build -t node-service:latest .

Once the build finishes, start a container with port maping:

docker run -p 8080:8080 node-service:latest

Visiting http://localhost:8080 in a browser will display the greeting message.

A typical workflow follows the plan outlined below:

gantt
    title Docker Image Build Timeline
    dateFormat  YYYY-MM-DD
    section Prepare application
    Write server code          :done, 2025-01-01, 1d
    Define package.json        :done, after Write server code, 1d
    section Image assembly
    Write Dockerfile           :done, after Define package.json, 1d
    Build the image            :done, after Write Dockerfile, 1d
    section Runtime
    Run container              :done, after Build the image, 1d

Tags: docker Node.js containerization devops

Posted on Tue, 07 Jul 2026 16:41:17 +0000 by greenberry