How to run builds in Docker containers from Jenkins

dockerJenkinsptytty

I am trying to use Jenkins to build a C++ project in a Docker container. I have no problem building in Jenkins, or building in a container outside of Jenkins.

Below is what I tried. I am omitting the volumes mapping for clarity.

Case 1

The following command successfully runs a build in a shell.

docker run --rm --interactive=true --tty=true $IMAGE make

However when run in Jenkins as an "execute shell" step Docker returns the following error.

cannot enable tty mode on non tty input

Case 2

The following command is similar to the previous one but disables interactivity.

docker run --rm $IMAGE make

Jenkins can run a build successfully. However there are serious issues when aborting a build. The build is immediately marked as aborted but the container keeps running until the build completes. Also the container is not removed after exiting.

When run in a shell the command builds successfully but it is not possible to interrupt it. Also the container is removed after exiting.

Question

Would anyone know how to cleanly run builds in Docker containers from Jenkins and retain the capability to abort builds?

Using any of the Jenkins plugins is not an option because the Docker calls are inside scripts and cannot be extracted easily.

Best Answer

The easiest way to run your docker builds in Jenkins is to use the pipeline job. It has got a lot of inbuilt plugins that could control your Docker environment and containers.

a few examples are

    docker.image("image-name").run() -Runs the container from the image 
    docker.image("image-name").inside(){//your commands} -Runs your commands inside the docker container and also removes your container as soon as your commands are executed.

For more info: https://www.cloudbees.com/blog/orchestrating-workflows-jenkins-and-docker

Related Question