Docker › Compose

Local PostgreSQL and Redis for Spring Boot with Docker Compose

Standardize local Spring Boot development with Docker Compose v2, PostgreSQL 17, and Redis 7 using .env templates, healthchecks, and named volumes.

Local PostgreSQL and Redis for Spring Boot with Docker Compose

Different local database versions and hardcoded credentials create “works on my machine” bugs during onboarding. This post walks through a repeatable Docker Compose v2 setup for running PostgreSQL 17 and Redis 7 alongside a local Spring Boot application.

Tested with Docker Engine 27, Docker Compose v2, Spring Boot 3.4, PostgreSQL 17, and Redis 7.


Why local setups drift across a team

Every time a new engineer joins a backend project—or switches to a fresh laptop—the same local setup failures show up:

  • One person runs PostgreSQL 15 installed through Homebrew while another runs PostgreSQL 17 left over from an older project.
  • Minor SQL behavior differences (JSON operators, UUID functions, default collations) cause integration tests to pass on one laptop and fail on another.
  • A background Redis daemon already holds port 6379, breaking application startup before the first request ever runs.
  • Someone edits application.yml with their personal local password and accidentally commits it to Git.

This kind of environment drift slows down onboarding, adds noise to code reviews, and wastes hours debugging setup issues instead of application logic. Treating infrastructure as code shouldn’t stop at cloud staging and production; it pays off just as much on developer laptops.

With Docker Compose v2, a teammate can clone the repository and spin up the exact database and cache versions used in production with a single docker compose up -d command.

When not to use this setup

Running infrastructure in Docker Compose isn’t always the right answer:

ScenarioRecommended approachWhy
Daily local Spring Boot devIDE for Spring Boot + Compose for DB/RedisKeeps fast IDE hot reload and debugger while isolating infrastructure
Isolated JUnit integration testsTestcontainersEphemeral random ports prevent test state leakage across runs
Production or shared stagingManaged DB/Cache (RDS, ElastiCache) or KubernetesCompose lacks multi-node failover, automated backups, and rolling upgrades
Tiny single-file prototypesH2 or SQLiteAvoids Docker Desktop overhead when you don’t need real PostgreSQL features

If you’re writing automated repository tests that need a clean database per test class, use Testcontainers rather than sharing a persistent local Compose volume.


Architecture and network layout

For day-to-day backend work, I prefer running the Spring Boot app directly in IntelliJ IDEA while isolating PostgreSQL and Redis inside Docker Compose. Containerizing the Spring Boot app during active coding slows down compilation and debugging unless you pair it with Compose Watch.

flowchart TD
    subgraph Host["Host Machine (macOS / Linux / Windows)"]
        Dev["IDE (IntelliJ IDEA)"]
        Spring["Spring Boot App (localhost:8080)"]
        Dev -->|"Run & Debug"| Spring
    end
    subgraph DockerEnv["Docker Compose (local-network)"]
        PG["PostgreSQL 17<br/>(local-postgres:5432)"]
        RD["Redis 7<br/>(local-redis:6379)"]
        VolPG[("postgres_data<br/>(Named Volume)")]
        VolRD[("redis_data<br/>(Named Volume)")]
        PG --- VolPG
        RD --- VolRD
    end
    Spring -->|"localhost:5432 (JDBC)"| PG
    Spring -->|"localhost:6379 (Lettuce)"| RD

Both containers sit on a dedicated Docker bridge network (local-network) and publish only their service ports (5432 and 6379) to the host. Each service writes to a named volume so stopping or recreating containers doesn’t wipe your local tables or cached keys.


Separating credentials and ports with .env

Avoid hardcoding database passwords or host port bindings directly inside compose.yaml. Teammates often have another local PostgreSQL or Redis instance already bound to 5432 or 6379, and they need a clean way to shift ports without editing tracked files.

Docker Compose v2 automatically reads a .env file in the project root and substitutes its values into compose.yaml. Commit a safe .env.example template to Git instead of the real .env file:

1
2
3
4
5
6
7
8
9
10
# .env.example
# PostgreSQL Configuration
POSTGRES_HOST_PORT=5432
POSTGRES_DB=app_dev
POSTGRES_USER=app_user
POSTGRES_PASSWORD=local_secret_password!

# Redis Configuration
REDIS_HOST_PORT=6379
REDIS_PASSWORD=local_redis_secret!

Always add .env to .gitignore so personal overrides or real credentials never reach your repository. Document cp .env.example .env as the first step in your README.


Production-style compose.yaml template

Under the current Compose Specification, compose.yaml is the preferred filename over the older docker-compose.yml. Here is the complete Compose v2 template I use for Spring Boot projects:

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
# compose.yaml
services:
  postgres:
    image: postgres:17-alpine
    container_name: local-postgres
    restart: unless-stopped
    environment:
      POSTGRES_DB: ${POSTGRES_DB:-app_dev}
      POSTGRES_USER: ${POSTGRES_USER:-app_user}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-local_secret_password!}
      TZ: UTC
    ports:
      - "${POSTGRES_HOST_PORT:-5432}:5432"
    volumes:
      - postgres_data:/var/lib/postgresql/data
    networks:
      - local-network
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-app_user} -d ${POSTGRES_DB:-app_dev}"]
      interval: 5s
      timeout: 5s
      retries: 5
      start_period: 10s

  redis:
    image: redis:7-alpine
    container_name: local-redis
    restart: unless-stopped
    command: ["redis-server", "--requirepass", "${REDIS_PASSWORD:-local_redis_secret!}", "--appendonly", "yes"]
    ports:
      - "${REDIS_HOST_PORT:-6379}:6379"
    volumes:
      - redis_data:/data
    networks:
      - local-network
    healthcheck:
      test: ["CMD-SHELL", "redis-cli -a ${REDIS_PASSWORD:-local_redis_secret!} ping | grep PONG"]
      interval: 5s
      timeout: 3s
      retries: 5
      start_period: 5s

