Best way to stop Docker container in Jenkins

I have a CI-server (jenkins) which is building new Docker images.
Now I want to run a new Docker container when the build is succesful.
But therefor I have to stop the previous running container.

What’s the best way to perform this?
localhost:5000/test/myapp:"${BUILD_ID} is the name of my new images. So I’m using the build-id as tag. First I thought to perform:

  • Docker image corruption? Remove layers?
  • Multiple instance application in docker
  • Is it possible to have a private/internal docker repository?
  • how to mount volume in ElasticBeanstalk Docker container using only Dockerrun.aws.json
  • docker 1.12 swarm : Does Swarm have a configuration store like kubernetes configMap
  • Docker: how to automatically accept “Do you really want to push to public registry?”
  • docker stop localhost:5000/dbm/my-php-app:${BUILD_ID-1}
    

    But this isn’t a right solution because when a build would fail, this would be wrong.

    Build 1: succes -> run container 1 
    Build 2: failed -> run container 1
    Build 3: succes -> stop container (3-1) =2 --> wrong (isn't running)
    

    What could be a solution? Proposals where I have to change the tag-idea are also welcome

  • Docker on Windows Server 2016 & microsoft-build-tools
  • docker tomcat directory not found?
  • Vaultier is unusable for docker/ubuntu/debian (Python)
  • Location of docker images downloaded by Docker (1.9.1) on Mac OS X
  • How to make Docker container accessible to other network machines through IP?
  • How to write parameterized Bash alias for Docker command
  • 2 Solutions collect form web for “Best way to stop Docker container in Jenkins”

    The docker stop command takes a docker container name as parameter, not a docker image ID.

    You would have to name your container when you run it:

    # build the new image
    docker build -t localhost:5000/test/myapp:"${BUILD_ID}" .
    
    # remove the existing container
    docker rm -f myjob && echo "container myjob removed" || echo "container myjob does not exist"
    
    # create and run a new container
    docker run -d --name myjob localhost:5000/test/myapp:"${BUILD_ID}"
    

    Just replace myjob with a better suited name in this example.

    Thanks to @Thomasleveil I found the answer on my question:

    # build the new image
    docker build -t localhost:5000/test/myapp:"${BUILD_ID}" .
    
    
    # remove old container
    SUCCESS_BUILD=`wget -qO- http://jenkins_url:8080/job/jobname/lastSuccessfulBuild/buildNumber`
    
    docker rm -f "${SUCCESS_BUILD}" && echo "container ${SUCCESS_BUILD} removed" || echo "container ${SUCCESS_BUILD} does not exist"
    
    # run new container
    docker run -d -p 80:80 --name "${BUILD_ID}" localhost:5000/test/myapp:${version}
    
    Docker will be the best open platform for developers and sysadmins to build, ship, and run distributed applications.