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

推荐订阅源

云风的 BLOG
云风的 BLOG
雷峰网
雷峰网
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Cyberwarzone
Cyberwarzone
Hacker News: Ask HN
Hacker News: Ask HN
C
Cisco Blogs
NISL@THU
NISL@THU
C
Cyber Attacks, Cyber Crime and Cyber Security
L
LINUX DO - 热门话题
A
Arctic Wolf
Simon Willison's Weblog
Simon Willison's Weblog
S
Schneier on Security
P
Palo Alto Networks Blog
Know Your Adversary
Know Your Adversary
C
Cybersecurity and Infrastructure Security Agency CISA
G
GRAHAM CLULEY
K
Kaspersky official blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
V
Vulnerabilities – Threatpost
小众软件
小众软件
博客园 - 司徒正美
腾讯CDC
AWS News Blog
AWS News Blog
Last Week in AI
Last Week in AI
T
Tenable Blog
I
Intezer
博客园_首页
IT之家
IT之家
阮一峰的网络日志
阮一峰的网络日志
AI
AI
V
V2EX
Hacker News - Newest:
Hacker News - Newest: "LLM"
博客园 - 三生石上(FineUI控件)
W
WeLiveSecurity
D
Docker
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Security Latest
Security Latest
F
Fortinet All Blogs
S
Secure Thoughts
T
Troy Hunt's Blog
T
The Blog of Author Tim Ferriss
Recorded Future
Recorded Future
M
MIT News - Artificial intelligence
GbyAI
GbyAI
Microsoft Security Blog
Microsoft Security Blog
L
LINUX DO - 最新话题
B
Blog RSS Feed
U
Unit 42
TaoSecurity Blog
TaoSecurity Blog

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 Compose Local Dev Environments: Beyond docker-compose up
The Practica · 2026-06-04 · via The Practical Developer

Every team I have worked with starts with the same Docker Compose file. It is three services: a web app, a Postgres container, a Redis container. docker compose up works perfectly on the author’s machine. Six weeks later, a new developer clones the repo and spends two hours debugging why the app container crashes at startup because Postgres is not ready yet. Another developer on a Mac sees different file permissions inside the volume than on Linux. Someone’s node_modules is mounted from the host and links to system libraries that do not exist in the container.

“Works on my machine” is not a joke. It is the predictable consequence of treating local dev setups as one-off scripts rather than infrastructure. The fix is to apply the same rigor to compose.yaml that you apply to your production deployment: explicit health checks, dependency ordering, environment validation, and a startup sequence that does not rely on luck.

This post is the pattern I use for production-grade local dev environments. Every technique here has survived teams of five to fifteen engineers, multiple operating systems, and the chaos of npm install across platforms.

The problem with the naive compose file

The three-service setup that everyone starts with looks like this:

# compose.yaml -- the naive version that works for one person
services:
  app:
    build: .
    ports:
      - "3000:3000"
    depends_on:
      - postgres
      - redis
    environment:
      DATABASE_URL: postgres://user:pass@postgres:5432/devdb
      REDIS_URL: redis://redis:6379

  postgres:
    image: postgres:16-alpine
    environment:
      POSTGRES_USER: user
      POSTGRES_PASSWORD: pass
      POSTGRES_DB: devdb
    ports:
      - "5432:5432"

  redis:
    image: redis:7-alpine
    ports:
      - "6379:6379"

This file has three problems.

depends_on does not wait for readiness. It only waits for the container to start. Postgres may start its process, but it will reject connections for several seconds while it recovers from a WAL checkpoint. The app container crashes, the restart policy kicks in, and eventually it works, but the error output scares every new developer.

Ports are exposed on the host for every service. If two projects both use port 5432, they collide. Developers end up editing the compose file locally and never committing the changes. Then the docker-compose.yml in the repo has a stale workaround for someone else’s machine.

No initialization logic. When was the last time you dropped into a fresh Postgres container and it had the extensions, the role grants, and the test data you needed? Never. You run a migration script manually, or you rely on someone else’s database dump from three months ago.

Pattern 1: Health checks that actually gate startup

