简体   繁体   中英

sudo permission inside docker container for jenkins pipeline

I had created a Jenkinsfile using declarative syntax to build my nodejs application. I had used a docker agent to build, now its giving me permission error. This is my sample Jenkinsfile.

pipeline {
    agent { 
        docker { 
            image 'node:8.4'
              }
         }   
    stages {
        stage('build') {
            steps {
                    sh 'pwd'
                    sh 'npm --version'
                    sh 'npm --prefix ./Server install'
            }
          }
        }
}

Unhandled rejection Error: EACCES: permission denied, mkdir '/.npm'

I had even tried to add the sudo command

 sh 'sudo npm --version'

but then it gives me no sudo found error. How can we give permission inside the docker from the Jenkinsfile, the current unix user is jenkins which I have added to the sudoers also. When i run the Jenkins file i can see it passes the jenkins user and group to the docker using -u option.

 docker run -t -d -u 109:116 -w /var/lib/jenkins/testapp

Problem is related to npm trying to write its cache on /.npm folder. Since you are running your container with the -u flag, the user you run it is not root (the default). On a Linux machine, by default, non root users cannot create a new directory in /.

You have a few options to solve your problem:

  1. Running your container as root by removing the -u option (this means that npm would be run by root user, this could lead to security problems)
  2. Changing npm cache path to a folder where the unprivileged users can write such as /tmp
  3. Use a custom docker image instead of the default node one where you create the /.npm directory and give write permissions to unprivileged users.

In my opinion option 2 is the easiest, just run this command before npm install in your build script:

export HOME=/tmp ;  npm config set cache /tmp

Also, npm stores its config into user's home directory. Since the user you are using doesn't exists in the container, their home directory is set to / . In order to avoid having write permission error, try setting the HOME env variable to /tmp too. Your install command becomes:

export HOME=/tmp ;  npm --prefix ./Server install

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM