惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园 - 三生石上(FineUI控件)
WordPress大学
WordPress大学
阮一峰的网络日志
阮一峰的网络日志
大猫的无限游戏
大猫的无限游戏
T
Tailwind CSS Blog
S
SegmentFault 最新的问题
The Hacker News
The Hacker News
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
小众软件
小众软件
Google DeepMind News
Google DeepMind News
腾讯CDC
博客园 - 司徒正美
Cisco Talos Blog
Cisco Talos Blog
Apple Machine Learning Research
Apple Machine Learning Research
The Cloudflare Blog
博客园 - 聂微东
博客园 - 【当耐特】
Project Zero
Project Zero
有赞技术团队
有赞技术团队
量子位
P
Privacy International News Feed
博客园_首页
酷 壳 – CoolShell
酷 壳 – CoolShell
J
Java Code Geeks
IT之家
IT之家
SecWiki News
SecWiki News
H
Hacker News: Front Page
PCI Perspectives
PCI Perspectives
L
Lohrmann on Cybersecurity
宝玉的分享
宝玉的分享
Cloudbric
Cloudbric
雷峰网
雷峰网
月光博客
月光博客
Cyberwarzone
Cyberwarzone
S
Securelist
Hugging Face - Blog
Hugging Face - Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
博客园 - Franky
T
Threat Research - Cisco Blogs
罗磊的独立博客
Forbes - Security
Forbes - Security
NISL@THU
NISL@THU
N
News and Events Feed by Topic
T
Troy Hunt's Blog
Jina AI
Jina AI
Hacker News - Newest:
Hacker News - Newest: "LLM"
C
Cyber Attacks, Cyber Crime and Cyber Security
The Last Watchdog
The Last Watchdog
V2EX - 技术
V2EX - 技术

The Practical Developer

