Updating Docker image is a pain if you do it manually. This post is going to show you all the methods I found from Internet how to update your docker image to latest. Using Watchtower definitely helps a lot to expedite this updating process.

Manual Update Dockers

1  Standard Four Steps

  • Stop the container:docker stop <CONTAINER>
  • Delete the container:docker rm <CONTAINER>
  • Update mirror:docker pull <IMAGE>
  • Start the container:docker run <ARG> ... <IMAGE>

2  Simplified Three Steps

  • Delete the container:docker rm <CONTAINER> -f
  • Update mirror:docker pull <IMAGE>
  • Start the container:docker run <ARG> ... <IMAGE>

Use Script to Automatic Update Dockers

We can use a script which checks if a running container is started with the latest image. We also use upstart init scripts for starting the docker image.

#!/usr/bin/env bash
set -e
BASE_IMAGE="registry"
REGISTRY="registry.hub.docker.com"
IMAGE="$REGISTRY/$BASE_IMAGE"
CID=$(docker ps | grep $IMAGE | awk '{print $1}')
docker pull $IMAGE

for im in $CID
do
    LATEST=`docker inspect --format "" $IMAGE`
    RUNNING=`docker inspect --format "" $im`
    NAME=`docker inspect --format '' $im | sed "s/\///g"`
    echo "Latest:" $LATEST
    echo "Running:" $RUNNING
    if [ "$RUNNING" != "$LATEST" ];then
        echo "upgrading $NAME"
        stop docker-$NAME
        docker rm -f $NAME
        start docker-$NAME
    else
        echo "$NAME up to date"
    fi
done

And init looks like

docker run -t -i --name $NAME $im /bin/bash

Introduction of Watchtower

Watchtower is a practical tool that can automatically update the Docker base image and container. It monitors the running container and related mirrors. When it detects that the mirror in the registry is different from the local mirror, it will pull the latest mirror and restart the corresponding container with the same parameters as in the initial deployment.

GitHub Repository: containrrr/watchtower

Documentation Website: https://containrrr.dev/watchtower.

 

[email protected]:/var/run# docker run --rm containrrr/watchtower -h

        Watchtower automatically updates running Docker containers whenever a new image is released.
        More information available at https://github.com/containrrr/watchtower/.

Usage:
  watchtower [flags]

