JDGuide
JDGuide

Reputation: 6525

How to stop docker container automatically?

I am trying to stop the docker container automatically after 1 hour. I mean, if there is no process going on or the container is idle for 1 hour, then stop that container. Is this possible to do it programmatically within the Dockfile? Any thoughts would be helpful.

Thanks in advance.

Upvotes: 2

Views: 2784

Answers (2)

Mihai
Mihai

Reputation: 10727

As far as I know such a scenario is not part of the docker workflow.

The container is alive a long as its main process is alive. When that project (PID: 1) exits (with error or success) then the container also stops.

So the only way I see is to either build this logic inside your program (the main process in the container) or wrap the program in a shell script that kills the process based on some rule (like no log entries for a certain amount of time).

Upvotes: 0

Lukasz Dynowski
Lukasz Dynowski

Reputation: 13630

The closest solution that fits your problem supported by Dockerfile would be HEALTHCHECK directive e.g. HEALTHCHECK [OPTIONS] CMD command . Here you can specify interval (e.g. 1 hour) and time out.

--interval=DURATION (default: 30s)
--timeout=DURATION (default: 30s)
--start-period=DURATION (default: 0s)
--retries=N (default: 3)

Other than that you would have to create custom shell script that is triggered by cronjob every 1 hour. In this script you would stop foreground process and by that stooping the running container.

Upvotes: 3

Related Questions