Worklet: Auto-Update Stale Docker Containers

Keeping running Docker containers up-to-date is a challenge that can become pretty unwieldy as the amount of infrastructure you manage grows. Thanks to Watchtower, a Docker image that can update other Docker images in a system, updates can be handled in a safe and—more importantly—scalable way.

This worklet will check for any Docker running containers on an endpoint with available updates and, if the container has the com.centurylinklabs.watchtower.enable label set to true, will mark those containers for update.

Evaluation:

#!/bin/bash

# helper function to check if a command exists
function command_exists {
    type "$1" &> /dev/null
}

# only evaluate if docker is available
if command_exists docker; then
    # check for docker containers with available updates
    #
    # NOTE: this check only applies to containers where
    #       the com.centurylinklabs.watchtower.enable label
    #       is set to "true"
    docker run --rm -v /var/run/docker.sock:/var/run/docker.sock containrrr/watchtower --run-once --monitor-only --label-enable 2>&1 | grep -q "Found new"

    OUT=$?

    # updates found for one or more images, mark evaluation as non-compliant 
    if [ $OUT -eq 0 ]; then
        exit 1
    fi
fi

# nothing to do
exit 0

Remediation:

#!/bin/bash

# update all docker containers with available updates
#
# NOTE: automatic updates only apply to containers where
#       the com.centurylinklabs.watchtower.enable label
#       is set to "true"
docker run --rm -v /var/run/docker.sock:/var/run/docker.sock containrrr/watchtower --run-once --label-enable

# how'd we do?
exit $?

IMPORTANT: While you can keep all containers up to date by removing the --label-enable flag from both the Evaluation and Remediation steps, this is not recommended. Not every Docker image can handle seamless updates without requiring extra steps (such as migrations, configuration changes, etc), so keeping control over what images get auto-updated using the com.centurylinklabs.watchtower.enable label is strongly suggested.

3 Likes