Kill docker container created more than x days ago

I would like to kill all running docker containers older than 7 days. I could not find a way to easily filter by creation date. There is a before filter to docker ps but it only takes another container's id, see documentation: https://docs.docker.com/engine/reference/commandline/ps/#filtering

Upvotes: 3

Views: 1788

Answers (1)

chash
chash

Reputation: 4433

I know of no way to filter by creation date, but you can do some post-processing in the shell or some other scripting language. For example:

docker ps -f status=running --format "{{.ID}} {{.CreatedAt}}" | while read id cdate ctime _; do if [[ $(date +'%s' -d "${cdate} ${ctime}") -lt $(date +'%s' -d '7 days ago') ]]; then docker kill $id; fi; done

here is the same code refactored to try to be more human readable:

docker ps -f status=running --format "{{.ID}} {{.CreatedAt}}" \
| while read id cdate ctime _; do
    if [[ $(date +'%s' -d "${cdate} ${ctime}") -lt $(date +'%s' -d '7 days ago') ]]; then
        docker kill $id
    fi
done

note: the prune commands support filtering on until but the docker container ls --filter errors out if you try to pass in any until=5m for the filter parameter.

Upvotes: 11

Related Questions