Chris Dzombak

sharing preview • dzombak.com

Making a Docker container depend on a disk being properly mounted

Quick and easy way to a Docker container depend on an external disk being connected and mounted.

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:

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.