Rajasekar
Rajasekar

Reputation: 129

Is it possible to delete running container automatically after 1 day?

I have created my own linux container and its in running state. I want to delete the running container after one day automatically.

Is there anyway to delete the container automatically?

If it's possible, Where do I have to add script/code in my Dockerfile?

Upvotes: 3

Views: 1095

Answers (2)

BMitch
BMitch

Reputation: 264831

There's no built in feature that does this explicitly. However you can hack up a solution in several places.


Inside the container, you can have an entrypoint that runs:

#!/bin/sh
( sleep 86400 && kill 1 && sleep 10 && kill -9 1 )&
exec "$@"

That runs a subshell in the background that will sleep for a day, send a SIGTERM, give the process 10 seconds to gracefully exit, and then send a SIGKILL. The exec at the end then runs your CMD as pid 1.


You can hijack the healthcheck to kill pid 1 after a day. You can either work with timeouts on the when the healthcheck runs, or look at the process start time with a ps command if you need a regular healthcheck for other purposes.


Outside of the container, you can run a script, possibly in cron, that checks the output of docker ps, greps for "Up .* days", and selectively runs a docker rm -f on matching lines. I'd recommend scripting this up using the --format option for docker ps and using labels on containers to limit which containers you perform this action.

Upvotes: 3

sanath meti
sanath meti

Reputation: 6603

I had this requirement earlier and I used sleep 86400 in script file like

service apache2 start && sleep 86400 in bash script , which runs for 1day.

Else you can go through this thread which explained

stop and delete docker container if its running

Upvotes: 0

Related Questions