networks:
  local-network:
    driver: bridge

volumes:
  postgres_data:
    name: local_postgres_data
  redis_data:
    name: local_redis_data

Why each option is here

  1. Fallback syntax (:-): Writing ${POSTGRES_DB:-app_dev} lets docker compose up -d succeed even if a developer skips copying .env.example. When .env exists, its values override the defaults.
  2. Alpine base images: postgres:17-alpine and redis:7-alpine pull faster on new machines and consume less disk space than Debian-based variants. Note that Alpine uses musl libc, so if your production database relies on glibc collation sorting rules, switch postgres:17-alpine to postgres:17.
  3. Real readiness healthchecks: pg_isready verifies that PostgreSQL is actively accepting queries rather than just opening a socket, and redis-cli -a ... ping checks both connectivity and password authentication. If you later run your Spring Boot app inside Compose as well, these healthchecks let you gate startup with condition: service_healthy.
  4. Explicit named volume names: Setting name: local_postgres_data keeps the volume name stable even if you rename the parent project folder, which would otherwise change Compose’s default <directory>_postgres_data prefix.

Wiring Spring Boot with application-local.yml

Once the containers are defined, align your Spring Boot local profile with the same environment variable names and defaults.

src/main/resources/application-local.yml:

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
spring:
  config:
    activate:
      on-profile: local

  datasource:
    url: jdbc:postgresql://localhost:${POSTGRES_HOST_PORT:5432}/${POSTGRES_DB:app_dev}
    username: ${POSTGRES_USER:app_user}
    password: ${POSTGRES_PASSWORD:local_secret_password!}
    driver-class-name: org.postgresql.Driver
    hikari:
      pool-name: LocalHikariPool
      maximum-pool-size: 10
      minimum-idle: 5
      connection-timeout: 30000

  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
    properties:
      hibernate:
        format_sql: true
        default_batch_fetch_size: 100

  data:
    redis:
      host: localhost
      port: ${REDIS_HOST_PORT:6379}
      password: ${REDIS_PASSWORD:local_redis_secret!}
      timeout: 3000ms
      lettuce:
        pool:
          max-active: 8
          max-idle: 8
          min-idle: 2

Notice the subtle syntax difference: Docker Compose uses ${VAR:-default} (which also falls back when the variable is empty), whereas Spring Boot’s property placeholder syntax uses ${VAR:default}.

On Spring Boot 3.1+, you can also add spring-boot-docker-compose as a developmentOnly dependency. Spring Boot detects compose.yaml at startup, starts the containers automatically, and registers ServiceConnection beans for PostgreSQL and Redis without manual URL wiring.


Verification, troubleshooting, and checklist

From the project root, copy the template, start the containers in detached mode, and verify their health status:

1
2
3
4
5
6
7
8
# 1. Create local env file (one-time)
cp .env.example .env

# 2. Start PostgreSQL and Redis in the background
docker compose up -d

# 3. Verify healthcheck status and published ports
docker compose ps

Expected output:

1
2
3
NAME             IMAGE                COMMAND                  SERVICE    CREATED          STATUS                    PORTS
local-postgres   postgres:17-alpine   "docker-entrypoint.s…"   postgres   12 seconds ago   Up 11 seconds (healthy)   0.0.0.0:5432->5432/tcp
local-redis      redis:7-alpine       "docker-entrypoint.s…"   redis      12 seconds ago   Up 11 seconds (healthy)   0.0.0.0:6379->6379/tcp

Once both rows show (healthy), start Spring Boot with --spring.profiles.active=local.

Common local issues

Port 5432 or 6379 is already in use

Don’t edit compose.yaml. Override only the host ports in your untracked .env file:

1
2
3
# .env
POSTGRES_HOST_PORT=15432
REDIS_HOST_PORT=16379

The container ports remain 5432 and 6379, while the host exposes 15432 and 16379. Pass the same environment variables to your IntelliJ Run Configuration and both stacks coexist cleanly.

Corrupted schema or dirty test data

Restarting containers won’t reset data stored in named volumes. Pass -v (--volumes) to tear down the containers and delete their volumes together:

1
2
3
4
5
# Remove containers and named volumes
docker compose down -v

# Start from a clean database
docker compose up -d

docker compose down -v permanently deletes local_postgres_data and local_redis_data from disk. Dump any local test data you want to keep before running it.

Setup checklist

  • Pin major versions (postgres:17-alpine, redis:7-alpine) to match production.
  • Commit .env.example and add .env to .gitignore.
  • Define healthcheck blocks for every stateful dependency so readiness is observable.
  • Name your volumes explicitly (local_postgres_data, local_redis_data) to avoid directory-rename surprises.
  • Document the exact 3-step onboarding commands (cp .env.example .env, docker compose up -d, run app with local profile) in README.md.
This post is licensed under CC BY 4.0 by the author.