dockerjenkinsdocker-composejenkins-pipelinedocker-tag

tagging docker images with Jenkins pipeline parameter


I am trying to tag my docker image`. I am using Jenkins to do that for me by declaring a string parameter.

In the docker-compose.yml file I have my image like so:

image: api:"${version}"

I get an error saying the tag is incorrect.

In my Jenkins pipeline I have a string parameter named version with default LATEST. However, I want to be able to enter v1 or v2 which will be used as an image tag.

I am doing it using blue-green deployment.


Solution

  • You can set the VERSION in the environment for the build using withEnv in your pipeline, for example:

    # Jenkinsfile
    ---
    stage('build'){
        node('vagrant'){
            withEnv([
               'VERSION=0.1'
            ]){
                git_checkout()
                dir('app'){
                    ansiColor('xterm') {
                        sh 'mvn clean install'
                    }
                }
                // build docker image with version
                sh 'docker build --rm -t app:${VERSION} .'
            }
        }
    }
    
    def git_checkout(){
        checkout([
            $class: 'GitSCM',
            branches: [[name: '*/' + env.BRANCH_NAME]],
            doGenerateSubmoduleConfigurations: false,
            extensions: [
                [$class: 'SubmoduleOption', disableSubmodules: false, parentCredentials: true, recursiveSubmodules: false, reference: '', trackingSubmodules: true],
                [$class: 'AuthorInChangelog'],
                [$class: 'CloneOption', depth: 0, noTags: false, reference: '', shallow: false]
            ],
            submoduleCfg: [],
            userRemoteConfigs: [
                [credentialsId: '...', url: 'ssh://vagrant@ubuntu18/usr/local/repos/app.git']
            ]
        ])
    }
    
    # Dockerfile
    ---
    FROM ubuntu:18.04
    
    RUN apt update && \
        apt install -y openjdk-11-jre && \
        apt clean
    
    COPY app/special-security/target/special-security.jar /bin
    
    ENTRYPOINT ["java", "-jar", "/bin/special-security.jar"]
    

    The version number set in the Jenkins build environment is used by the docker build command.

    Jenkins console output

    Note: the java application that I'm building with maven (e.g. mvn clean install) is purely for example purposes, the code is available https://stackoverflow.com/a/54450290/1423507. Also, the colorized output in Jenkins console requires the AnsiColor Plugin as explained https://stackoverflow.com/a/53227633/1423507. Finally, not using docker-compose in this example, there is no difference for setting the version in the environment.