Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

dockerized-node-microservice

Node.js Fastify Docker pino License: MIT

A cloud-native Node.js microservice built to production operational standards — demonstrating container lifecycle management, structured observability, graceful shutdown, and request pipeline architecture.

Part of the cloud-platform-showcase portfolio — a collection of production-style engineering projects.


Demo

Container health

After make up, the Docker HEALTHCHECK confirms the service is alive and accepting traffic:

$ docker compose ps

NAME                     IMAGE      STATUS                   PORTS
microservice-app-1       app        Up 30 seconds (healthy)  0.0.0.0:3000->3000/tcp

Endpoints

$ curl http://localhost:3000/health
{
  "status": "ok",
  "service": "dockerized-node-microservice",
  "version": "1.0.0",
  "uptime": 42,
  "timestamp": "2026-05-22T01:06:30.000Z"
}

$ curl http://localhost:3000/ready
{
  "status": "ready"
}

$ curl http://localhost:3000/unknown
{
  "statusCode": 404,
  "error": "Not Found",
  "message": "Route GET /unknown not found",
  "requestId": "921238a5-8a50-44a6-8add-502a2bcbf256"
}

Security headers on every response

$ curl -I http://localhost:3000/health

HTTP/1.1 200 OK
x-content-type-options: nosniff
x-frame-options: DENY
x-xss-protection: 0
referrer-policy: no-referrer
permissions-policy: camera=(), microphone=(), geolocation=()
x-request-id: b80d9e9d-5829-46d9-96f6-adf29139bc77

Structured startup logs (make dev)

[2026-05-22 06:06:27] INFO: Server listening at http://0.0.0.0:3000
[2026-05-22 06:06:27] INFO: Service ready
    service: "dockerized-node-microservice"
    version: "1.0.0"
    env: "development"

Graceful shutdown (Ctrl+C or make down)

[2026-05-22 06:06:45] INFO: Shutdown signal received — draining in-flight requests
    signal: "SIGTERM"
[2026-05-22 06:06:45] INFO: Server closed cleanly

Terminal recording — see scripts/record-demo.sh for a one-command asciinema demo once asciinema is installed (pip install asciinema).


Project Goals

This repository is not a CRUD tutorial. It exists to demonstrate the operational concerns that separate a production microservice from a local prototype:

  • How a service signals its own health to an orchestrator
  • How it handles shutdown without dropping in-flight requests
  • How every log line carries a traceable request identifier
  • How the container image is built securely, in layers, for minimal attack surface
  • How configuration is typed, validated, and fail-fast from day one

The domain is intentionally lightweight — the engineering is the point.


Operational Readiness at a Glance

Concern Implementation Why It Matters
Liveness probe GET /health — always 200 if alive Orchestrators restart crashed containers
Readiness probe GET /ready — 503 during startup/shutdown Load balancers stop routing before drain begins
Graceful shutdown SIGTERM → drain → timeout guard → exit Rolling deploys don't drop in-flight requests
Structured logging pino JSON + requestId on every line Logs are machine-parseable and correlatable
Request timeout 408 if handler stalls beyond threshold Hung connections don't exhaust the thread pool
Security headers X-Content-Type-Options, X-Frame-Options, etc. Baseline HTTP security without a full WAF
Schema validation AJV with field-level error formatting Callers get actionable errors, not schema internals
Container security Multi-stage build + non-root user Production layers contain zero dev tooling

Architecture

