docker

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


I would like to take a Docker image (let's say ubuntu:latest) and make something like:

> docker-image-mount ubuntu:latest my_little_ubuntu  
> cd my_little_ubuntu
> ls
/usr /var /bin etc.

Is it possible somehow?


Solution

  • 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).

    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.