Recently, I’ve dockerized (my very simple) personal backend project and I’ve used a volume in Docker Compose. In fact, Docker volume was something I didn’t comprehand well until now, and this time, I got to know a bit more about how it is used in Docker Compose.
What is Docker Volume?
“Volumes are the preferred mechanism for persisting data generated by and used by Docker containers.”
Use Volume With Docker Compose
This is what I have in my docker-compose.yml
:
services:
...
db:
image: postgres:15.4-bullseye
volumes:
- db-data:/var/lib/postgresql/data
...
volumes:
db-data:
In the leftmost volumes
, we specified db-data
and this allows us to define db-data
volume with default options,
and the volume can be reused across other services.
Then, inside db
service, we have volumes:
and this is where we mount our db-data
volume at /var/lib/postgresql/data
path
in the container. This allows us to have our database data in our Docker volume that’s mounted at the specified container path.