Spring › Feature

Spring Boot Docker Compose with idempotent PostgreSQL seed data

Auto-start PostgreSQL and Redis on bootRun and seed local dev data once with a PL/pgSQL DO block that stays idempotent under ddl-auto update.

Spring Boot Docker Compose with idempotent PostgreSQL seed data

Cloning a backend repo shouldn’t require a checklist of manual container commands and seed scripts. This post shows how I paired spring-boot-docker-compose with a PL/pgSQL DO block so ./gradlew bootRun starts PostgreSQL and Redis automatically and seeds sample data once—without wiping local records on restart.

Tested with Spring Boot 3.4, Kotlin 2.1, PostgreSQL 17, and Redis 7.

The local DX dilemma

While building a legal-judgment ingestion and summary backend (demo-backend-server), local development ran into two recurring friction points.

First, infrastructure lived outside the app lifecycle. Running the server required PostgreSQL 17 and Redis 7, so every reboot or fresh clone meant remembering docker compose up -d before hitting Connection refused.

Second, ddl-auto forced an ugly trade-off between preserving local data and having sample data ready:

StrategyUpsideBreaking point
ddl-auto: create / create-dropClean tables every boot; data.sql runs cleanlyWipes hundreds of collected local records and test posts on every restart
ddl-auto: update + sql.init.mode: alwaysPreserves collected records across restartsRe-runs INSERT statements on boot and crashes with duplicate key value violates unique constraint
ddl-auto: update + sql.init.mode: neverPreserves collected records; no crashFresh clones boot into an empty database with no test users

My target was simple: run ./gradlew bootRun once, let Spring Boot bring up healthy containers, seed sample data only when the database is empty, and restart 100 times with zero errors and zero lost records.

Spring Boot startup log auto-starting PostgreSQL and Redis via Docker Compose Figure 1. ./gradlew bootRun detecting docker-compose.yaml, starting PostgreSQL and Redis, waiting for healthchecks, and injecting connection properties.


Startup lifecycle overview

The spring-boot-docker-compose module delays bean initialization until container healthchecks pass, Hibernate applies schema updates, and a single PL/pgSQL DO block decides whether to seed or exit early.

flowchart TD
    Start["./gradlew bootRun (dev profile)"] --> Compose["DockerComposeLifecycleManager<br/>runs docker compose up -d"]
    Compose --> Health{"Healthchecks pass?<br/>(pg_isready, redis-cli ping)"}
    Health -->|"Healthy"| JPA["Inject ConnectionDetails<br/>and run Hibernate ddl-auto: update"]
    JPA --> Seed{"PL/pgSQL DO block:<br/>Anchor seed user exists?"}
    Seed -->|"Yes (restart)"| Skip["RETURN early (3 ms)"]
    Seed -->|"No (fresh volume)"| Insert["Insert sample users, judges, posts"]
    Skip --> Admin["DevAdminInitializer + Tomcat ready"]
    Insert --> Admin

Step 1: Wire up spring-boot-docker-compose

Add spring-boot-docker-compose under developmentOnly in build.gradle.kts so it never ships inside your production JAR:

1
2
3
4
5
6
7
8
9
10
11
// build.gradle.kts
dependencies {
    implementation("org.springframework.boot:spring-boot-starter-data-jpa")
    implementation("org.springframework.boot:spring-boot-starter-data-redis")
    implementation("org.springframework.boot:spring-boot-starter-webmvc")

    developmentOnly("org.springframework.boot:spring-boot-devtools")
    developmentOnly("org.springframework.boot:spring-boot-docker-compose")

    runtimeOnly("org.postgresql:postgresql")
}

Next, define docker-compose.yaml at the repository root. Include explicit healthcheck blocks—without them, Docker marks the container running while PostgreSQL is still initializing, and HikariCP fails on boot (see configuring Docker Compose depends_on healthchecks).

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
# docker-compose.yaml
services:
  postgres:
    image: 'postgres:17'
    environment:
      - 'POSTGRES_DB=demo-app_dev'
      - 'POSTGRES_USER=myuser'
      - 'POSTGRES_PASSWORD=secret'
    ports:
      - '5432:5432'
    volumes:
      - postgres-data:/var/lib/postgresql/data
    healthcheck:
      test: [ "CMD-SHELL", "pg_isready -U myuser -d demo-app_dev" ]
      interval: 10s
      timeout: 5s
      retries: 5

  redis:
    image: 'redis:7'
    command: [ "redis-server" ]
    ports:
      - '6379:6379'
    volumes:
      - redis-data:/data
    healthcheck:
      test: [ "CMD", "redis-cli", "ping" ]
      interval: 10s
      timeout: 5s
      retries: 5

