When I run a script in a docker container, and the script traps EXIT, and I send a Ctrl+C, docker fails to stop the container.
Dockerfile
FROM alpine
RUN apk add --no-cache bash
COPY script.sh /
CMD ./script.sh
script.sh
#!/bin/bash
func() {
echo "exit script"
}
trap func EXIT
echo "script"
sleep 30
To run
$ docker build -t traps .
$ docker run -it traps
After seeing "script" echoed, hit Ctrl+C.
Expected: "exit script" is printed, and the container exits, returning control to my terminal, the same as if there were no EXIT trap.
Actual: "exit script" is printed, but the container is still running and holding onto my terminal.
To complicate matters, if I add a SIGINT trap, things work exactly as I would expect. On hitting Ctrl+C, the SIGINT trap fires first, then the EXIT trap, and then the container exits.
What's going on? And is there any way to make things work without adding a dummy SIGINT trap?
(The reason for using -t
in the first place is to enable Ctrl+C.)
I ran your files and determined that bash entered a 100% CPU state after hitting Ctrl-C. Attaching gdb or strace indicates that it's SIGSEGVing infinitely. If that is the case, you may be able to work around this by changing the shebang to:
#!/bin/bash -i
Or alternatively, the CMD command to:
CMD /bin/bash -i ./script.sh
Maybe look at this for more information: https://github.com/moby/moby/issues/4854
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With