Customize Consent Preferences

We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.

The cookies that are categorized as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... 

Always Active

Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

No cookies to display.

Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

No cookies to display.

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

No cookies to display.

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

No cookies to display.

Advertisement cookies are used to provide visitors with customized advertisements based on the pages you visited previously and to analyze the effectiveness of the ad campaigns.

No cookies to display.

Watchtower para actualizar automáticamente tus contenedores Docker usando Docker Compose

Tiempo de lectura: 3 minutos

Hola, hoy vamos a ver cómo podemos actualizar automáticamente nuestros contenedores Docker usando Watchtower.

Paso 1: Instalación de Docker y Docker Compose Antes de comenzar, asegúrate de tener Docker y Docker Compose instalados en tu sistema. Puedes seguir las instrucciones oficiales de Docker para instalar estas herramientas en tu sistema operativo.

Paso 2: Crear un archivo de configuración de Docker Compose Crea un archivo llamado docker-compose.yml en el directorio raíz de tu proyecto. Este archivo contendrá la configuración de tus contenedores, incluyendo WatchTower.

Aquí tienes un ejemplo básico de un archivo docker-compose.yml:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
version: "3"
services:
myapp:
image: myapp:latest
restart: always
watchtower:
image: containrrr/watchtower
volumes:
- /var/run/docker.sock:/var/run/docker.sock
restart: always
command: --interval 30
version: "3" services: myapp: image: myapp:latest restart: always watchtower: image: containrrr/watchtower volumes: - /var/run/docker.sock:/var/run/docker.sock restart: always command: --interval 30
version: "3"
services:
  myapp:
    image: myapp:latest
    restart: always

  watchtower:
    image: containrrr/watchtower
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
    restart: always
    command: --interval 30

En este ejemplo, hay dos servicios definidos: myapp y watchtower. El servicio myapp es el contenedor que deseas actualizar, y el servicio watchtower es responsable de monitorear y actualizar el contenedor myapp.

El volumen /var/run/docker.sock se monta en el contenedor de WatchTower para permitir que se comunique con el demonio de Docker en el host.

Paso 3: Configuración adicional de WatchTower Puedes personalizar la configuración de WatchTower agregando más opciones de línea de comando al servicio en el archivo docker-compose.yml. Aquí tienes algunos ejemplos de configuraciones comunes:

  • Actualizar solo contenedores específicos: Si tienes múltiples contenedores en tu proyecto y solo quieres que WatchTower actualice uno en particular, puedes agregar la etiqueta com.centurylinklabs.watchtower.enable=true al contenedor que deseas actualizar. Por ejemplo:yaml
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
version: "3"
services:
myapp:
image: myapp:latest
restart: always
labels:
- com.centurylinklabs.watchtower.enable=true
watchtower:
image: containrrr/watchtower
volumes:
- /var/run/docker.sock:/var/run/docker.sock
restart: always
command: --interval 30
version: "3" services: myapp: image: myapp:latest restart: always labels: - com.centurylinklabs.watchtower.enable=true watchtower: image: containrrr/watchtower volumes: - /var/run/docker.sock:/var/run/docker.sock restart: always command: --interval 30
version: "3"
services:
  myapp:
    image: myapp:latest
    restart: always
    labels:
      - com.centurylinklabs.watchtower.enable=true

  watchtower:
    image: containrrr/watchtower
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
    restart: always
    command: --interval 30

Programar actualizaciones: Puedes configurar WatchTower para que actualice los contenedores en momentos específicos utilizando la opción --schedule. Por ejemplo, para programar una actualización diaria a las 3 a.m., puedes modificar el comando de WatchTower de la siguiente manera:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
watchtower:
image: containrrr/watchtower
volumes:
- /var/run/docker.sock:/var/run/docker.sock
restart: always
command: --interval 30 --schedule "0 3 * * *"
watchtower: image: containrrr/watchtower volumes: - /var/run/docker.sock:/var/run/docker.sock restart: always command: --interval 30 --schedule "0 3 * * *"
watchtower:
  image: containrrr/watchtower
  volumes:
    - /var/run/docker.sock:/var/run/docker.sock
  restart: always
  command: --interval 30 --schedule "0 3 * * *"

