在docker容器中挂载linux镜像

问题描述 投票:0回答:2

对于一个项目,我需要在运行 ubuntu 的 docker 容器中安装 Linux 映像。我要挂载的镜像是Raspbian。我需要访问图像的 Linux 文件系统并添加一个文件。

我通过安装带有卷标志的文件夹来访问图像:

docker run -it -v /path/to/image/folder:/default ubuntu /bin/bash

fdisk -l raspbian.img
我找到了偏移量:

Disk raspbian.img: 1.3 GiB, 1389363200 bytes, 2713600 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x5a7089a1

Device        Boot  Start     End Sectors  Size Id Type
raspbian.img1        8192  137215  129024   63M  c W95 FAT32 (LBA)
raspbian.img2      137216 2713599 2576384  1.2G 83 Linux

现在,当我尝试使用

mount -o loop,offset=$((137216*512)) raspbian.img /mnt/
安装图像时,我得到
mount: /mnt/: mount failed: Unknown error -1
。有人可以解释一下我是否可以在正在运行的 docker 容器中安装 Linux 映像,如果可以的话如何安装?

编辑

在 vagrant 中执行相同的挂载操作效果非常好。 docker挂载文件系统有一些限制吗?

linux docker mount
2个回答
14
投票

docker挂载文件系统有一些限制吗?

是的。标准 Docker 容器有许多安全限制。正如您所发现的,您无法安装新的文件系统。您也无法修改容器的网络环境。

一种解决方案是简单地在主机上执行挂载操作,然后使用

-v
docker run
参数将挂载的目录公开到容器中。比如:

# losetup -fP --show raspbian.img
/dev/loop0
# mount /dev/loop0p2 /mnt
# docker run -v /mnt:/raspbian ubuntu bash

但是,如果您确实想在容器内执行挂载,则可以使用

--privileged
选项来运行特权容器
docker run
。这消除了通常对 Docker 容器施加的大部分限制:

  • 您将拥有对主持人的
    /dev
    的完全访问权限。
  • 您将能够挂载文件系统。
  • 您将能够修改容器内的网络配置。

例如:

# docker run -it --rm --privileged -v /images:/images ubuntu bash

现在我可以检查图像了:

root@30f80d4598dc:/# fdisk -l /images/2016-09-23-raspbian-jessie-lite.img 
Disk /images/2016-09-23-raspbian-jessie-lite.img: 1.3 GiB, 1389363200 bytes, 2713600 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x5a7089a1

Device                                       Boot  Start     End Sectors  Size Id Type
/images/2016-09-23-raspbian-jessie-lite.img1        8192  137215  129024   63M  c W95 FAT
/images/2016-09-23-raspbian-jessie-lite.img2      137216 2713599 2576384  1.2G 83 Linux

并安装它:

root@952a75f105ee:/# mount -o loop,offset=$((137216*512))  /images/2016-09-23-raspbian-jessie-lite.img /mnt
root@952a75f105ee:/# ls /mnt
bin   dev  home  lib64       media  opt   root  sbin  sys  usr
boot  etc  lib   lost+found  mnt    proc  run   srv   tmp  var
root@952a75f105ee:/# 

0
投票

在 Dockefile 中添加 VOLUME:

VOLUME /youdir

启动docker时:

docker -v /youdir:/youdir

在容器中:

mount youisofile.iso /youdir
© www.soinside.com 2019 - 2024. All rights reserved.