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:

  • Elastic Beanstalk with Docker deployment failure
  • Run shell script inside a container
  • Flannel and docker don't start
  • Kubernetes Volume mountpath
  • Docker volumes binding: container to host
  • 'docker push …' from Bitbucket Pipelines is very slow to my self-hosted docker 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

  • Build ASP.NET Core 1.1 preview4 project in Docker-image microsoft/aspnetcore-build:1.1.0-msbuild
  • Docker container vs Java Virtual Machine
  • Red Hat support for Docker
  • Connecting to Host Postgresql From inside a Container
  • What is the different between putting a separate service discovery and integrate it into the cluster machine in Docker Swarm
  • Docker Mysql (Hibernate) Connection
  • 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.