Delayed starting of Docker service until expected mounts are available

Delayed starting of Docker service until expected mounts are available

(Or for any other systemctl controlled service, for that matter)

If you've ever run into the situation where you reboot your computer (or virtual machine) and the Docker service kicked in a bit too fast, even before some of your fstab defined mounts are fully available, you might've noticed that some of your containers might not know how to deal with expected data being available right from the get-go. A restart of the containers usually fixes this, but to do this manually every time is rather tedious.

Fortunately there is a way to fix this by making the docker service wait to start until all desired mounts are ready and available.

This is achieved by adding a docker.service configuration overwrite that adds a prerequisite. This override is added in such a way that subsequent docker updates won't inadvertently undo this. Let's get started.

First, open up your favorite terminal and run the following command on the system that runs your docker service:

❯ sudo systemctl edit docker.service

Your favorite text editor (or whatever is defined in the $EDITOR environment variable, anyway) will automatically open, with the entire docker.service configuration listed out in a comment section. Reading through the comments shown you'll see that you'll be able to add what you need to add between two comment notes near the top.

Add the following in-between these two comments (comments are shown below as a guide, please don't include them in your own config file again), substituting the example /mnt/foo and /mnt/bar paths with a space delimited list of all mount paths you want to wait for before starting the docker service:

### Anything between here and the comment below will become the new contents of the file

RequiresMountsFor=/mnt/foo /mnt/bar

### Lines below this comment will be discarded

When that's done, close your text editor and that's it! Next time you reboot your system, the Docker service will wait to start until after the mount(s) you have defined here have become available.

I hope this helps!