The Libuv Thread Pool Trap: Why Node.js Async APIs Stall Under Load Postgres Covering Indexes with INCLUDE: Eliminate Heap Fetches on Read-Heavy Workloads Postgres DISTINCT ON: The Fastest Way to Get the Latest Row Per Group Postgres Transaction Isolation: The Anomalies Your App Actually Faces in Production Linux TCP Tuning for Node.js Microservices: The Kernel Settings That Stop Silent Connection Drops Under Load Postgres HOT Updates and Fillfactor: Why Not All Writes Are Created Equal Database Connection Pool Leaks: Finding the Promise That Never Returns Its Seat Linux OOM Killer in Production: Why Your Node.js Containers Die Without a Stack Trace Postgres Materialized Views: Refresh Strategies That Do Not Lock Your Dashboards API Dependency Health Checks: Why /health Is Not Enough Authorization with Zanzibar Tuples: How Google Manages Permissions and How To Build the Same Check in Node.js Postgres Advisory Locks: The 20-Character Primitive That Replaces Redis for Coordination Dead Letter Queues: The Message Queue Pattern That Saves You at 2 a.m. File Descriptor Exhaustion: The Kernel Limit That Silently Drops Node.js Connections Graceful Degradation: The Pattern That Turns Total Outages into Partial Success PostgreSQL Full-Text Search: Dropping Elasticsearch for 90% of Use Cases S3 Presigned Multipart Uploads: Stop Your API Server from Being a File Upload Bottleneck MessagePack vs JSON: The Binary Serialization Switch That Cut Our Internal RPC Overhead by 40% DNS Caching in Node.js: The Silent Cause of Production Latency Spikes Reliable Cron Jobs: The Pattern That Stops Double Runs, Missed Executions, And The 2 AM Page GraphQL Query Complexity: Stop the OOM Query Before It Reaches Your Resolver Node.js Event Loop Lag: The Hidden Metric Behind Random Latency Spikes API Request Validation with Zod: The Schema That Catches Bad Input Before It Corrupts Your Database Load Shedding in Node.js: How to Reject Traffic Before You Drown Request Hedging: Cut Tail Latency In Half Without Overprovisioning Git Bisect: The Automated Binary Search That Finds Breaking Commits in Minutes Node.js Garbage Collection Tuning: Stop Letting V8 Pause Your Event Loop Node.js Server Timeouts: The Settings That Stop Slow Clients from Holding Sockets Hostage Postgres BRIN Indexes: The Time-Series Secret That Shrinks Indexes by 99% Event Sourcing with PostgreSQL: The Pragmatic 80% Solution Node.js Cluster Mode: Scaling the Event Loop Across CPU Cores Postgres Partial Indexes: Stopping Soft Deletes from Ruining Your Query Performance Request Coalescing with the Singleflight Pattern: Stop Drowning Your Database on Every Cache Miss The Bulkhead Pattern: Why One Slow Endpoint Should Not Drown Your Whole Service Node.js AsyncLocalStorage: End-to-End Request Context Without the Propagation Hell Postgres Deadlocks: Logging the Victim, Reproducing the Race, and Fixing the Lock Order Your Node.js HTTP Client Is the Bottleneck: Connection Pool Tuning That Works Optimistic Locking in Postgres: Stop Losing Data to Race Conditions Postgres Read Replicas: Stop Serving Stale Data to Your Users Cursor Pagination: Why Offset Queries Explode at Scale and How to Fix Them Node.js Worker Threads: 60 Lines That Stop a CSV Upload from Timing Out Every Other Request Reliable Webhook Delivery: Architecture for Outbound HTTP You Can Trust Request Timeouts and Deadline Propagation: Stop the Chain of Slowness Advanced Security Practices in Node.js Graceful Shutdown in Node.js: The 40 Lines That Stop 502s During Deploys Finding Node.js Memory Leaks with Heap Snapshots Idempotency Keys in 30 Lines: Stop Your Webhook From Charging Customers Twice Backpressure In Node.js: The Fix For Slow-Motion Queue Meltdowns Retries Done Right: Jitter, Budgets, and the Stampede You Did Not See Coming The Cache Stampede: Why Your "Just Add Redis" Layer Crashes Postgres at 3 a.m. Postgres SKIP LOCKED: An 80-Line Job Queue You Can Run Without Redis Stop Doing Work Nobody Wants: AbortController in Node.js, Done Right The N+1 Query Problem: We Found 23 In One Codebase And Killed Every One I Tried 5 AI Coding Tools for a Month. Here Is What I Actually Use CI/CD From Zero to Production in 30 Minutes With GitHub Actions Node.js vs Bun vs Deno: Which Runtime Should You Pick in 2025? Kubernetes Resource Requests And Limits: The Numbers That Decide If Your Cluster Is Stable The Three Pillars of Observability Are A Myth: What Actually Matters In Production pnpm Vs npm Vs yarn Vs Bun For Monorepos: Which One Earns The Migration In 2024 JSONB Indexing In Postgres: GIN Vs Expression Indexes, And When Each Is The Right Choice A Code Review Checklist That Ends The Same Three Arguments Every Sprint gRPC Vs REST In 2024: When The Switch Pays For Itself React Suspense For Data Fetching: The Pattern That Replaces Half Your Loading State Code The Five-Stage Rollout: How To Ship A Risky Change Without Holding Your Breath GitHub Actions In A Monorepo: Caching, Path Filters, And Secret Boundaries That Actually Work The Blameless Postmortem That Actually Improves Things: A Template And Six Hard-Won Rules Recursive CTEs In Postgres: How To Query A Tree Without N Round Trips Node.js Streams: When They Actually Help, And When They Just Add Complexity Playwright Vs Cypress In 2024: The Honest Comparison Of Which One Earns The Test Time React Server Components: The Mental Model That Makes The "use client" Boundary Obvious Pod Disruption Budgets: The K8s Object That Keeps Your Service Up During Cluster Maintenance Postgres LISTEN/NOTIFY: The Pub/Sub You Already Have And Are Not Using Chaos Engineering Starter Kit: The Five Drills That Don't Need Netflix-Scale Spec-Driven API Development With OpenAPI: How To Stop Drifting From Your Docs Kubernetes Autoscaling Beyond CPU: The Custom-Metric HPA Pattern That Actually Works Postgres Partitioning For Time-Series: The Boring Setup That Saves Your Database Distributed Locks With Redis: An Honest Look At Redlock And When You Don't Need It HTTP/2 vs HTTP/3: What Actually Changes For Your App, And What Doesn't Image Optimization For The Web In 2023: srcset, AVIF, And The Lighthouse Score You Actually Want Kafka vs RabbitMQ: A Decision Tree That Doesn't Hate You UUID vs Bigint Primary Keys In Postgres: The Index Math That Decides For You Flame Graphs: How To Find The Slow Function In 30 Seconds Without Profiling Theatre Postgres Streaming Vs. Logical Replication: Which One Solves Your Actual Problem ESLint Rules That Earn Their Keep: The Twelve I Enable On Every Project Pre-Commit Hooks That Pay For Themselves: Husky, lint-staged, And The Five Rules That Stick Zero-Downtime Database Migrations: The Six-Step Pattern That Rules Them All Circuit Breakers In Node.js: 50 Lines That Stop A Failing Dependency From Taking Down Your Service Postgres VACUUM Is Not Magic: How Your Hot Table Bloats To 80GB And How To Fix It Kubernetes Liveness And Readiness Probes: The Difference That Causes Half Your Outages Rate Limiting In Production: A Token Bucket In 30 Lines Of Redis The Outbox Pattern: How To Stop Losing Events When Postgres And Kafka Disagree Load Testing With k6: The Three Scenarios That Find Real Bugs (Not Synthetic Numbers) Postgres Row-Level Security For Multi-Tenant Apps: The Pattern That Stops You From Leaking Data Rebase vs. Merge: The Team Policy That Ends The Argument Forever OpenTelemetry in Node.js: Distributed Tracing That Actually Helps During an Incident Feature Flags That Pay Rent: The 4 Flag Types And When To Delete Each ETag, Last-Modified, and the Caching Headers Most APIs Get Wrong Connection Pooling Without the Cargo Cult: pgbouncer in 100 Lines of Config JSONB Is Not a Schema: When To Reach For It in Postgres, And When To Stop Bash Strict Mode: The Three Lines That Stop Your Deploy Script From Lying To You
Docker HEALTHCHECK for Node.js: The Pattern That Stops Your Orchestrator From Routing Traffic to Broken Containers
The Practica · 2026-06-25 · via The Practical Developer

