Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to kill process inside container? Docker top command

I have simple example from official guide at docker website.

I run the following:

sudo docker run -d ubuntu:latest /bin/sh -c "while true; do echo hello world; sleep 1; done"
a66asdasdhqie123...

Then take some output from created container:

sudo docker logs a66
hello
hello
hello
...

Then I lookup the running processes of a container:

sudo docker top a66
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                25055               15152               0                   20:07               ?                   00:00:00            /bin/sh -c while true; do echo hello world; sleep 1; done
root                25295               25055               0                   20:10               ?                   00:00:00            sleep 1

Next I try to kill the first process of container:

sudo docker exec a66 kill -9 25055

However after I make it nothing changes. Process still works and output "hello" every second. What do I wrong?

like image 929
Timur Fayzrakhmanov Avatar asked Jan 03 '15 17:01

Timur Fayzrakhmanov


People also ask

How do I kill a process in docker container?

The docker kill subcommand kills one or more containers. The main process inside the container is sent SIGKILL signal (default), or the signal that is specified with the --signal option. You can reference a container by its ID, ID-prefix, or name.

How do you stop a command in docker containers?

When we try to run /bin/sh on a stopped container using docker exec , Docker will throw a No such container error. We have to transform the stopped Docker container into a new Docker image before we can inspect the internals of the container. We can transform a container into a Docker image using the commit command.


2 Answers

When I reproduce your situation I see different PIDs between docker top <container> and docker exec -it <container> ps -aux. When you do docker exec the command is executed inside the container => should use container's pid. Otherwise you could do the kill without docker straight from the host, in your case: sudo kill -9 25055.

like image 50
Mykola Gurov Avatar answered Nov 09 '22 02:11

Mykola Gurov


check this:

ps | grep -i a66 | tr -s ' '|cut -f2 -d' '|
{
    while read line;
    do kill -9 $line;
    done
}

to understand this start from executing commands from left till end of each pipe (|)

Simpler option:

kill $(pidof a66) 
like image 32
Ganesh Kamath - 'Code Frenzy' Avatar answered Nov 09 '22 02:11

Ganesh Kamath - 'Code Frenzy'