Interview Prep/Jenkins/Integrations: SonarQube, Nexus, Artifactory, Docker, Trivy

How do you build and push a Docker image from Jenkins on a VM agent?

BeginnerConceptIntegrations: SonarQube, Nexus, Artifactory, Docker, Trivy
Answer
stage('Image') {
  steps {
    withCredentials([usernamePassword(credentialsId: 'dockerhub', usernameVariable: 'U', passwordVariable: 'P')]) {
      sh '''
        echo "$P" | docker login -u "$U" --password-stdin
        docker build -t devopsshack/shack-api:${GIT_COMMIT:0:7} .
        docker push devopsshack/shack-api:${GIT_COMMIT:0:7}
        docker logout
      '''
    }
  }
}

${GIT_COMMIT:0:7} is bash syntax; Jenkins' sh runs /bin/sh, which may be dash. Add #!/bin/bash as the first line of the script or compute the short SHA in Groovy.

All Jenkins questions Roadmap: Jenkins

More on Integrations: SonarQube, Nexus, Artifactory, Docker, Trivy