Replace depends_on with depends_on + condition: service_healthy. This is the single biggest quality-of-life improvement for a team compose file.

services:
  app:
    build: .
    ports:
      - "3000:3000"
    depends_on:
      postgres:
        condition: service_healthy
      redis:
        condition: service_healthy
    environment:
      DATABASE_URL: postgres://user:pass@postgres:5432/devdb
      REDIS_URL: redis://redis:6379

  postgres:
    image: postgres:16-alpine
    environment:
      POSTGRES_USER: user
      POSTGRES_PASSWORD: pass
      POSTGRES_DB: devdb
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U user -d devdb"]
      interval: 2s
      timeout: 5s
      retries: 10
      start_period: 10s

  redis:
    image: redis:7-alpine
    healthcheck:
      test: ["CMD", "redis-cli", "--raw", "incr", "ping"]
      interval: 2s
      timeout: 5s
      retries: 5

The start_period is key. It gives the container time to boot before health checks even start counting. Without it, a cold-start Postgres fails the first three checks (because it is still recovering) and the container gets killed before it ever becomes healthy.

Test the healthcheck yourself before relying on it:

docker compose exec postgres pg_isready -U user -d devdb
# postgres:5432 - accepting connections

If that returns anything other than a zero exit code, the healthcheck will never pass and docker compose up will hang forever.

Pattern 2: Named volumes, not bind mounts for databases

The second most common cause of “my local dev is broken” is a Postgres container whose data directory is a bind-mounted host folder. On Linux, the PostgreSQL UID inside the container (typically 999) maps to a different user on the host. The container cannot write to the bind mount, or it writes files that are owned by UID 999 and the host user cannot delete them. On macOS, VirtioFS or gRPC FUSE handles the mapping differently, so the data survives, but performance is dismal.

Use named volumes for anything that does not need live editing.

services:
  postgres:
    image: postgres:16-alpine
    volumes:
      - pgdata:/var/lib/postgresql/data
      - ./init-scripts:/docker-entrypoint-initdb.d:ro
    # ... healthcheck, env, etc.

  redis:
    image: redis:7-alpine
    volumes:
      - redisdata:/data

volumes:
  pgdata:
  redisdata:

The init scripts directory (./init-scripts) is a bind mount, and that is fine. It is read-only (:ro) and contains SQL files the container runs once on first start. Everything else lives in Docker-managed volumes.

Create init-scripts/01-extensions.sql:

CREATE EXTENSION IF NOT EXISTS pgcrypto;
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
CREATE EXTENSION IF NOT EXISTS hstore;

And init-scripts/02-dev-user.sql:

-- Create a read-only user for any tool that should not mutate data
DO $$
BEGIN
  IF NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = 'readonly') THEN
    CREATE ROLE readonly WITH LOGIN PASSWORD 'readonly' NOSUPERUSER;
  END IF;
END
$$;
GRANT CONNECT ON DATABASE devdb TO readonly;
GRANT USAGE ON SCHEMA public TO readonly;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO readonly;

Now every developer on the team gets the same extensions and roles on first docker compose up. No manual steps, no “can you run this SQL for me.”

Pattern 3: Internal DNS and the port collision fix

Exposing every service port on localhost is a recipe for collision. The whole point of Docker Compose is that services discover each other by service name over the internal network. Your application already connects to postgres:5432 and redis:6379. You do not need localhost:5432 for anything in production.

Remove the ports block from every service that does not need direct host access. For Postgres, Redis, Kafka, and most infrastructure services, the host does not need to reach them. Your app runs in a container and connects via the internal network.

services:
  postgres:
    image: postgres:16-alpine
    # No ports section. The app connects to postgres:5432 internally.
    expose:
      - "5432"
    # expose is documentation-only. It does not publish the port.

The expose key is optional (Compose creates an internal DNS entry regardless), but it is useful documentation for anyone reading the file.

Keep ports only on the services you need to reach from your host machine:

services:
  app:
    ports:
      - "3000:3000"
    # The API is on localhost:3000. Everything else stays internal.

  adminer:  # optional DB browser
    image: adminer
    ports:
      - "8080:8080"
    profiles: ["tools"]

