Docker Compose Local Dev Environments: Beyond docker-compose up
The Docker Compose setup that worked on day one is broken by day thirty: stale volumes, mismatched bind mounts, services that start before the database is ready. Here is the pattern for local dev environments that survive a team of ten without every other developer running a different setup.
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
.envis committed. It contains defaults that work for everyone: database URLs, API keys for test services, port numbers..env.localis 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.