Docker › Compose

Seeding databases with initdb.d and reloading via Compose Watch

Automate idempotent PostgreSQL seed data via /docker-entrypoint-initdb.d/ and speed up local iteration with Docker Compose Watch sync and rebuild rules.

Seeding databases with initdb.d and reloading via Compose Watch

Manually inserting test accounts after every fresh clone—and rebuilding Docker images for one-line config edits—drags down local backend development. This post covers how to automate idempotent PostgreSQL seed data with /docker-entrypoint-initdb.d/ and wire live file syncing using Docker Compose Watch (develop.watch).

Tested with Docker Engine 27, Docker Compose v2.24+, PostgreSQL 17, and Spring Boot 3.4.


Why local test data breaks onboarding

When a new teammate clones a backend repository and boots the app, the first blocker is rarely the code—it’s an empty database. Without a test admin account, default roles, or base product categories, you can’t even exercise a login endpoint.

Teams usually reach for one of three workarounds, and each comes with real friction:

ApproachMain drawback
CommandLineRunner / @PostConstruct seedersPollutes production source code with local dummy logic and breaks boot whenever entity validation rules change
Manual SQL files shared in SlackGoes stale quickly and runs in inconsistent order across machines
ORM ddl-auto: create-dropWipes your working state on every restart, making stateful debugging painful
/docker-entrypoint-initdb.d/ (Infrastructure layer)Keeps seed data out of app code, versioned in Git, and initialized automatically on fresh volumes

Handling seed data at the database container layer keeps your application codebase clean while giving every developer the same baseline state.


How /docker-entrypoint-initdb.d/ works under the hood

Official PostgreSQL, MySQL, and MariaDB images all include an entrypoint hook at /docker-entrypoint-initdb.d/. When the container starts, docker-entrypoint.sh inspects PGDATA (or /var/lib/mysql) and takes one of two paths:

