A Docker image typically goes through a lifecycle:
It’s advantageous to add a new tag when the image progresses to a new stage in the lifecycle.
As an example, take the Git commit SHA
tested-0b3da7f(note that previously added tags are kept).
The list of tags can be used to be clean up stale Docker images. For each Docker image, the following can be checked:
deployed-production-…, and is it one of the 10 most recent images tagged like
deployed-production-…? If so, keep it.
deployed-staging-…, and is it one of the 20 most recent images tagged like
deployed-staging-…? If so, keep it.
tested-…, and is it less than 30 days old? If so, keep it.
When deploying a Git commit, the deploy script can construct the appropriate Docker tag to deploy. For example, to perform a staging deploy, concatenate
tested- with the (short) Git SHA, e.g.
tested-0b3da7f. Pull the Docker image with that tag and deploy it.
The deployment will fail if no Docker image with such a tag exists. In other words, the deployment will fail if the Docker image did not pass tests.
Some cautionary notes:
This approach is not limited to Docker. While I have not done so myself, I imagine it could work for publishing builds on an S3 bucket or similar.
How it could work (assuming
0b3da7f is the Git commit SHA of the build, which itself is a
builds/0b3da7f.tar.gz. Create the file
tags/built-0b3da7fand store in it the string
tags/tested-0b3da7fand store in it the string
tags/deployed-staging-0b3da7fand store in it the string
tags/deployed-production-0b3da7fand store in it the string
To facilitate cleanup, it might be necessary to add the date to each tag, e.g.
20210222 being the current date (February 22nd, 2021). With the date in the tag name, it becomes possible to parse out the date and delete stale builds.