Flags:
  -a, --api-version string                          api version to use by docker client (default "1.25")
  -c, --cleanup                                     remove previously used images after updating
  -d, --debug                                       enable debug mode with verbose logging
      --enable-lifecycle-hooks                      Enable the execution of commands triggered by pre- and post-update lifecycle hooks
  -h, --help                                        help for watchtower
  -H, --host string                                 daemon socket to connect to (default "unix:///var/run/docker.sock")
      --http-api-metrics                            Runs Watchtower with the Prometheus metrics API enabled
      --http-api-token string                       Sets an authentication token to HTTP API requests.
      --http-api-update                             Runs Watchtower in HTTP API mode, so that image updates must to be triggered by a request
      --include-restarting                          Will also include restarting containers
  -S, --include-stopped                             Will also include created and exited containers
  -i, --interval int                                poll interval (in seconds) (default 86400)
  -e, --label-enable                                watch containers where the com.centurylinklabs.watchtower.enable label is true
  -m, --monitor-only                                Will only monitor for new images, not update the containers
      --no-color                                    Disable ANSI color escape codes in log output
      --no-pull                                     do not pull any new images
      --no-restart                                  do not restart any containers
      --no-startup-message                          Prevents watchtower from sending a startup message
      --notification-email-delay int                Delay before sending notifications, expressed in seconds
      --notification-email-from string              Address to send notification emails from
      --notification-email-server string            SMTP server to send notification emails through
      --notification-email-server-password string   SMTP server password for sending notifications
      --notification-email-server-port int          SMTP server port to send notification emails through (default 25)
      --notification-email-server-tls-skip-verify   Controls whether watchtower verifies the SMTP server's certificate chain and host name.
                                                    Should only be used for testing.
      --notification-email-server-user string       SMTP server user for sending notifications
      --notification-email-subjecttag string        Subject prefix tag for notifications via mail
      --notification-email-to string                Address to send notification emails to
      --notification-gotify-tls-skip-verify         Controls whether watchtower verifies the Gotify server's certificate chain and host name.
                                                    Should only be used for testing.
      --notification-gotify-token string            The Gotify Application required to query the Gotify API
      --notification-gotify-url string              The Gotify URL to send notifications to
      --notification-msteams-data                   The MSTeams notifier will try to extract log entry fields as MSTeams message facts
      --notification-msteams-hook string            The MSTeams WebHook URL to send notifications to
      --notification-slack-channel string           A string which overrides the webhook's default channel. Example: #my-custom-channel
      --notification-slack-hook-url string          The Slack Hook URL to send notifications to
      --notification-slack-icon-emoji string        An emoji code string to use in place of the default icon
      --notification-slack-icon-url string          An icon image URL string to use in place of the default icon
      --notification-slack-identifier string        A string which will be used to identify the messages coming from this watchtower instance (default "watchtower")
      --notification-template string                The shoutrrr text/template for the messages
      --notification-url stringArray                The shoutrrr URL to send notifications to
  -n, --notifications strings                        notification types to send (valid: email, slack, msteams, gotify, shoutrrr)
      --notifications-level string                  The log level used for sending notifications. Possible values: panic, fatal, error, warn, info or debug (default "info")
      --remove-volumes                              remove attached volumes before updating
      --revive-stopped                              Will also start stopped containers that were updated, if include-stopped is active
      --rolling-restart                             Restart containers one at a time
  -R, --run-once                                    Run once now and exit
  -s, --schedule string                             the cron expression which defines when to update
      --scope string                                Defines a monitoring scope for the Watchtower instance.
  -t, --stop-timeout duration                       timeout before a container is forcefully stopped (default 10s)
  -v, --tlsverify                                   use TLS and verify the remote
      --trace                                       enable trace mode with very verbose logging - caution, exposes credentials
      --warn-on-head-failure string                 When to warn about HEAD pull requests failing. Possible values: always, auto or never
[email protected]:/var/run#
 

 

Install

 

1  Quick Start from GitHub

From Command line:

$ docker run -d \
    --name watchtower \
    -v /var/run/docker.sock:/var/run/docker.sock \
    containrrr/watchtower
From Portainer:

 

Also make sure restart policy is selected as Unless stopped.

2  Auto Clean Up Old Images option

Official default startup command  can accumulate a lot of old images with tags for none after a long time use.  If left in system, it will take up a lot of disk space. To avoid this, you can add an option --cleanupoption, so each update will clean out the old mirror.

docker run -d \
    --name watchtower \
    --restart unless-stopped \
    -v /var/run/docker.sock:/var/run/docker.sock \
    containrrr/watchtower \
    --cleanup

--cleanupOptions can be abbreviated as -c:

docker run -d \
    --name watchtower \
    --restart unless-stopped \
    -v /var/run/docker.sock:/var/run/docker.sock \
    containrrr/watchtower -c
 

2  Set automatic update check frequency

By default, Watchtower will poll every 24 hours. If you think this frequency is not good for you, you can use the following options to control the frequency of update checks, but you can only choose one of the two.

  • --interval-i-Set the update detection time interval, in seconds. For example, check for updates every 1 hour:
docker run -d \
    --name watchtower \
    --restart unless-stopped \
    -v /var/run/docker.sock:/var/run/docker.sock \
    containrrr/watchtower -c \
    --interval 3600

You can set those options from Portainer’s Command settings textbox.

  • --schedule-s-Set the timing detection update time. The format is a 6-field Cron expression, instead of the traditional 5-field, that is, the first digit is seconds. For example, check for updates at 2 AM every day:
docker run -d \
    --name watchtower \
    --restart unless-stopped \
    -v /var/run/docker.sock:/var/run/docker.sock \
    containrrr/watchtower -c \
    --schedule "0 0 2 * * *"
 

For other options, such as control the list which docker can be upgraded or excluded from upgrading, please check original documentation page.

References

from Blogger http://blog.51sec.org/2021/05/auto-monitor-and-update-docker-image-to.html

By Jon

Leave a Reply