Home > OS >  How can I kill my docker container from the running python script?
How can I kill my docker container from the running python script?

Time:09-08

I am running a docker where there's a python script running. At some moment, in my python script I will want to kill the parent docker running this python script. How can I kill it from this python script?

Dockerfile:

FROM python:3.9.13

# Variable arguments
ENV AM_I_IN_A_DOCKER_CONTAINER True
WORKDIR /code

#Install requirements
COPY ./requirements.txt /code/requirements.txt
RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt

#Copy code into the container
COPY ./example/ /code/example/


#Start the app
CMD ["python", "example/example.py"]

Docker is running from an AWS task.

Example.py:

import threading
import time 

def start_worker():
    #do some stuff
    time.sleep(10)
    print("WE ARE EXITING")
    print("EXIT")
    exit()
        
ce = threading.Thread(target=start_worker)
ce.start()

CodePudding user response:

In your example you basically need to send SIGTERM or SIGKILL to the thread's process. Which is possible by the following code:

import os
import signal

os.kill(os.getppid(), signal.SIGTERM)

In order to stop the container regardles if the thread's process is the first container's process (in your example executed by: CMD ["python", "example/example.py"]), you just need to kill process with PID 1. Which is possible by the following code:

import signal
pid = 1
os.kill(pid, signal.SIGTERM)

Inspired by link

  • Related