skip to Main Content

Here is my dockerfile

FROM node:20-alpine3.18

WORKDIR /app

COPY package*.json .npmrc ./
RUN --mount=type=secret,id=npmrc 
    NPM_TOKEN=$(cat /run/secrets/npmrc) 
    npm ci --production
COPY . .

EXPOSE 8000

CMD ["npm", "run", "start"]

Here is my Jenkinsfile and docker-compose

  jenkins:
    container_name: jenkins
    image: jenkins/jenkins:lts
    privileged: true
    user: root
    ports:
      - "8080:8080"
      - "50000:50000"
    volumes:
      - ./volumns/jenkins/config:/var/jenkins_home
      - /var/run/docker.sock:/var/run/docker.sock
    networks:
      - tasker

  jenkins-agent:
    container_name: jenkins-agent
    image: jenkins/ssh-agent:jdk11
    privileged: true
    user: root
    expose:
      - 22
    environment:
      - JENKINS_AGENT_SSH_PUBKEY=ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDDsKbwjgeLCuRXghRiUBlMvFDrfHiLMN89i1O1haVIs8HBDNUeD+TGxGi/UZ4I0PR6O6g19MYo/qaL7ro9G/dvRSsUAtrmh2bVJYXxVZWzscMPuXoNJSA8FOG8pbzqvzs/x3JiZw+L9+namV9zmUz2FQVWOC3Obu5q8hD+C2AJ3akjtLQFqU5D7jWH8147uVNZw06c74yCdVxsn1aOqqVU6xwhqY+tnKa/Tf9CPJd9D3sYPHz3In+1Qldlvm+eOkIn5IygIYO34HtMxwd/rxW05XU8LAmZsJ3PLj4pYuOvUG04Rku/gj1I+CntZ9V/b6EnZylbb6tPZnA3gOk+9KyKE104Kbv/Bxy+2tM4eUAmGj3gUCowRz+BX0DI01yhn9OCqPCkj5YTayVxKEpZZEKrF5yJEdJ1Rl+gh9fEGghGKsI4Pm7RsPpI2yE8MccpnUVI5BvwkwWeNGHKsjzGt1CPYCmQCmGVFtz3Yh73pMeZnt+N0FfUA3vh30gGTyUZJBU= rulerchen@RulerChen-Desktop
    networks:
      - tasker
namespace = "production"
serviceName = "tasker-auth"
service = "Tasker Auth"

pipeline {
  agent {
    label 'Jenkins-Agent'
  }

  tools {
    nodejs "NodeJS"
    dockerTool "Docker"
  }

  environment {
    DOCKER_CREDENTIALS = credentials("dockerhub")
    IMAGE_NAME = "rulerchen" + "/" + "tasker-3-auth"
    IMAGE_TAG = "stable-${BUILD_NUMBER}"
  }

  stages {
    stage("Cleanup Workspace") {
      steps {
        cleanWs()
      }
    }

    stage("Prepare Environment") {
      steps {
        withCredentials([string(credentialsId: 'NPM_TOKEN', variable: 'NPM_TOKEN')]) {
          git branch: 'main', credentialsId: 'github', url: 'https://github.com/RulerChen/tasker-auth'
          sh 'npm install'
        }
      }
    }

    stage("Lint Check") {
      steps {
        sh 'npm run lint'
      }
    }

    stage("Unit Test") {
      steps {
        sh 'npm run test'
      }
    }

    stage("Write Secret") {
      steps {
        withCredentials([string(credentialsId: 'NPM_TOKEN', variable: 'NPM_TOKEN')]) {
          sh 'echo $NPM_TOKEN > npmrc'
        }
      }
    }

    stage("Build and Push") {
      steps {
        sh 'docker login -u $DOCKER_CREDENTIALS_USR --password $DOCKER_CREDENTIALS_PSW'
        sh "docker image build --secret id=npmrc,src=npmrc -t $IMAGE_NAME ." 
        sh "docker tag $IMAGE_NAME $IMAGE_NAME:$IMAGE_TAG"
        sh "docker tag $IMAGE_NAME $IMAGE_NAME:stable"
        sh "docker push $IMAGE_NAME:$IMAGE_TAG"
        sh "docker push $IMAGE_NAME:stable"
      }
    }

    stage("Clean Artifacts") {
      steps {
        sh "docker rmi $IMAGE_NAME:$IMAGE_TAG"
        sh "docker rmi $IMAGE_NAME:stable"
        sh "rm -f npmrc"
      }
    }
  }
}

When i using Jenkins Pipeline,the error message:

Login Succeeded
[Pipeline] sh
+ docker image build --secret id=npmrc,src=npmrc -t rulerchen/tasker-3-auth .
DEPRECATED: The legacy builder is deprecated and will be removed in a future release.
            Install the buildx component to build images with BuildKit:
            https://docs.docker.com/go/buildx/

unknown flag: --secret
See 'docker image build --help'.
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Clean Artifacts)
Stage "Clean Artifacts" skipped due to earlier failure(s)

Because I use private github npm package, i need to use secret to store NPM_TOKEN and build my docker image.
I use lateset and 25.0.3 docker version in Jenkins and im sure that this command can run on my computer.

