Making a Docker container depend on a disk being properly mounted
I needed, for reasons outside the scope of this post, to make a Docker container in a docker-compose
stack start up only if a specific USB drive is currently connected and mounted.
Some requirements:
- Lightweight, runs quickly, and easy to implement.
- I don’t want to build a custom Docker image just for this, and I don’t want to modify any images or containers I’m using.
- This needs to apply to a single container, not the entire Docker service. (This rules out a
systemd
-based approach.)
My solution is to add a new Alpine Linux container in the docker-compose
stack that just checks whether the disk is mounted and exits — successfully if the disk is mounted, unsuccessfully otherwise.
To allow the new container to easily and accurately identify the disk, I put an empty file at the root of the disk, named using the disk’s UUID:
touch /mnt/my-ext-disk/.d581cb95-e8a8-48dd-bc39-d9cb3c2a3fc4
chmod 0444 /mnt/my-ext-disk/.d581cb95-e8a8-48dd-bc39-d9cb3c2a3fc4
Then, I add a new “disk verifier” container in the relevant docker-compose.yml
, and I make the preexisting container depend on this new container:
services:
myextdisk-verifier:
image: alpine:3
volumes:
- /mnt/my-ext-disk:/mnt/my-ext-disk:ro
command:
- "/bin/sh"
- "-c"
- "[ -f /mnt/my-ext-disk/.d581cb95-e8a8-48dd-bc39-d9cb3c2a3fc4 ]"
my-service:
volumes:
- /mnt/my-ext-disk/svc-data:/svc-data
depends_on:
myextdisk-verifier:
condition: service_completed_successfully
restart: true
# ... remainder of my-service goes here ...
The myextdisk-verifier
container here just uses Alpine and sh
. I can’t think of anything much simpler.