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
}
}
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.
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.
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'
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With