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
You can run script with something like this in
Jenkinsfile
(here I save the script with name stopByPort.sh)Execute:
stopByPort.sh 8080
Link references:
https://stackoverflow.com/a/56953427/14312225
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: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
so later you can use
In your pipeline the combination will look the other way round:
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.