Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop a Docker container that's been running for a certain amount of time

Tags:

bash

docker

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?

like image 651
Adrienne Dunham Avatar asked Oct 18 '25 12:10

Adrienne Dunham


1 Answers

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.

like image 62
Siru Avatar answered Oct 21 '25 01:10

Siru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!