9.1.2.1 Compose Local Databases
A focused guide to Compose Local Databases, connecting core concepts with practical Docker and container operations.
Compose local databases are database services defined within a Compose file, providing a developer with a consistent, easily reset, and isolated database instance for local development and testing, without affecting any other project or developer's own database setup.
Defining a Local Database Service
A database service typically specifies the image, exposed port, and basic credential configuration needed for local use.
services:
db:
image: postgres:16
ports:
- "5432:5432"
environment:
- POSTGRES_USER=devuser
- POSTGRES_PASSWORD=devpassword
- POSTGRES_DB=myapp_dev
volumes:
- dev-db-data:/var/lib/postgresql/data
volumes:
dev-db-data:
Why a Volume Still Matters Even for Local Development
Even in a local development context, backing the database's data directory with a volume ensures data persists across routine container restarts, while still being easy to deliberately reset when a genuinely fresh start is wanted.
docker compose restart db
The database's data survives this restart, since it's backed by the dev-db-data volume rather than relying on the container's ephemeral writable layer.
Resetting to a Completely Fresh Database State
When a genuinely fresh database state is needed — testing a migration from scratch, for instance — removing the volume along with the containers achieves this cleanly.
docker compose down -v
docker compose up -d
Seeding the Local Database With Initial Data
Some database images support automatically running initialization scripts the first time the database starts, useful for seeding consistent test data.
services:
db:
image: postgres:16
volumes:
- ./init-scripts:/docker-entrypoint-initdb.d
Why Compose Local Databases Matter
Defining a local database through Compose provides a consistent, easily managed, and isolated database environment for development and testing, avoiding both the overhead of a directly installed database and the risk of one developer's local database interfering with another's.