Docker-in-docker: Share storage layers with host

I use docker-in-docker to build images. I quickly realized that the dind approach has its own storage, and it will pull again all the base images.

Is there a way to keep using the storage driver on the host?

Super-late response, but for anyone facing the same problem, hopefully this answer helps.

When you run a container with Docker’s official DinD image, Docker implicitly creates a volume on the host and mounts it into the DinD container’s “/var/lib/docker” directory. This is done to avoid an “overlayfs-over-overlayfs” scenario (not supported by overlayfs).

If you stop, remove, and start a new DinD container, Docker creates another volume for this. And unfortunately it does not delete the old volume (leading to volume sprawl, potentially consuming a good amount of storage on your host). You can confirm this by doing docker volume ls as you start, stop, remove DinD containers.

Now, seems what you were looking for was a way to persist inner container images across the DinD container lifecycle.

You can do this by bind-mounting a host directory of your choice to the DinD container’s /var/lib/docker directory. This way, inner container images handled by Docker inside the DinD container will be stored on this host directory and persist across the DinD container’s lifecycle:

For example:

$ cd $HOME
$ mkdir docker-cache
$ docker run --privileged --name some-docker -d  --network some-network --network-alias docker     -e DOCKER_TLS_CERTDIR=/certs     -v some-docker-certs-ca:/certs/ca     -v some-docker-certs-client:/certs/client  --mount type=bind,source=/home/someuser/docker-cache,destination=/var/lib/docker docker:dind

Hope that helps.

FYI: I am the founder of a company called Nestybox; we’ve developed a container runtime (aka runc) that allows you to run Docker-in-Docker without using unsecure privileged containers. It protects your host, avoids the volume sprawl problem described above, and supports neat features such as using a Dockerfile to create a DinD container that comes pre-loaded with inner images. It’s free. Check it out at www.nestybox.com.