volumes:
  postgres-data:
  redis-data:

Once both services report healthy, Spring Boot’s PostgresDockerComposeConnectionDetailsFactory and RedisDockerComposeConnectionDetailsFactory inspect the container port mappings and credentials and register ConnectionDetails automatically—overriding any default localhost placeholders in application.yaml.

Docker Desktop showing PostgreSQL 17 and Redis 7 containers running Figure 2. PostgreSQL 17 and Redis 7 containers started automatically by Spring Boot in Docker Desktop.

By default, Spring Boot leaves containers running when the JVM exits (lifecycle-management: start-only). Subsequent restarts skip container boot completely and come up in about two seconds.


Step 2: Idempotent seeding under ddl-auto: update

Configure application-dev.yaml to defer SQL initialization until Hibernate finishes updating tables, point to a dev-only seed file, and override the default statement separator:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# src/main/resources/application-dev.yaml
spring:
  jpa:
    hibernate:
      # Preserve locally collected records across restarts
      ddl-auto: update
    show-sql: true
    properties:
      hibernate:
        format_sql: true
        dialect: org.hibernate.dialect.PostgreSQLDialect
    # Wait for Hibernate DDL updates before running seed SQL
    defer-datasource-initialization: true

  sql:
    init:
      mode: always
      # Keep dev seed separate from default data.sql so prod/tests stay clean
      data-locations: classpath:db/seed-dev.sql
      # Send the entire PL/pgSQL DO block as a single statement
      separator: ^^^ END OF SCRIPT ^^^

Two settings here prevent the most common boot failures:

  1. defer-datasource-initialization: true: Since Spring Boot 2.5, spring.sql.init runs before JPA creates EntityManagerFactory. Without deferring it, your seed script executes before Hibernate creates the tables.
  2. separator: ^^^ END OF SCRIPT ^^^: Spring’s ScriptUtils splits SQL files on ; by default. A PostgreSQL DO $seed$ BEGIN ... END $seed$; block contains dozens of internal semicolons. Leaving the default separator cuts the block at the first ; and throws:
1
2
3
org.springframework.jdbc.datasource.init.ScriptStatementFailedException:
Failed to execute SQL script statement: DO $seed$ BEGIN IF EXISTS (SELECT 1 FROM users WHERE id = '...');
[PSQLException: ERROR: syntax error at end of input]

Using a sentinel separator that never appears in the file hands the entire DO block to PostgreSQL intact.

Writing seed-dev.sql without breaking IDENTITY sequences

At the top of seed-dev.sql, check for a fixed anchor UUIDv7 user (see why I use UUIDv7 for JPA entity primary keys). If it exists, return immediately.

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
-- src/main/resources/db/seed-dev.sql
-- Idempotent dev seed executed as a single PL/pgSQL block.

DO $seed$
BEGIN
    -- 1. Idempotency guard: exit immediately if the anchor seed user exists
    IF EXISTS (SELECT 1 FROM users WHERE id = '0192f000-0000-7000-8000-000000000001') THEN
        RETURN;
    END IF;

    -- 2. Seed sample users with deterministic UUIDv7 IDs
    INSERT INTO users (id, email, password, nickname, profile_image_url, created_at, updated_at, created_user, updated_user)
    VALUES ('0192f000-0000-7000-8000-000000000001', 'alex@example.com', '$2a$10$fQOlprBgjTx7auQ/j0wc1eE5yR9qyi4Rsn89uvhSqknzB9q4kKplq', 'Alex', 'https://api.dicebear.com/7.x/lorelei/svg?seed=alex@example.com', now() - interval '30 days', now() - interval '2 days', 'SYSTEM (seed)', 'SYSTEM (seed)'),
           ('0192f000-0000-7000-8000-000000000002', 'mina@example.com', '$2a$10$fQOlprBgjTx7auQ/j0wc1eE5yR9qyi4Rsn89uvhSqknzB9q4kKplq', 'Mina', 'https://api.dicebear.com/7.x/lorelei/svg?seed=mina@example.com', now() - interval '28 days', now() - interval '28 days', 'SYSTEM (seed)', 'SYSTEM (seed)');

    -- 3. Seed judges
    INSERT INTO judges (name, court, profile_image_url, created_at, updated_at, created_user, updated_user)
    VALUES ('Doyun Kim', 'Supreme Court', 'https://api.dicebear.com/7.x/lorelei/svg?seed=doyun', now() - interval '40 days', now() - interval '40 days', 'SYSTEM (seed)', 'SYSTEM (seed)'),
           ('Minseo Choi', 'Seoul High Court', 'https://api.dicebear.com/7.x/lorelei/svg?seed=minseo', now() - interval '35 days', now() - interval '35 days', 'SYSTEM (seed)', 'SYSTEM (seed)');

    -- 4. Resolve IDENTITY foreign keys via natural keys to avoid sequence desync
    INSERT INTO article_comments (article_id, author_id, content, created_at, updated_at, created_user, updated_user)
    SELECT a.id, v.author_id::uuid, v.content, now() - (v.hours_ago || ' hours')::interval, now() - (v.hours_ago || ' hours')::interval, 'SYSTEM (seed)', 'SYSTEM (seed)'
    FROM (VALUES ('2024-Do-10234', '0192f000-0000-7000-8000-000000000001', 'The key question is intent at the time of dispatch.', 400),
                 ('2023-Da-21345', '0192f000-0000-7000-8000-000000000002', 'How many years of wear count as normal depreciation?', 300)
         ) AS v(case_number, author_id, content, hours_ago)
             JOIN judgments j ON j.case_number = v.case_number
             JOIN articles a ON a.judgment_id = j.id;

