Mounting disk images inside a Docker container requires 2 steps. The first step is giving the Docker container elevated permissions to create loopback devices that are both inside and outside the container, and the second is creating a loopback device inside the container.
If you don’t want to use elevated permissions, see below the first example. You cannot use loopback devices without –privileged and removed other privileges via –cap-drop so if you cannot use that tag you cannot use them inside the container.
Execute outside, on the host:
docker run -it --privileged \ ubuntu /bin/bash
Execute the following inside the container:
losetup -f # /dev/loop0 # make a 64 Megabyte disk fallocate -l 64M img.img mkfs.ext4 img.img # mount the disk on the loopback device (e.g. put the CDROM into the DRIVE) losetup /dev/loop0 img.img # mount the CDROM mkdir ./mountpoint mount /dev/loop0 ./mountpoint df -h # /dev/loop0 58M 52K 54M 1% /mountpoint
You can create as many as you like:
# make another loopback drive inside the container losetup -f # /dev/loop1 # make a example 10 Megabyte disk fallocate -l 10M img1.img mkfs.ext4 img1.img # put the disk in the loopback drive losetup /dev/loop1 img1.img # mount the drive mkdir ./mountpoint1 mount /dev/loop1 ./mountpoint1 df -h # /dev/loop0 58M 52K 54M 1% /mountpoint # /dev/loop1 5.7M 28K 5.0M 1% /mountpoint1
When you are finished, unmount the image from the mountpoint, and delete the empty loopback drive:
umount /mountpoint umount /mountpoint1 losetup -d /dev/loop0 losetup -d /dev/loop1
If you do not provide enough permissions, you will see:
root@bba9ea680442:/# losetup /dev/loop0 img1.img
losetup: /dev/loop0: failed to set up loop device: Operation not permitted
If you want to use lower privileges, create the loopback device outside the container first.
And also use –cap-drop to remove permissions elevated by –privileged.
sudo losetup -f # /dev/loop0 docker run -it --privileged \ -v /dev/loop0:/dev/loop0 \ ubuntu /bin/bash
Leave a Reply