Search code examples
docker

Can I mount docker host directory as copy on write/overlay?


I'd like to mount a host directory in docker that on the outside is actually read/only. But I'd like it to appear inside the container as read/write.

So that files/directories can be written to but not changed on the outside. Is this possible using some kind of overlay process?


Solution

  • Edit: Check @javabrett's comment:

    Upvoted despite this solution having a sunset. See answer regarding overlay-upperdir-on-overlay being disabled on 4.8 kernels and newer.

    See: https://stackoverflow.com/a/50917037/644504


    This is what I do:

    On the host:

    Load the directory as read only.

    docker run --privileged -v /path/on/host:/path/on/client-read-only:ro -it ubuntu /bin/bash
    

    On the client:

    On the client use OverlayFS over the read-only directory mounted from the host.

    mount -t overlayfs none -o lowerdir=/path/on/client-read-only,upperdir=/path/on/client /path/on/client
    

    Then use /path/on/client to read/write the files.

    Edit: if you have a 3.18+ kernel on your host, you may prefer using this on the client:

    mount -t overlay overlay -o lowerdir=/path/on/client-read-only,upperdir=/path/on/client,workdir=/path/on/client-workdir /path/on/client
    

    Which isn't overlayfs. With overlayfs I had an issue regarding being unable to use rm. overlay solved this problem for me.