Autoupdate Script Docker Container

From Master of Neuroscience Wiki

Example for nginx.

You need to adapt:

SERVICE_NAME="nginx"
CONTAINER_NAME="nginx"
IMAGE_NAME="nginx:stable-alpine"
YAML_DIRECTORY_NAME="/docker/compose/"
#!/bin/bash
set -euo pipefail

SERVICE_NAME="nginx"
CONTAINER_NAME="nginx"
IMAGE_NAME="nginx:stable-alpine"
YAML_DIRECTORY_NAME="/docker/compose/"

# Get current image ID (short format)
CURRENT_IMAGE=$(docker inspect --format='{{.Image}}' "${CONTAINER_NAME}" 2>/dev/null | cut -d: -f2 | cut -c1-12) || true

# Pull the latest image
echo "Pulling latest image..."
docker pull "${IMAGE_NAME}"

# Get new image ID (short format)
NEW_IMAGE=$(docker images "${IMAGE_NAME}" --format '{{.ID}}')

echo "Current image: $CURRENT_IMAGE"
echo "Latest image:  $NEW_IMAGE"

# Compare and restart only if different
if [ -z "$CURRENT_IMAGE" ]; then
    echo "Container not found, starting it up..."
    cd "${YAML_DIRECTORY_NAME}"
    docker compose up -d "${SERVICE_NAME}"
elif [ "$CURRENT_IMAGE" != "$NEW_IMAGE" ]; then
    echo "New image detected, restarting container..."
    cd "${YAML_DIRECTORY_NAME}"
    docker compose down "${SERVICE_NAME}"
    docker compose up -d "${SERVICE_NAME}"
    echo "Update completed!"
else
    echo "Already running the latest version, no restart needed."
fi

Make the script executable (chmod 07.... ). Add it to cron (crontab -e ) with the correct path and script name:

0 4 * * * /docker/compose/autoupdate_nginx.sh >> /var/log/nginx-update.log 2>&1