loop device in a Linux container?
Solution 1:
If you're using systemd-nspawn, start up your container with the --capability=CAP_MKNOD
command line switch. This will allow you to create device nodes inside your container. Then create a loop device like this:
# mknod /dev/loop0 b 7 0
Remember that this loop device is shared with the host and is called /dev/loop0
there as well. And that it is now possible to access host devices if you know the major and minor numbers. There could also be other consequences that I haven't thought about. Be warned.
Solution 2:
Loop devices are provided by a kernel module. Therefore, you need special privileges to access them. You also need them to be exposed into your container, or you need to manually create the device files.
The quick answer
docker run --privileged=true ...
An alternative
sudo losetup /dev/loop0 test.img
mount /dev/loop0 /mnt
docker run -v /mnt:/mnt ...
This almost works
docker run --device=/dev/loop-control:/dev/loop-control --device=/dev/loop0:/dev/loop0 --cap-add SYS_ADMIN ...
However I get this error:
root@5c033d5f8625:/# sudo mount /dev/loop0 /mnt
mount: block device /dev/loop0 is write-protected, mounting read-only
mount: cannot mount block device /dev/loop0 read-only
See this link for more information.
A note on systemd-nspawn man page:
systemd-nspawn limits access to various kernel interfaces in the container to read-only, such as /sys, /proc/sys or /sys/fs/selinux. Network interfaces and the system clock may not be changed from within the container. Device nodes may not be created. The host system cannot be rebooted and kernel modules may not be loaded from within the container.