I’m having trouble with data persistence in my Docker Compose setup for a Spring Boot application that uses PostgreSQL. The data persists only when I stop the PostgreSQL container individually and start it again, but when I bring the entire Docker Compose stack down and then up again, the data is lost.
Here’s my docker-compose.yml file:
version: '3.8'
services:
postgres:
image: postgres:latest
container_name: postgres-container
environment:
POSTGRES_DB: jwt_security
POSTGRES_USER: postgres
POSTGRES_PASSWORD: password
volumes:
- postgres-data:/var/lib/postgresql/data
ports:
- "5431:5432"
app:
image: my-spring-app # Replace with your actual Spring Boot app image name
container_name: spring-boot-app
environment:
SPRING_DATASOURCE_URL: jdbc:postgresql://postgres:5432/jwt_security
SPRING_DATASOURCE_USERNAME: postgres
SPRING_DATASOURCE_PASSWORD: password
depends_on:
- postgres
ports:
- "8080:8080" # Adjust if your Spring Boot app runs on a different port
volumes:
postgres-data:
external: true
Steps I Have Tried:
-
Remove Existing Containers and Volumes:
docker-compose down -v docker volume rm postgres-data
-
Create the External Volume:
docker volume create --name postgres-data
-
Bring Up the Containers:
docker-compose up
Problem:
After setting up the environment and adding data to the database, I can see the data using:
docker exec -it postgres-container psql -U postgres -d jwt_security
SELECT * FROM _user;
However, when I run docker-compose down
and then docker-compose up
, the data is lost. Here are the details of what I observe:
- The external volume seems to be created and used correctly.
- When I inspect the volume, it appears to be mounted correctly.
- Logs from the PostgreSQL container indicate the database system initializes correctly but does not retain data.