Your container boots, registers with the service mesh, and starts receiving traffic. The Node.js process is up. The health endpoint returns 200. Everything looks fine.

But the database connection pool is exhausted because a previous deployment left connections open. The event loop is running at 98% lag because a memory leak has pinned GC into a continuous cycle. The response time has gone from 12ms to 4 seconds, but the health endpoint still returns 200 because it only checks process.uptime() > 0.

This is the gap that Docker HEALTHCHECK fills, and most teams configure it wrong.

What HEALTHCHECK actually does

Docker HEALTHCHECK is a Dockerfile instruction that tells the container runtime to run a command periodically inside the container. The exit code of that command determines the container health state:

  • Exit 0: healthy
  • Exit 1: unhealthy
  • Exit 2: reserved (do not use)

Docker updates the container’s Status field in docker ps, emits a health_status event, and stops routing traffic to the container through Docker’s internal networking. Orchestrators like Docker Swarm, Nomad, and some Kubernetes CNI plugins read this status and act on it.

The three parameters that matter:

HEALTHCHECK --interval=30s --timeout=5s --retries=3 \
  CMD node /healthcheck.js
  • interval: how often Docker runs the check. Default is 30s. Faster than 10s adds noise.
  • timeout: how long Docker waits before declaring the check failed. Must be significantly shorter than interval. If your health check can take 30 seconds, it is doing too much.
  • retries: consecutive failures before marking unhealthy. Three matches the default Kubernetes behavior and absorbs transient blips.

