Dockerfile by Example: Volume Mount Declaration
The VOLUME instruction creates a mount point for externally mounted volumes. This sample code shows how to define persistent storage areas within the image.
Code
FROM postgres:15-alpine
# Define a volume for database data
# This tells Docker that /var/lib/postgresql/data holds persistent data
VOLUME ["/var/lib/postgresql/data"]
# You can define multiple volumes
VOLUME ["/etc/postgresql", "/var/log/postgresql"]
# When you run this image:
# docker run -v my-db-data:/var/lib/postgresql/data my-postgres
# The data in that directory will survive container restarts.Explanation
The VOLUME instruction creates a mount point with the specified name and marks it as holding externally mounted volumes. If a user starts the container without mapping this volume to a host directory, Docker automatically creates an anonymous volume to ensure the data is preserved. This mechanism prevents accidental data loss for critical paths like database storage directories.
Characteristics of Dockerfile Volumes:
- Creates an anonymous volume if no host path is provided at runtime
- Data in the volume persists beyond the container's lifecycle
- Subsequent
RUNinstructions cannot modify data in the volume - Used to declare intent that a directory contains persistent data
A critical limitation is that once a VOLUME is declared, subsequent instructions in the Dockerfile cannot modify the content of that directory. Any changes made to the volume path in later RUN steps are discarded or written to the temporary container layer, not the volume itself. Therefore, VOLUME instructions should generally be placed near the end of the Dockerfile, after all setup for that directory is complete.
Code Breakdown
VOLUME ["..."] declares the path as a volume mount point.FROM postgres... implies we are handling a stateful application.
