How to automate docker prune commands using crontab



  • Can someone help me on how to clean up containers and images which are 3 months older automatically by using crontab scheduling? Which type of method need to use for automation? I have manually tried deleting by using below commands and it worked but I need to automate it, to perform action for every 3 months without manual action.

    docker image prune  --force --filter “until=2020-01-01T00:00:00”
    docker container prune  --force --filter “until=2020-01-01T00:00:00”
    


  • You can add a new cron entry by prompting:

    sudo crontab -e

    You can then edit the file with your command and its frequency. Every three months is not a standard cron frequency (i.e. there's no built-in solution to transcribe this into cron) so you can use these frequencies:

    30 03 01 Jan,Apr,Jul,Oct *

    or else

    30 03 01 */3 *

    (Based on https://serverfault.com/a/129636/432407 by Richard Holloway on ServerFault)

    So eventually your cron entry will look like:

    30 03 01 Jan,Apr,Jul,Oct * docker image prune  --force --filter “until=2020-01-01T00:00:00”

    You can check out your new entry by prompting:

    sudo crontab -l

    Edit

    chicks's comment pointed out that the goal wasn't to automate an action to be performed every three months but rather to automatically find which objects are older than months. So guessing that you would like to perform this action everyday, I would rather go for:

    0 0 3 * * find /var/lib/docker -type f -ctime +90 -delete

    This finds all Docker files older than three months and deletes them every day at 3AM.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2