The startup period is a fourth dimension that is conspicuously missing from the Dockerfile syntax. Kubernetes handles this with initialDelaySeconds or a startup probe. Docker has no equivalent, which means your first HEALTHCHECK can fire before your app is ready. We will fix this with a deliberate approach to state.

The one-endpoint-to-rule-them-all trap

The most common mistake is a single /health endpoint that does everything:

import express from 'express';
const app = express();

app.get('/health', async (_req, res) => {
  // Is the DB reachable?
  await db.query('SELECT 1');
  // Is Redis alive?
  await redis.ping();
  // Is the upstream API responding?
  await upstream.healthCheck();

  res.json({ status: 'ok' });
});

This endpoint has three problems when used as a Docker HEALTHCHECK target.

First, it mixes liveness and readiness into one answer. If the database is down, should Docker restart the container? No. The database blip will pass. Restarting the container makes it worse because all replicas restart in a thundering herd and you create the death spiral the K8s probes post describes. Docker HEALTHCHECK is a liveness signal: is this container so broken that it needs to be replaced? It is not a readiness signal: is this container ready to accept traffic right now?

Second, it calls external services synchronously inside the health check. The HEALTHCHECK timeout starts when Docker invokes the command. If your database call takes 6 seconds and the timeout is 5 seconds, the check always fails, even if the container is perfectly healthy.

Third, it does not distinguish startup from steady state. If the first HEALTHCHECK fires 30 seconds after container start and your app takes 45 seconds to initialize, the container is marked unhealthy, the orchestrator restarts it, and you get a crash loop before the first request arrives.

The right approach: three states, one endpoint

Build a single health endpoint that reports three states, and write a HEALTHCHECK script that interprets only the state that matters for liveness:

interface HealthState {
  status: 'starting' | 'healthy' | 'unhealthy';
  checks: {
    self: 'pass' | 'fail';
    db?: 'pass' | 'fail';
    redis?: 'pass' | 'fail';
  };
  startedAt: number;
}

The endpoint returns starting during initialization, healthy when the process is running and the event loop is responsive, and unhealthy only when the container needs replacement:

import express from 'express';
import { executionAsyncId } from 'node:async_hooks';

const app = express();
const startedAt = Date.now();
const STARTUP_GRACE_MS = 30_000;

let dbConnected = false;
let redisConnected = false;

const db = createPool({ /* ... */ });
const redis = createClient({ /* ... */ });

db.on('connect', () => { dbConnected = true; });
db.on('error', () => { dbConnected = false; });

redis.on('connect', () => { redisConnected = true; });
redis.on('end', () => { redisConnected = false; });

app.get('/health', (_req, res) => {
  const uptime = Date.now() - startedAt;

  // Phase 1: Startup
  if (uptime < STARTUP_GRACE_MS) {
    res.set('Retry-After', '5');
    return res.status(503).json({
      status: 'starting',
      checks: { self: 'pass' },
      startedAt,
    });
  }

  // Phase 2: Liveness check (self only)
  // If the event loop is so blocked we cannot respond, we never reach here.
  // The HEALTHCHECK timeout fires, Docker marks us unhealthy. Good.
  const livenessResult = { status: 'healthy', checks: { self: 'pass' }, startedAt };

  // Phase 3: Readiness info (for the orchestrator, not the HEALTHCHECK)
  // Return db/redis status so load balancers can decide, but do NOT
  // fail the HEALTHCHECK on external dependency blips.
  return res.json({
    ...livenessResult,
    checks: {
      self: 'pass',
      db: dbConnected ? 'pass' : 'fail',
      redis: redisConnected ? 'pass' : 'fail',
    },
  });
});

Now the Docker HEALTHCHECK command targets only the liveness signal:

HEALTHCHECK --interval=30s --timeout=5s --start-period=40s --retries=2 \
  CMD node /healthcheck.js

