I'd like to create a cron job that would stop Docker containers if they've been running for more than, say, 2 hours.
I can get the times they started.
$ docker inspect -f '{{ .State.StartedAt }}' $(docker ps -q)
Just need to compare that with 2 hours ago...
$ date --utc --date="-2 hours" +"%Y-%m-%dT%H:%M:%S.%NZ"
...and if it's earlier stop the container
$ docker stop <<container_id>>
How can I do this with a bash script?
It is an old thread but still if someone is searching for an answer. The below command will stop containers running more than 2 hours.
docker ps --format="{{.RunningFor}} {{.Names}}" | grep hours | awk -F: '{if($1>2)print$1}' | awk ' {print $4} ' | xargs docker stop
Explaination:
docker ps --format="{{.RunningFor}} {{.Names}}"
will print the container names and running period.
grep hours
will print the containres running in hours.
awk -F: '{if($1>2)print$1}'
will only print containers running for more than 2 hours.
awk ' {print $4} ' | xargs docker stop
will print the container names obtained from previous output and pass it as argument to stop the containers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With