Paso 4: Configuración de notificaciones en WatchTower

Para recibir notificaciones cuando WatchTower actualiza un contenedor, puedes seguir estos pasos:

  1. Agrega la siguiente línea al servicio de WatchTower en tu archivo docker-compose.yml:yaml
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
watchtower:
image: containrrr/watchtower
volumes:
- /var/run/docker.sock:/var/run/docker.sock
restart: always
command: --interval 30 --notifications <notificación>
watchtower: image: containrrr/watchtower volumes: - /var/run/docker.sock:/var/run/docker.sock restart: always command: --interval 30 --notifications <notificación>
watchtower:
  image: containrrr/watchtower
  volumes:
    - /var/run/docker.sock:/var/run/docker.sock
  restart: always
  command: --interval 30 --notifications <notificación>

Reemplaza <notificación> con el tipo de notificación que deseas configurar. Algunos ejemplos de tipos de notificación son email, slack, gotify, discord, entre otros. La elección depende de tus preferencias y del servicio de notificación que utilices.

Configura los parámetros específicos de notificación según el tipo seleccionado. Por ejemplo, si eliges enviar notificaciones por correo electrónico, agrega el parámetro --notification-email al servicio de WatchTower. Asegúrate de proporcionar la dirección de correo electrónico correcta.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
watchtower:
image: containrrr/watchtower
volumes:
- /var/run/docker.sock:/var/run/docker.sock
restart: always
command: --interval 30 --notifications email --notification-email tu_correo@ejemplo.com
watchtower: image: containrrr/watchtower volumes: - /var/run/docker.sock:/var/run/docker.sock restart: always command: --interval 30 --notifications email --notification-email tu_correo@ejemplo.com
watchtower:
  image: containrrr/watchtower
  volumes:
    - /var/run/docker.sock:/var/run/docker.sock
  restart: always
  command: --interval 30 --notifications email --notification-email tu_correo@ejemplo.com

Guarda el archivo docker-compose.yml

También podemos generar una notificación usando Discord:

Agrega la siguiente línea al servicio de WatchTower en tu archivo docker-compose.yml:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
watchtower:
image: containrrr/watchtower
volumes:
- /var/run/docker.sock:/var/run/docker.sock
restart: always
command: --interval 30 --notifications discord
watchtower: image: containrrr/watchtower volumes: - /var/run/docker.sock:/var/run/docker.sock restart: always command: --interval 30 --notifications discord
watchtower:
  image: containrrr/watchtower
  volumes:
    - /var/run/docker.sock:/var/run/docker.sock
  restart: always
  command: --interval 30 --notifications discord

