How to Mount a Single File in a Docker Volume

Volumes are a powerful way to persist data in Docker containers. Usually, we mount entire directories, but sometimes you might want to mount just a single file — for example, a configuration file, an SSL certificate, or a custom script — into your container.

In this guide, we’ll explore how to mount a single file into a Docker container using the -v (or --mount) option.


1️⃣ The Basic Syntax

To mount a single file using the -v flag:

docker run -v /path/on/host/file.txt:/path/in/container/file.txt my_image

Explanation:

  • /path/on/host/file.txt → Path to the file on your host machine.
  • /path/in/container/file.txt → Path where the file will appear inside the container.
  • my_image → The Docker image you want to run.

2️⃣ Example: Mounting a Configuration File

If you have a configuration file nginx.conf on your host and want to mount it into /etc/nginx/nginx.conf inside the container:

docker run -d \
  -v /home/user/nginx.conf:/etc/nginx/nginx.conf \
  nginx

This overrides the default Nginx config file inside the container with your custom one.


3️⃣ Using --mount for More Control

The newer --mount syntax is more verbose but also more explicit:

docker run --mount type=bind,source=/home/user/app.env,target=/app/.env my_image

Benefits of --mount:

  • Clearer, key-value style.
  • Works consistently across Docker features.
  • Easier to read in scripts.

4️⃣ Important Notes and Gotchas

  • The file must exist on the host before mounting. Docker won’t create it for you.
  • Permissions matter — the container will have the same permissions as the file on the host.
  • Overwriting existing files: If the target file exists in the container, your mounted file will replace it while the container is running.
  • Windows vs Linux paths: On Windows, use absolute paths like: docker run -v C:/path/to/config.txt:/app/config.txt my_image

5️⃣ Example: Mounting a .env File for Application Settings

docker run --env-file /dev/null \
  --mount type=bind,source=$(pwd)/.env,target=/app/.env \
  my_app_image

This mounts your .env file from the host directly into your app’s working directory.


📌 Summary

To mount a single file in a Docker volume:

  • Use -v /host/path:/container/path for quick mounting.
  • Use --mount type=bind for a clearer, more structured approach.
  • Ensure the file exists on the host and has the correct permissions.

This technique is perfect for injecting configuration, secrets, or scripts into your container without having to rebuild your image.

Sharing Is Caring:

Leave a Comment