shelldockerkill-process

How to fix ctrl+c inside a docker container


If I connect to a docker container

$> docker exec -it my_container zsh

and inside it I want to kill something I started with ctrl+c I noticed that it takes forever to complete. I've googled around and it seems that ctrl+c works a bit different than you would expect. My question, how can I fix ctrl+c inside a container ?


Solution

  • The problem is that Ctrl-C sends a signal to the top-level process inside the container, but that process doesn't necessarily react as you would expect. The top-level process has ID 1 inside the container, which means that it doesn't get the default signal handlers that processes usually have. If the top-level process is a shell, then it can receive the signal through its own handler, but doesn't forward it to the command that is executed within the shell. Details are explained here. In both cases, the docker container acts as if it simply ignores Ctrl-C.

    Starting with docker 0.6.5, you can add -t to the docker run command, which will attach a pseudo-TTY. Then you can type Control-C to detach from the container without terminating it.

    If you use -t and -i then Control-C will terminate the container. When using -i with -t then you have to use Control-P Control-Q to detach without terminating.

    Test 1:

    $ ID=$(sudo docker run -t -d ubuntu /usr/bin/top -b)
    $ sudo docker attach $ID
    Control-P Control-Q
    $ sudo docker ps
    

    The container is still listed.

    Test 2:

    $ ID=$(sudo docker run -t -i -d ubuntu /usr/bin/top -b)
    $ sudo docker attach $ID
    Control-C
    $ sudo docker ps
    

    the container is not there (it has been terminated). If you type Control-P Control-Q instead of Control-C in the 2nd example, the container would still be running.

    Wrap the program with a docker-entrypoint.sh bash script that blocks the container process and is able to catch ctrl-c. This bash example might help: https://rimuhosting.com/knowledgebase/linux/misc/trapping-ctrl-c-in-bash

    #!/bin/bash
    
    # trap ctrl-c and call ctrl_c()
    trap ctrl_c INT
    
    function ctrl_c() {
            echo "** Trapped CTRL-C"
    }
    
    for i in `seq 1 5`; do
        sleep 1
        echo -n "."
    done