Watchtower自动升级Docker容器并发送邮件提醒教程

2023年1月23日 877点热度
# 监视容器更新最简范例:
version: "3"
services:
  watchtower:
    image: containrrr/watchtower
    container_name: watchtower
    restart: unless-stopped
    environment: 
        - TZ=Asia/Shanghai
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
    command: nginx portainer-ce next-terminal guacd --cleanup --schedule "0 0 4 * * *"
# 邮件提醒参数:
注:每次启动带邮件参数的Watchtower容器,会立即发送一封基本信息邮件到设置邮箱,若未收到请排错:
        - WATCHTOWER_NOTIFICATION_TITLE_TAG=vpsname
        - WATCHTOWER_NOTIFICATIONS=email
        - WATCHTOWER_NOTIFICATION_EMAIL_FROM=fromaddress@gmail.com
        - WATCHTOWER_NOTIFICATION_EMAIL_TO=toaddress@gmail.com
        - WATCHTOWER_NOTIFICATION_EMAIL_SERVER=smtp.gmail.com
        - WATCHTOWER_NOTIFICATION_EMAIL_SERVER_PORT=587
        - WATCHTOWER_NOTIFICATION_EMAIL_SERVER_USER=fromaddress@gmail.com
        - WATCHTOWER_NOTIFICATION_EMAIL_SERVER_PASSWORD=app_password
        - WATCHTOWER_NOTIFICATION_EMAIL_DELAY=2
# 监视容器更新并发送邮件提醒范例:
version: "3"
services:
  watchtower:
    image: containrrr/watchtower
    container_name: watchtower
    restart: unless-stopped
    environment: 
#        - WATCHTOWER_MONITOR_ONLY=true    #使用此参数则仅提醒有更新而不自动升级容器
        - TZ=Asia/Shanghai
        - WATCHTOWER_NOTIFICATION_TITLE_TAG=vpsname      #邮件标题前缀添加自定义内容
        - WATCHTOWER_NOTIFICATIONS=email
        - WATCHTOWER_NOTIFICATION_EMAIL_FROM=fromaddress@gmail.com
        - WATCHTOWER_NOTIFICATION_EMAIL_TO=toaddress@gmail.com
        - WATCHTOWER_NOTIFICATION_EMAIL_SERVER=smtp.gmail.com
        - WATCHTOWER_NOTIFICATION_EMAIL_SERVER_PORT=587
        - WATCHTOWER_NOTIFICATION_EMAIL_SERVER_USER=fromaddress@gmail.com
        - WATCHTOWER_NOTIFICATION_EMAIL_SERVER_PASSWORD=app_password
        - WATCHTOWER_NOTIFICATION_EMAIL_DELAY=2
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
    command: hello-world freenom nginx portainer-ce next-terminal guacd watchtower --cleanup --schedule "0 33 3 * * *"
#--schedule "0 0 4 * * *" 秒分时日月周、每天早上4点检测
#--schedule "0 */1 * * * *" 每分钟检查一次
前台运行模式,方便查看容器实时日志:docker-compose -f watchtower.yml up    。
检测日志无误后,切换到后台运行模式:docker-compose -f watchtower.yml up -d    。
后台运行时查看日志的方法:docker logs --since 30m watchtower    (输出30分内的容器日志)
# 测试Watchtower是否正确升级旧容器的范例:
#拉取一个旧镜像
docker pull dockercloud/hello-world:staging
#将旧镜像标记为latest镜像
docker tag dockercloud/hello-world:staging dockercloud/hello-world:latest
#运行容器
docker run -d --name hello-world dockercloud/hello-world:latest
#然后等待Watchtower到达计划任务执行时间,会检测到hello-world此时所用的latest标签镜像与服务器上的latest镜像不一致,容器日志中显示信息变化,并收到设置的邮件提醒。

书三拾

不积跬步无以至千里