Search code examples
linuxdockercontainersblockdevice

How to access block device inside a Docker container


I have been trying to access block storage device of host system from a docker container though binding mount. Getting 'Operation not permitted' error.

Is there anything that I'm missing here:

# ls -l /dev/sdb
brw-rw---- 1 root disk 8, 16 Sep  3 00:52 /dev/sdb
# 
# dd if=/dev/zero of=/dev/sdb bs=1M
16005+0 records in
16005+0 records out
16782458880 bytes (17 GB) copied, 12.4396 s, 1.3 GB/s

# 
# 
# docker container run --name c1 -it --mount type=bind,source=/dev/sdb,target=/data centos
/# ls -l /data
brw-rw---- 1 root disk 8, 16 Sep  3 06:52 /data
/# 
/#
/# dd if=/dev/zero of=/data bs=1M
dd: failed to open '/data': Operation not permitted
/#

Solution

  • For hardware device, you will need to give capabilities to container to operation the device, there are 2 options here:

    Option 1: Use privileged

    See Full container capabilities (--privileged):

    # docker container run --rm --privileged --name c1 -it --mount type=bind,source=/dev/sdb,target=/data centos
    [root@7ab2eaef67cd /]# ls -al /data
    brw-rw---- 1 root disk 8, 16 Sep  3 08:13 /data
    [root@7ab2eaef67cd /]# dd if=/dev/zero of=/data bs=1 count=1
    1+0 records in
    1+0 records out
    1 byte copied, 0.00710505 s, 0.1 kB/s
    [root@7ab2eaef67cd /]# exit
    exit
    

    Option 2: Use --device

    See Add host device to container (--device):

    # docker container run --rm --name c1 -it --device=/dev/sdb:/data centos
    [root@3a05b15b3b96 /]# ls -al /data
    brw-rw---- 1 root disk 8, 16 Sep  3 08:15 /data
    [root@3a05b15b3b96 /]# dd if=/dev/zero of=/data bs=1 count=1
    1+0 records in
    1+0 records out
    1 byte copied, 0.00326708 s, 0.3 kB/s
    [root@3a05b15b3b96 /]# exit
    exit