There are few ways to mount a single file as a Docker volume whatever you are trying to spin a single container using docker run
or being a part of a Docker Compose stack. This scenario usually comes in mind when dealing with a single configuration file that needs to be stored under a certain Git repository, hence you want to keep track of all changes applied on the file itself.
Prerequisites
- Docker
Solution(s)
docker compose
Mount a single file as a Docker volume code snippet:
version: "3.9"
services:
redis:
...
volumes:
- ./conf/redis.conf:/etc/redis/redis.conf
./
refers to the relative path which could be achieved using ${PWD}
as well. For instance:
volumes:
- ${PWD}/conf/redis.conf:/etc/redis/redis.conf
Alternate solution:
version: "3.9"
services:
redis:
...
volumes:
- type: bind
source: ./conf/redis.conf
target: /etc/redis/redis.conf
docker cli
Using --mount
option:
docker run -it -d --mount type=bind,source=$(pwd)/conf/redis.conf,target=/etc/redis/redis.conf redis:latest
Using --volumes (-v)
option:
docker run -it -d -v $(pwd)/conf/redis.conf:/etc/redis/redis.conf redis:latest
Note(s):
- Remember that host_path is the source, container_path is the destination (host_path/:container_path/).
- Use
"%cd%"
if running on Windows. - Always use absolute path when specifying the host path. If not, Docker will throw an error.
- The main difference between
--mount
and--volume
is that when dealing with volumes, if the host’s file or directory doesn’t exist yet, Docker will create as a directory whether it is a directory or not. However, that’s not the case with-mount
as it will throw an error each time, unless the file / directory exists on the host.
Conclusion
Feel free to leave a comment below and if you find this tutorial useful, follow our official channel on Telegram.