If you genuinely need to reach Postgres from a local GUI (DataGrip, TablePlus), use a temporary port mapping when you launch it:

docker compose run --rm -p 5433:5432 postgres

Or define a separate profile service (see Pattern 5).

Pattern 4: The entrypoint that validates the environment

The app container should crash fast and clearly when something is misconfigured. A startup script that checks required environment variables and service connectivity saves thirty minutes of head-scratching per developer per week.

Create docker-entrypoint.sh:

#!/bin/sh
set -e

# Check required env vars
required="DATABASE_URL REDIS_URL"
for var in $required; do
  eval "value=\$$var"
  if [ -z "$value" ]; then
    echo "FATAL: $var is not set"
    exit 1
  fi
done

# Check database connectivity (with retry)
echo "Waiting for database..."
for i in $(seq 1 30); do
  if pg_isready -d "$DATABASE_URL" > /dev/null 2>&1; then
    echo "Database is ready"
    break
  fi
  if [ "$i" -eq 30 ]; then
    echo "FATAL: Database not reachable after 30 seconds"
    exit 1
  fi
  sleep 1
done

# Run migrations
echo "Running migrations..."
if ! npx prisma migrate deploy 2>/dev/null && \
   ! npx sequelize db:migrate 2>/dev/null && \
   ! npx knex migrate:latest 2>/dev/null; then
  # None of the common migration tools detected. If you use something else,
  # handle it here or skip. The warning is not a fatal error.
  echo "WARN: No migration tool detected, skipping"
fi

# Seed if the database is empty
echo "Checking if seed data is needed..."
# Your seed logic here

exec "$@"

Build this into your Dockerfile:

FROM node:20-alpine

# Install postgres client for pg_isready in the entrypoint
RUN apk add --no-cache postgresql16-client

WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
COPY docker-entrypoint.sh /usr/local/bin/
RUN chmod +x /usr/local/bin/docker-entrypoint.sh

ENTRYPOINT ["docker-entrypoint.sh"]
CMD ["node", "dist/server.js"]

The entrypoint serves as the gatekeeper. If the database is unreachable, the container logs a clear message and exits. The Compose file’s restart: unless-stopped handles the retry, but now the developer sees “Database not reachable after 30 seconds” instead of a cryptic connection refused stack trace.

Pattern 5: Profiles for optional services

Not every developer needs every service every time. If your stack includes a message queue, a separate search index, a mail server, and a monitoring stack, forcing everyone to run all twelve containers is wasteful. Docker Compose profiles let you tag services so they only start when explicitly requested.

services:
  # Core services -- always started
  app:
    # ...
  postgres:
    # ...
  redis:
    # ...

  # Optional services -- started with --profile tools
  mailpit:
    image: axllent/mailpit
    ports:
      - "8025:8025"
    profiles: ["tools"]

  pgadmin:
    image: dpage/pgadmin4
    ports:
      - "5050:80"
    environment:
      PGADMIN_DEFAULT_EMAIL: dev@localhost
      PGADMIN_DEFAULT_PASSWORD: dev
    profiles: ["tools"]

  # Service for full-stack local testing
  search:
    image: meilisearch:latest
    ports:
      - "7700:7700"
    profiles: ["full"]

Start with only core services:

docker compose up -d
# Starts app, postgres, redis

Add the tools profile when you need a database browser:

docker compose --profile tools up -d

Spin up everything for a full integration test:

docker compose --profile full up -d

The profile system keeps the default startup fast and the full environment available on demand. Document the profiles in a Makefile or a justfile so developers do not have to remember the flags:

.PHONY: up up-tools up-full

up:
	docker compose up -d

up-tools:
	docker compose --profile tools up -d

up-full:
	docker compose --profile full up -d

down:
	docker compose down

reset:
	docker compose down -v
	docker compose up -d

The down -v target (reset) is another quality-of-life win. When a developer’s database state is corrupted from an aborted migration, running make reset nukes the volumes and starts fresh. Name this something obvious and put it in the README.