When i use docker image build --help in jenkins, there is no –secret

+ docker --version
Docker version 25.0.3, build 4debf41
[Pipeline] sh
+ docker image build --help
DEPRECATED: The legacy builder is deprecated and will be removed in a future release.
            Install the buildx component to build images with BuildKit:
            https://docs.docker.com/go/buildx/


Usage:  docker image build [OPTIONS] PATH | URL | -

Build an image from a Dockerfile

Aliases:
  docker image build, docker build, docker buildx build, docker builder build

Options:
      --add-host list           Add a custom host-to-IP mapping ("host:ip")
      --build-arg list          Set build-time variables
      --cache-from strings      Images to consider as cache sources
      --cgroup-parent string    Set the parent cgroup for the "RUN"
                                instructions during build
      --compress                Compress the build context using gzip
      --cpu-period int          Limit the CPU CFS (Completely Fair
                                Scheduler) period
      --cpu-quota int           Limit the CPU CFS (Completely Fair
                                Scheduler) quota
  -c, --cpu-shares int          CPU shares (relative weight)
      --cpuset-cpus string      CPUs in which to allow execution (0-3, 0,1)
      --cpuset-mems string      MEMs in which to allow execution (0-3, 0,1)
      --disable-content-trust   Skip image verification (default true)
  -f, --file string             Name of the Dockerfile (Default is
                                "PATH/Dockerfile")
      --force-rm                Always remove intermediate containers
      --iidfile string          Write the image ID to the file
      --isolation string        Container isolation technology
      --label list              Set metadata for an image
  -m, --memory bytes            Memory limit
      --memory-swap bytes       Swap limit equal to memory plus swap: -1
                                to enable unlimited swap
      --network string          Set the networking mode for the RUN
                                instructions during build (default "default")
      --no-cache                Do not use cache when building the image
      --platform string         Set platform if server is multi-platform
                                capable
      --pull                    Always attempt to pull a newer version of
                                the image
  -q, --quiet                   Suppress the build output and print image
                                ID on success
      --rm                      Remove intermediate containers after a
                                successful build (default true)
      --security-opt strings    Security options
      --shm-size bytes          Size of "/dev/shm"
  -t, --tag list                Name and optionally a tag in the
                                "name:tag" format
      --target string           Set the target build stage to build.
      --ulimit ulimit           Ulimit options (default [])

How can i fix this problem?

this command should not be error.

docker image build --secret id=npmrc,src=npmrc -t $IMAGE_NAME .

2

Answers


  1. Chosen as BEST ANSWER

    Thanks to @Olakunle Abiola

    This is my solution

        stage("Build and Push") {
          steps {
            sh 'docker login -u $DOCKER_CREDENTIALS_USR --password $DOCKER_CREDENTIALS_PSW'
    
            sh 'curl -sL https://github.com/docker/buildx/releases/download/v0.12.1/buildx-v0.12.1.linux-amd64 -o buildx-v0.12.1-linux-amd64'
            sh 'mkdir -p ~/.docker/cli-plugins'
            sh 'mv buildx-v0.12.1-linux-amd64 docker-buildx'
            sh 'mv docker-buildx ~/.docker/cli-plugins'
            sh 'chmod +x ~/.docker/cli-plugins/docker-buildx'
    
            withEnv(["DOCKER_BUILDKIT=1"]) {
              sh "docker image build --secret id=npmrc,src=npmrc -t $IMAGE_NAME ."
            }
    
            sh "docker tag $IMAGE_NAME $IMAGE_NAME:$IMAGE_TAG"
            sh "docker tag $IMAGE_NAME $IMAGE_NAME:stable"
            sh "docker push $IMAGE_NAME:$IMAGE_TAG"
            sh "docker push $IMAGE_NAME:stable"
          }
        }
    

  2. Ensure BuildKit is enabled for the build step to use the --secret flag.

    stage("Build and Push") {
      steps {
        sh 'docker login -u $DOCKER_CREDENTIALS_USR --password $DOCKER_CREDENTIALS_PSW'
        // Ensure BuildKit is enabled for using --secret in docker build
        
        withEnv(["DOCKER_BUILDKIT=1"]) {
          sh "docker image build --secret id=npmrc,src=npmrc -t $IMAGE_NAME ."
        }
        sh "docker tag $IMAGE_NAME $IMAGE_NAME:$IMAGE_TAG"
        sh "docker tag $IMAGE_NAME $IMAGE_NAME:stable"
        // Push the tagged images
        sh "docker push $IMAGE_NAME:$IMAGE_TAG"
        sh "docker push $IMAGE_NAME:stable"
      }
    }
    

    Before the docker image build command, withEnv(["DOCKER_BUILDKIT=1"]) is used to ensure that Docker’s BuildKit is enabled for the current shell session. This is necessary for the --secret flag to work as intended.

    If your Jenkins pipeline does not recognize withEnv, you can try using passing the buildkit variable directly in your docker image build command like this:

    stage("Build and Push") {
      steps {
        script {
          sh 'DOCKER_BUILDKIT=1 docker image build --secret id=npmrc,src=npmrc -t $IMAGE_NAME .'
        }
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search