Run Script on Docker Container Stop/Terminate – CMS/LMS

I would completely de-correlate log collection and image building. I suggest running a script on the host. For instance:

import json
import docker  # pip install docker


def main():
    client = docker.from_env()
    for event in client.events(decode=True):
        if event.get("status") == "stop":
            attributes = event.get("Actor", {}).get("Attributes", {})
            if (
                attributes.get("com.docker.compose.project.working_dir")
                == "/home/regis/.local/share/tutor/env/local"
                and attributes.get("com.docker.compose.service") == "lms"
            ):
                print("lms stopped: ", event)


if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        pass

You can even run this script in a container if you bind-mount /var/run/docker.sock.

1 Like