sequenceDiagram
    autonumber
    actor Dev as Developer
    participant Entry as docker-entrypoint.sh
    participant Volume as PGDATA Volume
    participant Engine as PostgreSQL
    Dev->>Entry: docker compose up -d
    Entry->>Volume: Check if cluster exists
    alt Empty data directory (first boot)
        Entry->>Volume: Run initdb to create cluster
        Entry->>Engine: Start temporary background server
        Entry->>Engine: Execute /docker-entrypoint-initdb.d/* in order
        Entry->>Engine: Stop temporary server
        Entry->>Engine: Start foreground server on 5432
    else Existing data found (reused volume)
        Entry->>Entry: Log "skipping initialization"
        Entry->>Engine: Start foreground server immediately
    end

The critical detail is that init scripts run only once, when the data directory is empty. If a populated named volume is already mounted, adding new .sql files to /docker-entrypoint-initdb.d/ does nothing until you reset the volume or run the script manually.

Controlling execution order

docker-entrypoint.sh executes .sql, .sql.gz, and .sh files in ascending lexicographical order. Prefix filenames with zero-padded numbers so extensions and tables exist before seed rows run:

1
2
3
4
infra/docker/initdb/
├── 01_init_extensions.sql    # Enable uuid-ossp, pg_trgm, etc.
├── 02_create_tables.sql      # DDL: base tables and indexes (if not using Flyway)
└── 03_seed_master_data.sql   # DML: test users, roles, and master configs

Note that if you already run Flyway migrations on startup, let Flyway own DDL and either place local-only seed migrations in a separate Flyway location or run 03_seed_master_data.sql after migrations finish.


Writing idempotent seed scripts and fixing sequences

During local development, you will often re-run a seed script against an existing database without wiping the whole volume. Make every seed script idempotent so running it twice leaves the database in the exact same state.

Upserts with ON CONFLICT

Use PostgreSQL’s ON CONFLICT DO UPDATE or ON CONFLICT DO NOTHING clauses:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
-- 03_seed_master_data.sql

-- 1. Seed fixed-UUID admin and developer accounts (update on rerun)
INSERT INTO users (id, email, name, role, created_at, updated_at)
VALUES
    ('11111111-1111-1111-1111-111111111111', 'admin@example.com', 'Admin User', 'ROLE_ADMIN', NOW(), NOW()),
    ('22222222-2222-2222-2222-222222222222', 'developer@example.com', 'Dev User', 'ROLE_USER', NOW(), NOW())
ON CONFLICT (email) DO UPDATE
SET
    name = EXCLUDED.name,
    role = EXCLUDED.role,
    updated_at = NOW();

-- 2. Seed default system configuration (ignore if already present)
INSERT INTO system_configs (config_key, config_value, description)
VALUES
    ('FEATURE_FLAG_BETA', 'true', 'Enable beta features locally'),
    ('MAX_LOGIN_ATTEMPTS', '5', 'Maximum consecutive login failures')
ON CONFLICT (config_key) DO NOTHING;

Fixing sequence drift after explicit ID inserts

If a table uses SERIAL or BIGINT GENERATED BY DEFAULT AS IDENTITY and your seed script inserts explicit integer IDs (1 through 10), PostgreSQL does not advance the underlying sequence counter. The very next INSERT from your application will try ID 1 and crash with duplicate key value violates unique constraint.

Always resynchronize integer sequences at the end of your seed script whenever you insert explicit numeric primary keys.

1
2
3
4
5
6
-- Resync the PostgreSQL sequence to the current maximum ID
SELECT setval(
    pg_get_serial_sequence('categories', 'id'),
    COALESCE((SELECT MAX(id) FROM categories), 1),
    true
);

Resetting database volumes safely with a Makefile

Running docker compose down -v wipes every named volume in your stack—including Redis, Kafka, or local MinIO buckets—when you only wanted to reset PostgreSQL.

I keep a small Makefile in the repository root with targeted recipes for resetting just the PostgreSQL volume or re-applying the idempotent seed script on a live container:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# Makefile
.PHONY: db-up db-down db-reset db-reseed

# Start only PostgreSQL in detached mode
db-up:
	docker compose up -d postgres

# Stop PostgreSQL without removing data
db-down:
	docker compose stop postgres

# Wipe only the PostgreSQL container and its named volume, then re-initialize
db-reset:
	@echo "==> Resetting PostgreSQL container and volume..."
	docker compose rm -s -f -v postgres
	docker volume rm -f myproject_postgres_data
	docker compose up -d postgres
	@echo "==> PostgreSQL re-initialized with fresh seed data."

# Re-apply the idempotent seed script against a running database
db-reseed:
	@echo "==> Re-applying seed data..."
	docker compose exec -T postgres psql -U app_user -d app_db < infra/docker/initdb/03_seed_master_data.sql

docker compose rm -s -f -v postgres stops (-s), force-removes (-f), and cleans anonymous volumes (-v) for that single service. Named volumes must still be removed explicitly with docker volume rm.


Live reloading without rebuilds using Compose Watch

When you run your backend inside a container (for example, to mirror Linux networking or share a single startup command with frontend teammates), running docker compose build && docker compose up on every file save kills momentum.

Docker Compose v2.22+ ships Compose Watch (develop.watch). Unlike classic bind mounts (- .:/app), which suffer from slow VirtioFS/gRPC-FUSE I/O on macOS/Windows and host-to-container UID/GID permission mismatches, Compose Watch listens for host filesystem events and copies only changed files into the container at native speed.

flowchart TD
    subgraph Host["Host Workspace (macOS / Linux)"]
        Src["Source Files (.java, .kt, .ts)"]
        Conf["Config Files (application-local.yml)"]
        Build["Build Files (build.gradle)"]
    end
    Watch["Docker Compose Watch Engine"]
    App["Backend Container (Spring / Node)"]
    Src -->|"action: sync"| Watch
    Conf -->|"action: sync+restart"| Watch
    Build -->|"action: rebuild"| Watch
    Watch -->|"Copy, restart, or rebuild"| App

Watch actions compared

ActionBehaviorTypical files
syncCopies changed host files directly into target inside the containerFrontend assets, templates, hot-reloading source directories
sync+restartSyncs the file, then restarts the container processapplication-local.yml, .env, reverse-proxy configs
rebuildRebuilds the image and replaces the containerbuild.gradle, settings.gradle, package.json, Dockerfile

When not to use Compose Watch

If you’re a Java or Kotlin backend developer running Spring Boot directly from IntelliJ IDEA (with only PostgreSQL and Redis in Compose, as in my local Spring Boot Compose setup), you don’t need Compose Watch for the JVM—IntelliJ’s native incremental compiler and debugger are still faster. Compose Watch shines when the application itself must run inside Linux containers or when non-JVM teammates run the backend without installing a local JDK.

Combined compose.yaml template

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# compose.yaml
services:
  postgres:
    image: postgres:17-alpine
    container_name: local-postgres
    restart: unless-stopped
    environment:
      POSTGRES_DB: app_db
      POSTGRES_USER: app_user
      POSTGRES_PASSWORD: app_secure_password
      PGDATA: /var/lib/postgresql/data/pgdata
    ports:
      - "5432:5432"
    volumes:
      - postgres_data:/var/lib/postgresql/data
      - ./infra/docker/initdb:/docker-entrypoint-initdb.d:ro
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U app_user -d app_db"]
      interval: 5s
      timeout: 5s
      retries: 5

  backend:
    build:
      context: .
      dockerfile: Dockerfile.dev
    container_name: local-backend
    ports:
      - "8080:8080"
      - "5005:5005" # JVM remote debug port
    environment:
      SPRING_PROFILES_ACTIVE: local
      SPRING_DATASOURCE_URL: jdbc:postgresql://postgres:5432/app_db
      SPRING_DATASOURCE_USERNAME: app_user
      SPRING_DATASOURCE_PASSWORD: app_secure_password
    depends_on:
      postgres:
        condition: service_healthy
    develop:
      watch:
        # 1. Rebuild image when Gradle build files change
        - action: rebuild
          path: ./build.gradle
        - action: rebuild
          path: ./settings.gradle

        # 2. Sync and restart when Spring config changes
        - action: sync+restart
          path: ./src/main/resources/application-local.yml
          target: /app/src/main/resources/application-local.yml

        # 3. Sync source files immediately for Spring DevTools / hot reload
        - action: sync
          path: ./src/main/java
          target: /app/src/main/java
          ignore:
            - "**/.*"
            - "**/*.class"