END
$seed$;

Never hardcode numeric id = 1, 2, 3 values into IDENTITY or BIGSERIAL tables. Hardcoded IDs bypass the backing sequence, causing the next Hibernate save() to generate id = 1 and crash with a primary-key conflict. Joining on a natural key like case_number keeps sequences aligned.


Step 3: Separating admin account setup (DevAdminInitializer)

Plain SQL works for static fixtures, but admin accounts need the app’s configured PasswordEncoder (BCrypt) and domain role rules. An ApplicationRunner scoped to @Profile("dev") handles that cleanly and stays idempotent via existsByEmail:

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
// src/main/kotlin/com/example/server/config/DevAdminInitializer.kt
package com.example.server.config

import com.example.server.user.domain.User
import com.example.server.user.domain.UserRepository
import com.example.server.user.domain.UserRole
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.ApplicationArguments
import org.springframework.boot.ApplicationRunner
import org.springframework.context.annotation.Profile
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.stereotype.Component
import org.springframework.transaction.annotation.Transactional

@Component
@Profile("dev")
class DevAdminInitializer(
    private val userRepository: UserRepository,
    private val passwordEncoder: PasswordEncoder,
    @Value("\${app.dev-admin.email:admin@example.com}") private val email: String,
    @Value("\${app.dev-admin.password:admin1234!}") private val password: String,
) : ApplicationRunner {

    private val log = LoggerFactory.getLogger(javaClass)

    @Transactional
    override fun run(args: ApplicationArguments) {
        if (userRepository.existsByEmail(email)) return

        userRepository.save(
            User(
                email = email,
                password = passwordEncoder.encode(password),
                nickname = "Admin",
                roles = mutableSetOf(UserRole.ADMIN, UserRole.USER),
            )
        )
        log.info("Created dev admin account: {}", email)
    }
}

Verification and caveats

On a fresh volume (docker compose down -v), ./gradlew bootRun starts both containers, creates the schema, runs seed-dev.sql, and registers the dev admin account. On every subsequent restart, the IF EXISTS ... RETURN guard finishes in 3 ms with zero duplicate-key errors, while preserving all locally collected records.

PL/pgSQL DO block execution log and psql row count verification Figure 3. Restart log showing the idempotent DO block exiting in 3 ms alongside psql row counts confirming no duplicate rows.

To reset the local database completely after major schema changes:

1
2
docker compose down -v
./gradlew bootRun --args='--spring.profiles.active=dev'

When not to use ddl-auto: update + seed-dev.sql
Keep this pattern strictly inside your dev profile. In staging and production, ddl-auto: update can’t safely handle column renames, non-null backfills, or rollbacks—use Flyway or Liquibase migrations instead. Also note that DO $seed$ blocks are PostgreSQL-specific and won’t run against an H2 test database.

Checklist

  • Scope spring-boot-docker-compose to developmentOnly.
  • Add healthcheck blocks for every service in docker-compose.yaml.
  • Set both defer-datasource-initialization: true and a custom spring.sql.init.separator for PL/pgSQL DO blocks.
  • Resolve IDENTITY foreign keys via natural-key joins instead of hardcoded numeric IDs.

References

This post is licensed under CC BY 4.0 by the author.