6

I need to run a command

 docker ps -a 

which says lists:

id    name   time
1      abc    6 weeks ago

To kill we need to fire the command:

docker kill id

I need to find all ids and run the kill command on each id which is older than 1 day. How can I do that?

1 Answer 1

11

Some docker commands provide the possibility to adjust the output format using go template. Thus, we can use that mechanism to get the start time of the running containers that is easier to process.

For example:

docker ps --format='{{.ID}}' \
  | xargs -n 1 -r docker inspect \
                           -f '{{.ID}} {{.State.Running}} {{.State.StartedAt}}' \
  | awk '$2 == "true" && $3 <= "'$(date -d 'yesterday' -Ins --utc \
                                     | sed 's/+0000/Z/')'" { print $1 }' \
  | xargs -r docker kill

We assume GNU xargs here - the -r option instruct xargs to only execute the command if there is at least one argument. We also rely on GNU date - the objective is to get yesterdays date+time - in ISO format with Zulu time suffix - such that it is compatible with the internal docker date format. Thus, both dates can be compared using normal string comparison, because the lexcicographic ordering of that date format matches the date ordering.

The ps docker command doesn't have the -a option set because by default, docker ps only shows the running containers - and we only need to look at the running ones for killing.

If you have an docker command alias defined (e.g. alias docker='sudo /usr/bin/docker') you have to replace docker with sudo /usr/bin/docker in that pipe.

2
  • Thanks a lot, that's exactly what I was searching for! I've injected the code into this script to easily search by age
    – weshouman
    Jan 24, 2020 at 11:11
  • If your timezone is not set to UTC, you need to remove the --utc flag from date or this won't work.
    – Mani
    Jun 10, 2021 at 10:36

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .