Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

docker hangs on SIGINT when script traps EXIT

Tags:

bash

docker

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.)

like image 815
philo Avatar asked Oct 28 '22 19:10

philo


1 Answers

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

like image 137
sneep Avatar answered Nov 15 '22 14:11

sneep