Cleaning up nicely before container exits

I’ve been attempting various ways to handle docker stop’s SIGTERM to do some cleanup and haven’t found a satisfactory way yet.

Ideally I would be able to have a neat place to put an exit to run something before the container exits.

I’ve tried using bash traps but the trap only seems to run if the script is in a particular state (not execing another process which is what all my containers do, not sleeping etc.) read works, ie the trap catches SIGTERM and I can do cleanup but read is not what my containers are doing obviously. Even if there was a way I would still have to forward the signal on to the process that the container is running to get it to start terminating before SIGKILL smashes up the joint.

I’ve seen others on google use a nanny process (perl/c) to handle SIGTERM, do the cleanup, launch the real process and forward SIGTERM to that process. Surely there is a better way ?

1 Like

We use a nanny process which works perfectly, in fact we run a nanny process for runsvdir

I raised this issue on this topic:

Also, keep in mind, you only have 10 seconds which may or may not be enough.

Thanks sam. Presumably you can collocate the cleanup code in the service dir and get your nanny to run it ? finish is obviously too late for some things which was one of the limitations of runsv I was concerned about.

Then you HUP runsvdir to proceed with runsv termination ?

Thanks again!

Yeah basically this, which works fine from bash

runsvdir wants a HUP not a TERM

also I get a clean shutdown seq by simulating stage 3 in runit.