┌──────────────────────────────────────────────────────────────────────┐
│                         Docker Container                              │
│                                                                      │
│   ┌──────────────────────────────────────────────────────────────┐   │
│   │                    Fastify  :3000                             │   │
│   │                                                              │   │
│   │   Plugin pipeline (applied globally, in registration order)  │   │
│   │   ┌───────────┐  ┌─────────────┐  ┌────────────────────┐   │   │
│   │   │   cors    │  │ req-timeout │  │   security-headers  │   │   │
│   │   └───────────┘  └─────────────┘  └────────────────────┘   │   │
│   │   ┌───────────┐  ┌─────────────┐                           │   │
│   │   │req-logger │  │ err-handler │                           │   │
│   │   └───────────┘  └─────────────┘                           │   │
│   │                                                              │   │
│   │   Routes                                                     │   │
│   │   ┌──────────┐   ┌──────────┐   ┌────────────────────┐    │   │
│   │   │ /health  │   │  /ready  │   │   /api/v1/*         │    │   │
│   │   └──────────┘   └──────────┘   └────────────────────┘    │   │
│   └──────────────────────────────────────────────────────────────┘   │
└──────────────────────────────────────────────────────────────────────┘

Request lifecycle

  Inbound request
       │
       ├── CORS policy check
       ├── Request timeout timer starts        ← REQUEST_TIMEOUT_MS
       │
       ├── Route handler executes
       │
       └── onSend hooks fire (every response)
               ├── Security headers applied
               ├── X-Request-Id header set      ← UUID, correlates logs ↔ response
               └── Timeout timer cleared

Shutdown sequence

  SIGTERM or SIGINT received
       │
       ├── setReady(false)                      ← /ready returns 503 immediately
       │                                           load balancer stops routing
       ├── app.close()                          ← Fastify drains in-flight connections
       │
       ├── Timeout guard fires if drain stalls  ← SHUTDOWN_TIMEOUT_MS (default 10s)
       │   └── process.exit(1)                 ← force exit, never hang a rolling deploy
       │
       └── process.exit(0)                      ← clean exit after successful drain

Getting Started

Prerequisites

Tool Version Install
Docker Desktop Latest docker.com
Node.js 20 LTS nodejs.org
GNU Make Any winget install GnuWin32.Make / brew install make

Docker (recommended)

git clone https://github.com/ZohaibAkram/dockerized-node-microservice
cd dockerized-node-microservice

cp .env.example .env
make up

Service is available at http://localhost:3000. The container reports (healthy) once the Docker HEALTHCHECK probe confirms /health is responding.

Local development

make install          # npm install
cp .env.example .env  # LOG_PRETTY=true is already set for readable output
make dev              # node --watch with pino-pretty

Available commands

make help
Command Description
make install Install dependencies
make dev Run locally with hot-reload
make build Build production Docker image
make up Start service in Docker (detached)
make down Stop and remove containers
make logs Tail application logs
make shell Open shell inside the container
make health Call /health and print response
make ready Call /ready and print response
make clean Remove containers, volumes, dangling images

API Reference

GET /health

Liveness check. Returns 200 as long as the process is running. Used by Docker HEALTHCHECK and Kubernetes liveness probes. This endpoint never intentionally fails.

curl http://localhost:3000/health
{
  "status": "ok",
  "service": "dockerized-node-microservice",
  "version": "1.0.0",
  "uptime": 42,
  "timestamp": "2025-01-15T10:00:00.000Z"
}

GET /ready

Readiness check. Returns 503 during startup and shutdown; 200 when fully initialized. Point Kubernetes readiness probes and load balancer health checks at this endpoint — not /health.

curl http://localhost:3000/ready
{ "status": "ready" }

Returns 503 with { "status": "not ready" } during startup and drain windows.


Error responses

All errors return a consistent JSON shape. requestId links the error body to the corresponding log line.

{
  "statusCode": 404,
  "error": "Not Found",
  "message": "Route GET /unknown not found",
  "requestId": "3fa85f64-5717-4562-b3fc-2c963f66afa6"
}

Validation errors include a details array with field-level feedback:

{
  "statusCode": 400,
  "error": "Bad Request",
  "message": "body must have required property 'email'",
  "requestId": "...",
  "details": [
    { "field": "email", "message": "must have required property 'email'" }
  ]
}

Project Structure

├── src/
│   ├── config/
│   │   └── index.js               # Typed env config — optional() vs required(),
│   │                              #   fail-fast on startup if required vars are absent
│   ├── plugins/                   # Fastify plugins — scoped globally via fastify-plugin
│   │   ├── error-handler.js       # Consistent error shape, 404 handler, 500s masked in prod
│   │   ├── request-logger.js      # X-Request-Id response header (log correlation)
│   │   ├── request-timeout.js     # 408 if handler exceeds REQUEST_TIMEOUT_MS
│   │   └── security-headers.js    # Baseline security headers on every response
│   ├── routes/
│   │   ├── health.js              # GET /health  — liveness
│   │   ├── ready.js               # GET /ready   — readiness gate (toggled by server.js)
│   │   └── api/v1/                # Versioned domain routes
│   ├── app.js                     # Fastify factory — plugins + routes, no side-effects on import
│   └── server.js                  # listen(), SIGTERM/SIGINT handling, process error guards
├── scripts/
│   └── healthcheck.sh             # Docker HEALTHCHECK probe — uses 127.0.0.1, not localhost
├── Dockerfile                     # 3 stages: deps (prod-only) → dev (watch) → production
├── docker-compose.yml             # Production-style service definition
├── docker-compose.override.yml    # Dev overrides — auto-merged locally, excluded from CI
├── Makefile                       # Developer commands
└── .env.example                   # All supported variables, documented inline

Configuration

Copy .env.example to .env before first run. No variables are required to start — all have safe defaults for development.

Variable Default Description
PORT 3000 HTTP listen port
HOST 0.0.0.0 Bind address (127.0.0.1 to restrict to localhost)
NODE_ENV development development or production (masks 500 bodies in prod)
LOG_LEVEL info trace · debug · info · warn · error · fatal
LOG_PRETTY false Enable pino-pretty — local dev only, never in containers
SERVICE_NAME dockerized-node-microservice Surfaced in /health response
SERVICE_VERSION 1.0.0 Surfaced in /health response
CORS_ORIGIN * Restrict in production: https://yourdomain.com
SHUTDOWN_TIMEOUT_MS 10000 Force-exits if drain stalls beyond this threshold
REQUEST_TIMEOUT_MS 30000 Returns 408 if a handler hasn't responded in time

Design Decisions

Fastify over Express Schema validation, pino integration, and request ID generation are built-in primitives. The hook/plugin model makes the request lifecycle explicit — each concern lives in its own file, registered in a clear order, rather than being buried in middleware chains.

Separate liveness and readiness contracts /health answers "is the process alive?" and never fails. /ready answers "is this instance ready for traffic?" and returns 503 during startup and drain. Conflating them is a common mistake that causes traffic to arrive during rolling restarts.

Readiness toggled before drain begins setReady(false) is called before app.close(). This matters because a load balancer checking /ready on its normal interval might route a request after SIGTERM is received but before the connection drain starts. Toggling it off first closes that window.

Shutdown timeout guard with timer.unref() app.close() drains connections, but a stalled client can block it indefinitely. The timeout guard force-exits after SHUTDOWN_TIMEOUT_MS. timer.unref() ensures the timer itself doesn't prevent the event loop from exiting if the drain completes first.

Field-level validation errors AJV's raw error objects expose schema paths like instancePath: "/user/email". The formatter converts these to { field: "user.email", message: "..." } — actionable for callers without leaking schema internals.

removeAdditional: true in AJV Unknown fields are stripped before they reach any handler. This enforces the API contract at the framework level without requiring manual object pruning in every route.

Multi-stage Dockerfile Stage deps runs npm ci --only=production. Only its node_modules output is copied into the final image. Dev tooling, test runners, and source maps never enter the production layer. Stage dev uses node --watch so the container hot-reloads without nodemon.

127.0.0.1 in HEALTHCHECK, not localhost Alpine Linux resolves localhost to ::1 (IPv6). Node.js binds to 0.0.0.0 (IPv4) by default. Using localhost in the probe causes every health check to fail silently with "connection refused" — a non-obvious production footgun.


Stack

Layer Technology Notes
Runtime Node.js 24 LTS ES modules ("type": "module")
Framework Fastify 5 Plugin-based, schema-first
Logger pino Structured JSON, low overhead
Validation AJV (bundled) JSON Schema, field-level errors
Container Docker — Alpine Multi-stage, non-root user
Orchestration Docker Compose v2 Dev override pattern
Developer tooling GNU Make Self-documenting via make help

Roadmap

Planned additions across future phases of this repository:

Phase Feature
Next GET /api/v1/items — sample domain routes demonstrating route modularization
Near OpenAPI / Swagger documentation via @fastify/swagger
Near GitHub Actions CI — lint, audit, Docker build on every PR
✅ Done Upgraded to Fastify v5 + Node 24 LTS — all CVEs resolved
Later Prometheus metrics endpoint (/metrics)
Later OpenTelemetry tracing integration
Later Kubernetes manifests — Deployment, Service, HPA, readiness/liveness probes

Suggested Screenshots / Recordings

To complete the visual presentation of this repository, consider capturing:

Asset Tool What to show
Startup logs Terminal screenshot pino-pretty colorized output on make dev
Docker health Terminal screenshot docker compose ps showing (healthy)
Shutdown sequence Terminal recording SIGTERM log lines in order
/health response Terminal screenshot curl output with jq formatting
Security headers Terminal screenshot curl -I output showing all headers

Recommended recording tool: Asciinema — produces lightweight terminal recordings that embed directly in GitHub READMEs via a badge or linked preview.


License

MIT — see LICENSE.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages