Search code examples
dockercontainerskill

How to kill a specific docker container in a single command


i've setup a jenkins pipeline job in a groovy script....

i am trying to build the jenkins job which runs a docker command on remote server. my jenkins is expected to connect to remote server and perform

       docker run -d -p 60:80 <image name>
  

so for that i have used the following groovy script in jenkins pipeline job

     stage ('Deploy on App Server')
     {
         def dockrun = 'docker run -d -p 60:80 <image name>'
         sshagent(['dev-servr-crdntls'])
         {
             sh "ssh -o StrictHostKeyChecking=no ubuntu@xx.xxx.xx.xx ${dockrun}" 
         }
     }

This scripts runs perfectly fine. Jenkins is connecting to remote server and running the docker command and app is running on port 60.

HOWEVER as this is in jenkins pipeline for CICD, next time when the Build is run job is getting failed because port 60 is already assigned. .

I want to kill the port 60 before running the docker run -d -p ......command. Any suggestions please


Solution

  • You could use the following command to kill the running container that occupies a given port:

    docker kill $(docker ps -qf expose=<port>)
    

    Explanation: The docker ps command allows to list containers and has a lot of useful options. One of them is the -f flag for filtering for containers based on some properties. Now you could filter for the running container that occupies <port> by using -f expose=<port>. In addition, the -q flag can be used to only output the container ID. This output can be used as input to the docker kill command.

    Edit: Because the command mentioned above could potentially fail with an error if no container is running on the given port, the following command can be used to circumvent this problem:

    docker kill $(docker ps -qf expose=<port>) 2> /dev/null || echo 'No container running on port <port>'
    

    Now, the command will either kill the container occupying <port> if such container exists and is running, or output No container running on port <port> (optional)