skip to Main Content

I am building a simple Jenkins pipeline, but when I push the deployment from git is said that the port is already used and I need to stop the running one.

I can’t get the container ID

stage("Deploy ") {
            steps{
                script {
                    
                    def dockerCmd = 'sudo docker run -p 8080:8080 -d --init biloocabba/kncare-app:1.0'
                    sshagent(['ec2-server-key']) {
                        sh "ssh -o StrictHostKeyChecking=no [email protected]  ${dockerCmd}"
                    
                    }
                }
            }

        }

2

Answers


  1. You can run script with something like this in Jenkinsfile (here I save the script with name stopByPort.sh)

    #!/usr/bin/env bash
    
    for id in $(docker ps -q)
    do
        if [[ $(docker port "${id}") == *"${1}"* ]]; then
            echo "stopping container ${id}"
            docker stop "${id}"
        fi
    done
    

    Execute:
    stopByPort.sh 8080

    Link references:
    https://stackoverflow.com/a/56953427/14312225

    Login or Signup to reply.
  2. When your Jenkinsfile runs, you probably still have a running container with that name, blocking the same resources that you want to use.

    So before you docker run the next container, you need to stop the existing one and remove it:

    docker stop <containername>; docker rm <containername>
    

    To be able to do that, you need to have a fixed name for your container rather than some randomly generated one. The name needs to be set like

    docker run --name mycontainer ...
    

    so later you can use

    docker stop mycontainer; docker rm mycontainer
    

    In your pipeline the combination will look the other way round:

    docker stop mycontainer; docker rm mycontainer
    docker run --name mycontainer ...
    

    But be aware when running the new container you need to issue the exact command you used when running the old container. Plus you run into issues if mycontainer is not running at the time of the build. To prevent that there is another way.

    Once your pipeline pushes the updated container to the registry, invoke a single run of Watchtower and that one will automatically update the container if a newer image is available.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search