Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy file from docker image to jenkins workspace

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

        }
    }
like image 957
cdm Avatar asked Sep 19 '17 18:09

cdm


People also ask

How do I copy a file from a Docker container?

Obtain the name or id of the Docker container. Issue the docker cp command and reference the container name or id. The first parameter of the docker copy command is the path to the file inside the container. The second parameter of the docker copy command is the location to save the file on the host.

How do I integrate a Docker file with Jenkins?

Go to Manage Jenkins -> Plugins -> Available and type “docker” into the field. Select “Docker plugin” and install it. Jenkins refers to the Docker plugin as a “cloud.” Click Manage Jenkins once again, and now click the Manage Clouds and Nodes button in the middle. Now click Configure Clouds on the left.


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
"""
like image 162
Larry Cai Avatar answered Oct 26 '22 02:10

Larry Cai


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'
        }
    }
like image 32
Datageek Avatar answered Oct 26 '22 02:10

Datageek