Copy file from docker image to jenkins workspace

Viewed 25649

I have a jenkinsfile that uses a dockerfile - and am interested in how I can copy a file from the docker image to the jenkins workspace. Specifically - I am generating an HTML report on the docker image that I'd like to have published by the jenkins job.

For example, if I generate a file called test.html in the /app/ directory of the docker image - how do I copy it to the jenkins workspace so I can publish it.

Sample Jenkinsfile below:

node ('ondemand') {
    try {
        stage "build"
        checkout scm
        def customImage = docker.build("docker-image:${env.BUILD_ID}", "-f ./docker-image/Dockerfile .")

        stage "test copying files"
        customImage.inside('-u root') {
            sh 'touch /app/test.html && ls' // can see that test.html is generated

        }
    }
2 Answers

As docker cp is not supported in docker plugin for pipeline, there are two ways to do it.

Solution 1 : volume mapping -v when starting instance

customImage.inside('-v $WORKSPACE:/output -u root') {
    sh 'touch /app/test.html && ls' // can see that test.html is generated
}
archiveArtifacts artifacts: '*.html'

see complete Jenkinsfile

Solution 2: Use traditional docker command in shell (not verified)

sh """
docker run --name sample -d -u root docker-image:${env.BUILD_ID} 'touch /app/test.html'
docker cp sample:/app/test.html .
docker rm -f sample
"""

Another alternative is to bind the workspace folder to the container using docker volume option (-v /path/build:/app/build)

Example:

node ('ondemand') {
    try {
        stage "build"
        checkout scm
        def customImage = docker.build("docker-image:${env.BUILD_ID}", "-f ./docker-image/Dockerfile .")

        stage "test copying files"
        customImage.inside('-u root -v /path/build:/app/build') {
            sh 'touch /app/build/test.html'
        }
    }
Related