Wait - start-period is not a Docker HEALTHCHECK parameter. It is a docker run flag or a Compose field. Docker HEALTHCHECK in the Dockerfile does not support a start period. This is the fourth dimension I mentioned. Here is how to handle it.

The startup period problem and two solutions

Docker HEALTHCHECK has no --start-period in the Dockerfile syntax. If you define HEALTHCHECK in your Dockerfile, Docker starts running checks immediately. Your options:

Option A: Accept the retries budget

Set --retries high enough that the container survives startup:

HEALTHCHECK --interval=10s --timeout=5s --retries=10 \
  CMD node /healthcheck.js

If your app takes 45 seconds to start, 10 retries at a 10-second interval gives 100 seconds of tolerance. The downside: Docker does not report the container as healthy until the first successful check, so orchestration tools that wait for healthy before routing wait longer.

Option B: Use the health endpoint’s startup grace period

Build the grace period into the endpoint itself, as shown above. Return 503 with starting status during the first N seconds. Mark the HEALTHCHECK so it only considers exit codes, not the response body:

HEALTHCHECK --interval=15s --timeout=5s --retries=3 \
  CMD curl -f http://localhost:3000/health || exit 1

With curl -f, a non-2xx status causes exit 1. The endpoint returns 503 during startup. Docker sees the exit code and waits. After N seconds, the endpoint switches to 200 with the health state. The retries absorb any timing edge cases.

This is the cleaner approach because it keeps the startup logic in application code where it belongs, not in retry-count guesses.

Docker Compose extension (for local dev)

If you use Docker Compose, the healthcheck block supports a start_period:

services:
  api:
    build: .
    healthcheck:
      test: ["CMD", "node", "/healthcheck.js"]
      interval: 30s
      timeout: 5s
      retries: 3
      start_period: 40s

Compose waits 40 seconds before the first check. This is the best option for Compose-based workflows. But it does not apply to production orchestrators that read the Dockerfile HEALTHCHECK directly.

What your health check should actually measure

A health check is not a monitoring system. It is a binary switch: should this container receive traffic or not? The threshold for “not” must be high enough that you do not restart containers unnecessarily.

Measure these (liveness)

  • Process responsiveness: If the endpoint responds in time, the event loop is running. That is the strongest liveness signal. If V8 is stuck in a GC cycle that lasts longer than your HEALTHCHECK timeout, you want a restart.
  • File descriptor exhaustion: Check /proc/self/fd count against the container limit. A leaked fd leak will eventually prevent accepting new connections.
  • Memory allocation failure: A try/catch around a small Buffer.alloc that checks whether V8 can still allocate. If it fails, you are about to be OOM-killed anyway. Signal early so the orchestrator drains you gracefully.
import { readFileSync } from 'node:fs';

function checkFileDescriptors(limit = 0.9): boolean {
  const open = readFileSync('/proc/self/fd', 'utf8').split('\n').length;
  const max = readFileSync('/proc/self/limits', 'utf8')
    .match(/Max open files\s+(\d+)\s+(\d+)/);
  if (!max) return true; // Can't determine, assume pass
  const soft = parseInt(max[1], 10);
  return open / soft < limit;
}

function checkMemory(): boolean {
  try {
    Buffer.alloc(1024 * 1024); // 1MB probe allocation
    return true;
  } catch {
    return false;
  }
}

Do not measure these (or measure them as info only)

  • Database reachability: The database will have blips. That is what connection pools and retries are for. Restarting the container does not fix the database.
  • Upstream API health: You have no control over upstreams. A down upstream does not mean your container should restart.
  • Disk space: Unless your container writes to a local volume, disk space is ephemeral and will reset on restart. Alert on disk in your monitoring, do not restart containers for it.
  • Queue depth or request latency: These are performance metrics, not health signals. Restarting a container because it has a backlog guarantees the backlog never drains.

The complete HEALTHCHECK script

Here is the production-grade health check script that the Dockerfile calls:

// healthcheck.js
// This script runs inside the container as the HEALTHCHECK command.
// It exits 0 for healthy, 1 for unhealthy. That is all Docker sees.

