Why don't my udev rules work inside of a running docker container?

Ryan picture Ryan · Apr 27, 2016 · Viewed 10.8k times · Source

I have udev rules written to create SYMLINKS when a device is connected. The rules are working fine on the host machine, but when I start a container with these same rules installed in /etc/udev/rules.d, they don't work inside my container.

I am trying to detect when an external drive is plugged in and create a corresponding symlink. /dev/sdX is created on boot of the container iff the drive was present at time of docker run, but it won't appear after the run command, nor will it disappear upon the drive being removed.

Here's an example rule that works just fine on the host machine:

KERNEL=="sd?", SYMLINK+="test_%k"

Answer

Ryan picture Ryan · Apr 27, 2016

I figured it out. What I've seen done on the internet is to mount the host's /dev inside the container:

docker run -v=/dev:/dev (Note: not safe)

But this is very dangerous and pretty much destroys the host computer by mucking with permissions (e.g. psuedo-terminals can't be spawned).

However, if I set up a udev rule on the host machine to create devices in a unique subdirectory, like /dev/foo/sdX, I can then just share dev/foo with my container:

docker run -v=/dev/foo:/dev/foo

Now, when I insert a drive that matches my udev rule, the host machine creates a symlink in /dev/foo/sdX, which is now suddenly visible to my container. When the drive is removed, /dev/foo/sdX also disappears.


The one missing feature that would be nice is the ability to trigger a script inside the container when the device is created. A udev rule can do that on the host machine, but no udev rules seem to be tripped inside the container. So manual polling it is, for now.