Search code examples
dockerjenkinsjenkins-pipelinedocker-registrydeclarative

Execute command inside docker image and save it in Jenkinsfile


I am working on Jenkins file which is pulling docker image and execute some command inside this docker image then after I want to save this image and push it into AWS ECR. in here execute commands inside a docker container and push the docker image to ECR part is working and have no clue about how to commit(save) updated docker image.

Excute commands inside

stage('Run inside Docker container') {
  agent {
    docker { image 'test/testimage:619c95b' }
  }
  steps {
    sh 'ls & pwd & ps'
  }
}

Save Docker image

???

Push to AWS ECR

steps {
    script {
      docker.withRegistry('https://xxxxxxxxxxx.dkr.ecr.us-east-2.amazonaws.com/', 'ecr:us-east-2:aws-xx-automation') {
        image.push("${env.tag}")
      }
    }
  }

Solution

  • You can build this into a straightforward Dockerfile:

    FROM test/testimage:619c95b  # docker { image ... }
    RUN ls && pwd && ps          # sh "..."
    

    You can test and run the resulting image on your developer system. (I have not had good luck locally testing complex Jenkins pipelines.)

    Now your Jenkins pipeline code can build and push that image:

    steps {
      script {
        image = docker.build("${env.tag}")
        docker.withRegistry('https://xxxxxxxxxxx.dkr.ecr.us-east-2.amazonaws.com/', 'ecr:us-east-2:aws-xx-automation') {
          image.push()
        }
      }
    }
    

    The approach you describe (probably) isn't technically possible. If you look at the Jenkins logs, you'll see a very long docker run command, that (among other things) has a -v option to mount the build workdir into the image on the same path. That means any changes you make within the build workdir aren't able to be committed into an image, they only live within that Jenkins-managed directory.