import http from 'node:http';

const HEALTH_URL = process.env.HEALTH_URL || 'http://localhost:3000/health';
const GRACE_MS = parseInt(process.env.HEALTH_STARTUP_GRACE_MS || '30000', 10);

const req = http.get(HEALTH_URL, { timeout: 4000 }, (res) => {
  let body = '';
  res.on('data', (chunk) => (body += chunk));
  res.on('end', () => {
    try {
      const state = JSON.parse(body);
      // During startup, the endpoint may return 503.
      // Absorb that into the retries budget.
      if (state.status === 'healthy') {
        process.exit(0);
      }
      // If the process is past grace period but still unhealthy, fail.
      process.exit(1);
    } catch {
      process.exit(1);
    }
  });
});

req.on('error', () => process.exit(1));
req.on('timeout', () => { req.destroy(); process.exit(1); });

And the Dockerfile:

FROM node:22-alpine AS runner
WORKDIR /app

COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
COPY healthcheck.js .

EXPOSE 3000

HEALTHCHECK --interval=30s --timeout=5s --start-period=40s --retries=3 \
  CMD node healthcheck.js

USER node
CMD ["node", "dist/server.js"]

Note that --start-period is included in this Dockerfile despite being absent from the HEALTHCHECK specification. Here is the reality: Docker 25+ and many cloud container runtimes (ECS, Google Cloud Run, Fly.io) accept and honor it as a HEALTHCHECK extension. If your runtime ignores it, the startup grace logic in the endpoint covers you. This dual protection is the production pattern.

How Kubernetes and HEALTHCHECK interact

If you run on Kubernetes, Docker HEALTHCHECK is redundant with the kubelet’s liveness probe. The kubelet does not read Docker’s health status. It runs its own probes. Most Kubernetes deployments should skip Docker HEALTHCHECK and use kubelet probes directly.

But there are three cases where Docker HEALTHCHECK still matters on Kubernetes:

  1. Sidecars that need to know the main container’s health: A sidecar proxy (Envoy, Linkerd) can read the main container’s Docker health status to decide whether to drain connections. The kubelet probe is not visible inside the container.

  2. Non-Kubernetes orchestrators: If you deploy to Nomad, Docker Swarm, or ECS (which uses a Docker-compatible health check), HEALTHCHECK is the primary signal.

  3. Development and CI environments: Docker Compose depends_on with condition: service_healthy ensures services start in order. Without HEALTHCHECK, Compose waits for the process to start, not for it to be ready.

# docker-compose.yml
services:
  postgres:
    image: postgres:16
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U app"]
      interval: 5s
      timeout: 3s
      retries: 5
      start_period: 10s

  api:
    build: .
    depends_on:
      postgres:
        condition: service_healthy
    healthcheck:
      test: ["CMD", "node", "healthcheck.js"]
      interval: 30s
      timeout: 5s
      retries: 3
      start_period: 40s

This pattern replaces the fragile sleep 30 startup hacks that most Compose files use. The API container does not start until Postgres reports healthy. No guessing, no magic numbers.

A note from Yojji

Designing container health checks that distinguish liveness from readiness, absorb transient infrastructure blips, and fail fast on real process issues is the kind of operational discipline that separates a service that survives a database failover from one that restarts itself into a prolonged outage. Getting the HEALTHCHECK right in your Dockerfile and Compose files means every deployment, scaling event, and infrastructure incident is handled by the orchestrator instead of the on-call engineer.

Yojji is an international custom software development company founded in 2016, with offices in Europe, the US, and the UK. Their senior engineering teams specialize in the JavaScript ecosystem (React, Node.js, TypeScript), cloud platforms (AWS, Azure, GCP), Docker and Kubernetes infrastructure, and the full cycle of product delivery from discovery through DevOps and production support. Yojji builds the kind of production-hardened backend systems where health checks, graceful shutdowns, and container lifecycle management are designed in from day one, not bolted on after the first outage.