Pattern 6: Development overrides with compose.override.yaml

Docker Compose merges multiple compose files. The default is compose.yaml + compose.override.yaml if it exists. Use the override file for developer-local changes that should never be committed.

The production-safe compose.yaml should contain:

  • The service definitions
  • Image references or build contexts
  • Health checks
  • Named volume declarations
  • Profile tags

The compose.override.yaml (gitignored) contains:

  • Port mappings to localhost
  • Volume mounts for hot-reloading source code
  • Debugger flags and exposed ports
  • Local environment variable overrides

Example override:

# compose.override.yaml (gitignored)
services:
  app:
    ports:
      - "3000:3000"
      - "9229:9229"  # Node inspector for --inspect
    volumes:
      - .:/app
      - /app/node_modules  # anonymous volume masks the host node_modules
    command: npx nodemon --inspect=0.0.0.0 dist/server.js
    environment:
      NODE_ENV: development
      LOG_LEVEL: debug

  postgres:
    ports:
      - "5432:5432"

Add compose.override.yaml to .gitignore:

compose.override.yaml
.env.local

The override file makes hot reloading work (the source code is bind-mounted into the container) while keeping the base compose file clean enough to deploy to a staging environment. The command override switches from the production CMD to nodemon. The NODE_ENV override enables verbose logging.

Pattern 7: Environment file hierarchy

Environment variables for local dev should come from files, not from random .env exports in a shell rc file. Docker Compose supports multiple env files per service.

services:
  app:
    env_file:
      - .env
      - .env.local
  • .env is committed. It contains defaults that work for everyone: database URLs, API keys for test services, port numbers.
  • .env.local is gitignored. It contains personal overrides: different ports, local-only feature flags, personal API tokens for third-party services.

Both files merge, with .env.local taking precedence. A developer can set LOG_LEVEL=debug in their .env.local without accidentally committing it.

When to break the pattern

The patterns above cover most teams, but there are exceptions.

Monorepo with multiple applications. Do not put all services in one compose file. Each application should have its own compose file, and a root-level compose file uses the include keyword (Compose v2.20+) to compose them together:

include:
  - apps/api/docker-compose.yml
  - apps/web/docker-compose.yml
  - packages/shared/docker-compose.yml

Windows developers. File permission semantics differ significantly. Use WSL2 and run Docker Desktop from WSL2. Bind mounts with hot reloading are slower on Windows, so consider adding a WATCH_MODE=poll option to your file watcher. Avoid USER directives in the Dockerfile that set a specific UID (most Node images handle this fine without explicit UIDs).

CI/CD pipelines. Your CI does not need hot reloading, profiles, or port mappings. Create a compose.ci.yml file that strips all development-only configuration:

# compose.ci.yml
include:
  - compose.yml

services:
  app:
    ports: []  # no host ports needed in CI
    command: npx vitest run --reporter=junit

Run it with docker compose -f compose.yml -f compose.ci.yml up --exit-code-from app.

The takeaway

A good local dev environment is invisible. It starts fast, it does not need manual setup steps, and every developer on the team gets the same result. The difference between a fragile dev setup and a reliable one is not the container runtime. It is applying three hours of upfront work: health checks that actually prevent startup until dependencies are ready, named volumes that survive operating system differences, an entrypoint that validates the environment loudly, profile-based service selection, and an override file that keeps personal customizations out of version control.

Start with make reset in your README. If a new developer can clone the repo, run make up, and have a working application without asking for help, you have won.


A note from Yojji

The discipline of treating local development environments as infrastructure (health checks, initialization scripts, consistent entrypoints, documented reset procedures) is the same discipline that keeps production deployments reliable. It is unglamorous work that becomes visible only when it is absent, and it is the kind of foundation Yojji’s teams build for every client project from day one.

Yojji is an international custom software development company founded in 2016, with teams across Europe, the US, and the UK. They specialize in the JavaScript ecosystem (React, Node.js, TypeScript), cloud platforms (AWS, Azure, GCP), and full-cycle product engineering, including the developer experience investments that determine how fast a team can ship.