Feedback

Chat Icon

Painless Docker - 2nd Edition

A Comprehensive Guide to Mastering Docker and its Ecosystem

Docker Volumes & Data Management
40%

Volume Initialization Behavior

When you attach an empty volume to a container directory that already has files, those files are copied into the volume. If you start a container and specify a volume that hasn't been created, Docker will initialize an empty one for you. This can be useful for sharing data between containers.

Let's say we have a Docker image with a directory /app/data that contains a file named sample.txt.

Now, when we run a container from this image and mount an empty volume to /app/data, the sample.txt will be copied to the volume.

But what if the volume already has some files in it? In that case, the existing files in the volume will take precedence, and the files from the container will not be copied over.

Here is a test:

# Create a Dockerfile
echo -e "FROM busybox\nRUN mkdir -p /app/data && echo 'This is sample.txt' > /app/data/sample.txt" > Dockerfile

# Build the Docker image
docker build -t myapp-with-data .

# Create a volume
docker volume create my-data-vol

# Create a file in the volume
docker run --rm -v my-data-vol:/app/data busybox sh -c 'echo "This is existing_file.txt" > /app/data/existing_file.txt'

# Verify the contents of the volume
docker run --rm -v my-data-vol:/app/data busybox ls -l /app/data

# Run a new container with the volume mounted
docker run -it -d --name my_container -v my-data-vol:/app/data myapp-with-data

# List the contents of the /app/data directory in the container
docker exec my_container ls -l /app/data

# Clean up
docker rm -f my_container
docker volume rm my-data-vol
docker rmi myapp-with-data

What you will see is that the existing_file.txt

Painless Docker - 2nd Edition

A Comprehensive Guide to Mastering Docker and its Ecosystem

Enroll now to unlock all content and receive all future updates for free.

Unlock now  $31.99$25.59

Hurry! This limited time offer ends in:

To redeem this offer, copy the coupon code below and apply it at checkout:

Learn More