Configura los parámetros específicos de notificación para Discord. Agrega los siguientes parámetros al servicio de WatchTower:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
watchtower:
image: containrrr/watchtower
volumes:
- /var/run/docker.sock:/var/run/docker.sock
restart: always
environment:
WATCHTOWER_NOTIFICATIONS: slack
WATCHTOWER_NOTIFICATION_SLACK_HOOK_URL: <discord_webhook>/slack
WATCHTOWER_NOTIFICATION_TEMPLATE: |
{{- if .Report -}}
{{- with .Report -}}
{{len .Scanned}} Scanned, {{len .Updated}} Updated, {{len .Failed}} Failed
{{- range .Updated}}
- {{.Name}} ({{.ImageName}}): {{.CurrentImageID.ShortID}} updated to {{.LatestImageID.ShortID}}
{{- end -}}
{{- range .Fresh}}
- {{.Name}} ({{.ImageName}}): {{.State}}
{{- end -}}
{{- range .Skipped}}
- {{.Name}} ({{.ImageName}}): {{.State}}: {{.Error}}
{{- end -}}
{{- range .Failed}}
- {{.Name}} ({{.ImageName}}): {{.State}}: {{.Error}}
{{- end -}}
{{- end -}}
{{- else -}}
{{range .Entries -}}{{.Message}}{{"\n"}}{{- end -}}
{{- end -}}
command: notify-upgrade
watchtower: image: containrrr/watchtower volumes: - /var/run/docker.sock:/var/run/docker.sock restart: always environment: WATCHTOWER_NOTIFICATIONS: slack WATCHTOWER_NOTIFICATION_SLACK_HOOK_URL: <discord_webhook>/slack WATCHTOWER_NOTIFICATION_TEMPLATE: | {{- if .Report -}} {{- with .Report -}} {{len .Scanned}} Scanned, {{len .Updated}} Updated, {{len .Failed}} Failed {{- range .Updated}} - {{.Name}} ({{.ImageName}}): {{.CurrentImageID.ShortID}} updated to {{.LatestImageID.ShortID}} {{- end -}} {{- range .Fresh}} - {{.Name}} ({{.ImageName}}): {{.State}} {{- end -}} {{- range .Skipped}} - {{.Name}} ({{.ImageName}}): {{.State}}: {{.Error}} {{- end -}} {{- range .Failed}} - {{.Name}} ({{.ImageName}}): {{.State}}: {{.Error}} {{- end -}} {{- end -}} {{- else -}} {{range .Entries -}}{{.Message}}{{"\n"}}{{- end -}} {{- end -}} command: notify-upgrade
watchtower:
  image: containrrr/watchtower
  volumes:
    - /var/run/docker.sock:/var/run/docker.sock
  restart: always
      environment:
      WATCHTOWER_NOTIFICATIONS: slack
      WATCHTOWER_NOTIFICATION_SLACK_HOOK_URL: <discord_webhook>/slack
      WATCHTOWER_NOTIFICATION_TEMPLATE: |
        {{- if .Report -}}
          {{- with .Report -}}
        {{len .Scanned}} Scanned, {{len .Updated}} Updated, {{len .Failed}} Failed
              {{- range .Updated}}
        - {{.Name}} ({{.ImageName}}): {{.CurrentImageID.ShortID}} updated to {{.LatestImageID.ShortID}}
              {{- end -}}
              {{- range .Fresh}}
        - {{.Name}} ({{.ImageName}}): {{.State}}
            {{- end -}}
            {{- range .Skipped}}
        - {{.Name}} ({{.ImageName}}): {{.State}}: {{.Error}}
            {{- end -}}
            {{- range .Failed}}
        - {{.Name}} ({{.ImageName}}): {{.State}}: {{.Error}}
            {{- end -}}
          {{- end -}}
        {{- else -}}
          {{range .Entries -}}{{.Message}}{{"\n"}}{{- end -}}
        {{- end -}}
    command: notify-upgrade

Reemplaza <URL_WEBHOOK_DISCORD> con la URL del webhook de Discord al que deseas enviar las notificaciones. Para obtener la URL del webhook, debes crear un webhook en tu servidor de Discord.

Guarda el archivo docker-compose.yml.

Paso 5: Ejecutar el tutorial

Una vez que hayas configurado el archivo docker-compose.yml con las opciones de WatchTower y las notificaciones deseadas, puedes ejecutar el tutorial siguiendo estos pasos:

  1. Abre una terminal y navega hasta el directorio donde se encuentra el archivo docker-compose.yml.
  2. Ejecuta el siguiente comando para iniciar los contenedores:bash
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
docker-compose up -d
docker-compose up -d
docker-compose up -d

Esto creará y ejecutará los contenedores definidos en el archivo docker-compose.yml.

WatchTower ahora monitoreará tus contenedores y los actualizará según la configuración establecida. Si hay actualizaciones disponibles, recibirás notificaciones según la configuración de notificación que hayas definido.

1

Deja un comentario