How to push docker image from jenkins to GCP artifact repo

527 Views Asked by At

I wanted to push the docker image from Jenkins(Running on same GCP project) to GCP Artifact Repo. I am using the maven-jib plugin to build and push the image. Maven-jib-plugin supports the container registry(It's Deprecated) but no documentation for the artifact registry.

Could you please help me with how to achieve this?

1

There are 1 best solutions below

3
Robert G On

Based on Jenkins community:

Here's an example of jenkinsfile to push to Artifact Registry:

pipeline {
  environment {
    PROJECT = "you-gcp-project"
    APP_NAME = "you-app-name"
    REPO_NAME = "your-repo-name"
    REPO_LOCATION = "your-repo-location"
    IMAGE_NAME = "${REPO_LOCATION}-docker.pkg.dev/${PROJECT}/${REPO_NAME}/${APP_NAME}"
  }

  agent {
    kubernetes {
      yaml '''
        apiVersion: v1
        kind: Pod
        metadata:
          labels:
            app: test
        spec:
          containers:
          - name: docker
            image: gcr.io/cloud-builders/docker
            command:
            - cat
            tty: true
            volumeMounts:
            - mountPath: /var/run/docker.sock
              name: docker-sock
          - name: kubectl
            image: gcr.io/cloud-builders/kubectl
            command:
            - cat
            tty: true
          volumes:
          - name: docker-sock
            hostPath:
              path: /var/run/docker.sock
      '''
    }
  }
  
  stages {
    stage('Pull Git'){
      when { expression { true } }
      steps{
        checkout scm
      }
    }

    stage('Build docker image') {
    when { expression { true } }
      steps{
        container('docker'){
          dir('Backend Net/MyDotnet') {
            echo 'Build docker image Start'
            sh 'pwd'
            sh 'docker build -t ${IMAGE_NAME}:${IMAGE_TAG} .'
            withCredentials([file(credentialsId: "${PROJECT}_artifacts", variable: 'GCR_CRED')]){
              sh 'cat "${GCR_CRED}" | docker login -u _json_key_base64 --password-stdin https://"${REPO_LOCATION}"-docker.pkg.dev'
              sh 'docker push ${IMAGE_NAME}:${IMAGE_TAG}'
              sh 'docker logout https://"${REPO_LOCATION}"-docker.pkg.dev'
            }
            sh 'docker rmi ${IMAGE_NAME}:${IMAGE_TAG}'
            echo 'Build docker image Finish'
          }
        }
      }
    }
  }
}

You may refer to the documentations below for your reference: