Docker – How to kill a process that the container was started with

docker

I have a container in which I'd like to kill a process that was used to start the container. The last line of the Dockerfile is CMD ["python", "app.py"]

My reason for doing this instead of just stopping the container is that I want to kill the process, exec bash into the container, change some files, and then start the process again. If I kill the entire container then I have no way to bash in and change the files.

If there is a better way to achieve what I'm after then I'd prefer that. I am new to docker so I might be missing something.

This is what I've done, which does not work.

➜  $ docker top mycontainer
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                1447                1226                0                   01:21               ?                   00:00:04            python app.py

➜  $ docker exec -it mycontainer ps -aux
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  0.5 20.6 1225304 210344 ?      Ssl  01:21   0:04 python app.py
root        61  0.0  0.2  15572  2208 ?        Rs+  01:35   0:00 ps -aux

➜  $ docker exec -it mycontainer kill -9 1
➜  $ docker top mycontainer
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                1447                1226                0                   01:21               ?                   00:00:04            python app.py

Best Answer

I had a similar issue. I was unable to kill process 1. So I had to run another process first. I chose to use a bash process, with a restart loop.

I am using Docker-compose so my container's command file ended up looking like something like this:

bash -c "echo 'Starting'; while true; do python -u app.py; sleep 4; echo 'restarting'; done"

Similar is possible when using Docker directly.

Related Topic