1

I've got a simple Python process running in a Docker container:

Dockerfile:

FROM ubuntu:18.04
RUN apt -y update && apt -y install python3
COPY app.py /app/
WORKDIR /app
ENTRYPOINT ["./app.py"]

app.py:

#!/usr/bin/env python3

if __name__ == '__main__':
    while True:
        pass

It runs just fine. However, I've noticed that the process is unaffected by SIGTERM. I.e.,

# In container
kill -s TERM `pgrep python3`

doesn't do anything. However,

kill -s INT `pgrep python3`

raises a KeyboardInterrupt in the process as expected.

I ran

grep Sig /proc/`pgrep python3`/status

in the container and got

SigQ:   1/127222
SigPnd: 0000000000000000
SigBlk: 0000000000000000
SigIgn: 0000000001001000
SigCgt: 0000000180000002

SIGTERM is 15 so why isn't it going through? If I run the Python script in my host (also Ubuntu), SIGTERM kills it as expected.

1 Answer 1

1

Because Docker containers have no init process, the Python process is running at PID 1. According to man 2 kill,

The only signals that can be sent to process ID 1, the init process, are those for which init has explicitly installed signal handlers. This is done to assure the system is not brought down accidentally.

The reason why SIGINT works is because Python registers a handler for that signal. So, you can do something similar:

#!/usr/bin/env python3

import signal

def handler(signum, frame):
    print('Exiting')
    exit(0)

if __name__ == '__main__':
    signal.signal(signal.SIGTERM, handler)
    while True:
        pass

Alternatively, you can tell Docker to run the container with an init process:

docker run -it --init my_image

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .