Some security updates have just come out and I want to rebuild my Docker images to take advantage of the updates.
However when I run docker build .
it completes immediately without updating anything because nothing has changed in the Dockerfile
, and everything is cached. It doesn't even try to run the apt-get update
line in my Dockerfile
.
How can I force Docker to run the apt-get update
command again, even though nothing has changed?
There is a --no-cache
option that says it won't use the cache during the build, but I want it to use the cache for the commands before apt-get update
and I want the results saved into the cache for the next run (replacing the currently cached images), so I definitely want to be using the cache.
I also can't use docker rmi
to remove the image generated at the point after apt-get
has been run, because it refuses to delete this image as the image has dependent child images
.
You can try something like the following:
Build image for the first time
As we can see all layers were built. Run one more time
And now all layers were taken from cache. Simple check
Now if you need to force update cache for some specific layer use the following
As you can see layers 1,2 were taken from cache but layer 3 and all latest layers were rebuilt
Repeat one more time
Another way which I have taken to doing is using the
LABEL
command:Then any time the date in the label is changed, every command after that runs again. As a bonus, the date gets built into the image so you can retrieve it with
docker inspect --format '{{ index .Config.Labels "package.dates" }}' <container>
so you can check your images to find any that have not had any security updates for a while, even if they have been rebuilt recently.Another trick which may save time updating packages is to update the base image first. With a Dockerfile like this:
You can run
docker pull debian:stable
to update that tag/image to the latest version. When you next build the Docker image, it will start with that new version and rebuild everything after it because there are not yet any cached layers starting from that new base image.Typically the base images are updated fairly regularly to include the latest packages, so updating that first will usually result in a smaller number of packages that the following
apt-get update
needs to download.