How to send signal to program run in a docker container?

  • docker kill used to send signal to main container process i.e process with PID 1.
  • Any application with PID 1 can handle signals directly. Below command kill the main docker process: $ docker kill --signal="SIGTERM" container-id/name
  • But application which does not have PID 1 i.e application is background process:
    • We can not send single directly to any background process running within docker container.
    • In this case we need to trap and handle the user defined signal in the shell script running as entry point.
  • Let's we have the following Dockerfile. (Update it as per the application)

FROM centos:6.7
# Install/Deploye the service below.

# Copy the shell script.
COPY entrypoint.sh /home
EXPOSE 8080
ENTRYPOINT ["/home/entrypoint.sh"]

  • Below is the entrypoint.sh. (Update it it as per the application). Suppose we wants to restart a init.d service.

    #start the service
    /etc/init.d/<servicename> start
    pid="$!"
    
    # SIGUSR1- Single handler
    my_handler() {
        /etc/init.d/<servicename> restart
    }
    
    # Trap and handle the user defind singnal.
    trap 'my_handler' SIGUSR1
    
    # wait forever(Alive container.)
    while true
    do
        tail -f /dev/null & wait ${!}
    done
    
  • Build the docker image and run the container.
  • Now you can restart the service from Host machine: $docker kill --signal="SIGUSR1" container-id/name

You can use docker kill --signal="<signal>" <container name or id> to send any signal to the root process of a given container.

See https://docs.docker.com/engine/reference/commandline/kill/#send-a-custom-signal--to-a-container


You can use nsenter to get into your container space and send your signal.

PID=$(docker inspect --format {{.State.Pid}} <container_name_or_ID>)
nsenter --target $PID --mount --uts --ipc --net --pid kill -SIGINT <PID of your program inside your container>

More info : http://jpetazzo.github.io/2014/06/23/docker-ssh-considered-evil/