What is VOLUME in Dockerfile: Explanation and Usage
VOLUME instruction in a Dockerfile declares a directory inside the container as a mount point for external storage. It allows data to persist outside the container lifecycle by linking container folders to host or external volumes.How It Works
The VOLUME instruction in a Dockerfile tells Docker that the specified directory inside the container should be treated as a special folder where data is stored outside the container's writable layer. Think of it like a filing cabinet drawer that stays even if you throw away the cabinet itself.
When you create a container from an image with a VOLUME, Docker automatically creates a volume or uses an existing one to store the data in that directory. This means the data inside that folder won't be lost when the container stops or is deleted, unlike normal container files.
This separation helps keep important data safe and allows sharing data between containers or between the container and the host machine.
Example
This example shows a Dockerfile that declares a volume at /data. Any data written to /data inside the container will be stored in a Docker-managed volume on the host.
FROM alpine:latest VOLUME ["/data"] CMD ["sh", "-c", "echo Hello > /data/greeting.txt && sleep 3600"]
When to Use
Use VOLUME when your container needs to save data that should not be lost when the container stops or is deleted. This is common for databases, logs, or any app-generated files you want to keep.
For example, a database container uses a volume to store its data files so that the data remains safe even if you update or remove the container. Similarly, web servers might store uploaded files or logs in volumes.
It also helps when multiple containers need to share the same data or when you want to back up or inspect container data from the host.
Key Points
- VOLUME marks a directory for persistent or shared storage.
- Data in volumes survives container removal.
- Docker manages the volume storage location on the host.
- Volumes help separate data from container lifecycle.
- Use volumes for databases, logs, and important files.