volumes:
  postgres_data:

Start the stack in watch mode with one command:

1
docker compose watch
1
2
3
4
5
6
7
[+] Running 3/3
 ✔ Network myproject_default     Created
 ✔ Container local-postgres      Healthy
 ✔ Container local-backend       Started
Watch enabled for service "backend"
Syncing src/main/java to /app/src/main/java...
[backend] Reloading application due to file changes...

Saving a file in your editor triggers a sync or restart in 1–2 seconds without running docker compose build manually.


Security caveats and checklist

Never commit production dumps as seed data: Copying real customer records into infra/docker/initdb/ exposes PII in Git history and creates immediate compliance violations. Always generate synthetic data with Faker or hand-crafted fixtures.

Keep your local seeding and watch loop maintainable with these checks:

  • Mount ./infra/docker/initdb:/docker-entrypoint-initdb.d:ro read-only so the container cannot modify host SQL files.
  • Write idempotent ON CONFLICT statements and reset integer sequences with setval(...).
  • Keep a Minimal Viable Seed (tens to hundreds of rows covering core flows) so cold container boot stays under 5 seconds.
  • Add make db-reset and make db-reseed targets so teammates don’t wipe unrelated volumes with docker compose down -v.
  • Exclude build artifacts (**/*.class, **/.*, node_modules/) under develop.watch.ignore to prevent unnecessary sync loops.
This post is licensed under CC BY 4.0 by the author.