Is it possible to mount a docker image and then access it (RO) as a normal directory or mounted device?

I've just investigated internal structure of how docker stores their images. In case of aufs storage driver there is following directory layout (I assume, that docker lives in /var/lib/docker).

  • /var/lib/docker/aufs/diff in this directory docker stores data of each image "layer". It is just a directory with files, which docker mounts in container root.
  • /var/lib/docker/aufs/layers in this directory docker stores just text files. Each files contains list of layer ID's for certain image.

So docker itself does something like that:

DOCKER_AUFS_PATH="/var/lib/docker/aufs/"
DOCKER_AUFS_LAYERS="${DOCKER_AUFS_PATH}/layers/"
DOCKER_AUFS_DIFF="${DOCKER_AUFS_PATH}/diff/"

error() { echo "$@" 1>&2; }

if [ -z "${IMAGE}" ];
then
  error "Image is not specified"
  exit 1
fi;

if [ -z "${TARGET}" ];
then
  error "Target is not specified"
  exit 1
fi;

BRANCH="br"
while read LAYER; do
  BRANCH+=":${DOCKER_AUFS_DIFF}/${LAYER}=ro+wh"
done < "${DOCKER_AUFS_LAYERS}/${IMAGE}"

mount -t aufs -o "${BRANCH}" "${IMAGE}" "${TARGET}"

Where ${IMAGE} is ID of docker container, and ${TARGET} is existed directory in host filesystem where to mount image.

To unmount it just call:

umount cf39b476aeec4d2bd097945a14a147dc52e16bd88511ed931357a5cd6f6590de

As I mentioned in comment above, this is heavily depends on storage driver (and obviously on docker version), so I could not give you any guarantee that you will get this code working.

Tags:

Docker