on
Docker 103 - Understand Dockerfile Volume
In this article, we’ll learn how to create a Docker image using Dockerfile
and volumes, and we will see why we should not declare Docker or host path volumes in a Dockerfile
.
Docker Guide (6 Part Series)
- Docker Containers
- Docker Images
- Docker Layers
- Docker with Java Spring and Maven
- Understand Dockerfile Volume
- Docker Builder Containers
Terminology
The basic concepts of Docker are Images and Containers:
- Image: Ordered collection of filesystem changes and execution parameters
- Container: Runtime instance of a docker image
There are other concepts to know about :
- Volume: System to persist data, independent of the container’s life cycle
- Dockerfile: Text document that contains all the commands to create an image
- Layer: modification to an image, represented by an instruction in the Dockerfile
- Tag: Label applied to a Docker image in a repository.
- Repository: Set of Docker images
- Registry: Hosted service containing repositories of images
- Union File System: conjunction with copy-on-write techniques to provide the building blocks for containers
In a Dockerfile
, the VOLUME
instruction specifies the volumes with given container-side paths. But it does not allow the image author to define a host path for security reasons and because the path must be defined at runtime as it changes from an OS to another. Hence, this means that the volume will be unnamed.
Let’s see how to create a volume with Dockerfile and use it inside a container:
FROM alpine
RUN mkdir /directory01
VOLUME /directory01
Next, we build the image and tag it:
$ docker build -t custom-alpin .
Then we start the container using the built image and do some changes in a bash session:
$ docker run -it custom-alpin sh
$ cd directory01
/directory01 $ touch file.txt
/directory01 $ exit
Data will be lost after stopping and deleting the container.
If the use of Docker volumes and host path volumes was implemented, think of the following situation:
FROM alpine
VOLUME data:/my/data
Next, we build the image and tag it:
$ docker build -t custom-alpin .
Then we start two containers using the built image:
$ docker run --name app1 custom-alpin
$ docker run --name app2 custom-alpin
Now both app1
and app2
would be creating a volume named data
, and use the same volume. Effectively we would only be able to run a single instance of the image.
Conclusion
In this article, we saw the use of volumes in Dockerfile
and why we should avoid declaring Docker volumes and host path volumes.