Persistent directories for one-way Docker containers

One-way bottles in germany will be thrown in the garbage after usage. Some Docker containers will be removed or destroyed after execution. But especially for some dependency management tools or task runners it can be nice to have a persistent directory. We can achieve that with the parameter --volumes-from and a busybox. I will show the usage on a Docker container of Composer and Gradle, but the principle is easy to transfer for other building or management Docker containers.

Composer

For example the composer/composer image has a recommended command like the following.

docker run --rm -v $(pwd):/app composer/composer install

The command from above will download your PHP dependencies that are defined in your composer.json and will store them in the vendor directory. Composer has to download the dependencies again if we remove the vendor directory or changing to an other project with similar dependencies. But the normal behavior of Composer would be to use the ~/.composer/cache/ directory instead of downloading again the same dependencies.

Composer busybox

We can create a Composer busybox that has just the task to store that cache directory.

docker create -v /composer --name composer_cache busybox

This container can be inserted into the command from above with the --volumes-from parameter.

docker run --rm --volumes-from composer_cache -v $(pwd):/app composer/composer install

Composer does not have to download the dependencies again if we execute the command more than ones, regardless of whether the vendor directory exists in the project directory or not.

Gradle

The described problem is even more challenging with my own Gradle Docker image. Gradle is storing the dependencies not in the project directory. Means every execution of my Gradle container is downloading the dependencies and throwing them away after tearing down the container, there is not even something like a vendor directory in the project directory as something like a first layer cache for dependencies. For example this check command is downloading the JUnit pom with every execution.

docker run --rm -v "$PWD":/usr/src/project -w /usr/src/project gradle gradle check

Gradle busybox

We can create a Gradle busybox that has just the task to store the downloaded dependencies.

docker create -v /root --name gradle_cache busybox

This container can be inserted into the evil command from above with the parameter --volumes-from to prevent that downloaded dependencies are thrown away after tearing down the Gradle container.

docker run --rm --volumes-from gradle_cache -v "$PWD":/usr/src/project -w /usr/src/project gradle gradle check
Next Previous