lebesgue.yu
lebesgue.yu

Reputation: 11

how to detach a infinite sleep docker gracefully and why

1) I run following command to start a container:

docker run -d ubuntu /bin/bash -c 'while true; do echo hello world; sleep 1; done;'

2) I attach to it using the following command.

docker attach xxxx

3) I cannot detach it using ctrl +c or ctrl +p ctrl+q sequence.

I wonder how to quit it and why ctrl + c doesn't work. Thank you.

Upvotes: 1

Views: 1443

Answers (1)

b0gusb
b0gusb

Reputation: 4701

The bash script is the main process in the container and it has PID 1. As explained in the docs the process with PID 1 is treated differently than other processes:

A process running as PID 1 inside a container is treated specially by Linux: it ignores any signal with the default action. So, the process will not terminate on SIGINT or SIGTERM unless it is coded to do so.

It means that the script should trap the signals and do something with them. To make it quit declare a trap:

docker run -d ubuntu /bin/bash -c 'trap exit INT TERM; while true; do echo hello world; sleep 1; done;'

Keep in mind that bash will not handle any signals until the foreground process terminates (in this case sleep). Therefore there will be a delay depending on the sleep interval and the moment you press CTRL+C. To exit immediately, sleep should be made interruptible (see sleep, wait and Ctrl+C propagation):

docker run -d ubuntu /bin/bash -c 'trap exit INT TERM; while true; do echo hello world; sleep 1 & wait; done;'

The container is run with the -d flag. You cannot detach unless you run it with -it.

If the container was run with -i and -t, you can detach from a container and leave it running using the CTRL-p CTRL-q key sequence

.

Upvotes: 1

Related Questions