How to set user in docker image

Issue

  • Running tasks on docker images that work correctly on the command line results in permission issues.
    • Eg. Running sh 'npm install package_blah' results in something similar to: npm ERR! Error: Invalid name: "@adsk/lmv".
    • Eg. Running sh 'pip install package_blah' on the python image results in something similar to: error: [Errno 13] Permission denied: '/usr/local/lib/python/site-packages/version.py'

Environment

  • CloudBees Jenkins Enterprise
  • CloudBees Docker Pipeline Plugin

Resolution

First determine that the commands you are running work using docker without the plugin (command line).

Assuming everything works natively, then determine what user is running these commands for the image (command line):

docker run -it <image> whoami

Specify that user in the Docker Pipeline job to ensure that the same user it used.

The below example shows how to run pip install with the python:2.7 docker image:

docker.image('python:2.7').withRun('-u root') {
    sh 'pip install version'
}
Have more questions? Submit a request

3 Comments

  • 0
    Avatar
    Gabriel Fdc

    This doesn't work, as the shell step would run outside of the docker image as it is said in https://go.cloudbees.com/docs/cloudbees-documentation/cje-user-guide/index.html#docker-workflow-sect-run

    So, if you have a jenkins with no nodejs, and would try to do a build inside the node docker image if you use this method:

    docker.image('node').withRun('-u node'){
    sh 'node -v'
    sh 'npm install'
    }

    you will get

    node: command not found

     

    But if you try to do it inside the docker image:

    docker.image('node').inside(){
    sh 'node -v'
    sh 'npm install'
    }

    you would get the error described in the article:

    npm ERR! Error: EACCES: permission denied, mkdir '/.npm'

    is there a way to specify the user to docker and run something inside the image?

  • 0
    Avatar
    Denys Digtiar

    Hi Gabriel,

    Please try the following since `inside` method supports parameters in a similar way as `withRun`

    docker.image('node').inside('-u node') {
    sh 'node -v'
    sh 'npm install'
    }
  • 0
    Avatar
    Gabriel Fdc

    Hi, thanks for replying.

    Yes after commenting i figured out i could use parameters in the inside method.

    It worked but you need to use root user, if you use node user, it will not have permissions to write in the workspace dir.

Please sign in to leave a comment.