Sometimes you might want to mount a device or directory tree into a running container. Since the container is in its own mounts namespace, you can’t just mount it under /var/lib/lxc/container/rootfs – that mount won’t get forwarded to the container.
Mounts propagation however will let you implement a nice simple solution. Below we’ll set up a container o1, such that anything you mount on the host under /shared/o1/ will show up under /shared in the container.
First, create and set up /shared. (I’m showing you how to do it the first time. It’s probably simplest, every time you reboot the host, to rm -rf /shared and re-run this segment – in an upstart job for instance).
mount –bind /shared /shared
mount –make-unbindable /shared
mount –make-shared /shared
(In case you are wondering, we first have to turn the directory into a bind mount, as there must be a vfsmount for us to set its propagation. Next we make it unbindable so that /shared won’t get bound into any containers by accident. Then we make it shared, which creates a new mounts peer group with only a single entry – /shared. We could be more fine-grained here and make only /shared/o1 itself shared, and then, *after* it gets bound into the container, turn the container’s mount into a slave so that the container can’t push mounts back into the host’s /shared/o1.)
Now if you haven’t yet, create a container:
lxc-create -f /etc/lxc.conf -t ubuntu -n o1
Create the /shared directory in the container:
And now add an lxc.fstab entry to bind mount the shared directory:
cat >> /var/lib/lxc/o1/fstab << EOF
/shared/o1 /var/lib/lxc/o1/rootfs/shared none bind 0 0
That's it. Now, when you do
mount –bind /lib /shared/o1/lib
on the host then container o1 will see that mount as /shared/lib
Likewise, anything the container mounts under /shared will show up under /shared/o1 on the host. This could be useful for /proc or /dev/pts, for instance.
For details, you can see the in-kernel documentation. (There used to be a developerworks article by Ram Pai and myself showing more use cases, but that appears to have disappeared.)
[Update: the DeveloperWorks article has re-appeared. You can see it here.]