【问题标题】:Jenkins: "sh npm i ..." not working in docker agent詹金斯:“sh npm i ...”不能在码头代理中工作
【发布时间】:2020-09-28 14:52:20
【问题描述】:

意图

我正在尝试基于最新的node docker 映像构建一个非常简单的声明式Jenkinsfile。我想通过在Jenkinsfile 中调用sh 'npm install ...' 来安装Node.js 应用程序的依赖项。在没有 Jenkins 的情况下从 Docker 容器中使用 npm 安装就像一个魅力,但在使用 Jenkins Pipeline 时则不然。

Jenkins 文件

pipeline {
   agent { 
       docker {
           image 'node:latest'
       }
   }
   stages {
      stage('Install Dependencies') {
         steps {
            sh 'npm -v' // sanity check
            sh 'ls -lart' // debugging filesystem
            sh 'npm i axios' // this leads to the error
         }
      }
   }
}

Jenkins 中的控制台登录

+ npm install axios
npm ERR! code EACCES
npm ERR! syscall mkdir
npm ERR! path /.npm
npm ERR! errno -13
npm ERR! 
npm ERR! Your cache folder contains root-owned files, due to a bug in
npm ERR! previous versions of npm which has since been addressed.
npm ERR! 
npm ERR! To permanently fix this problem, please run:
npm ERR!   sudo chown -R 1962192188:58041779 "/.npm"

我认为它必须与来自 Jenkins 和/或启动 Docker 容器的用户的已安装卷中的权限有关:

我尝试了什么

  1. args '-u root' 在 Jenkinsfile 的 Docker 代码块中。这可行,但我怀疑这应该如何解决。

    docker {
        image 'node:latest'
        args '-u root'
    }
    
  2. sudo chown -R 1962192188:58041779 "/.npm" 在错误消息中提出。但这会导致:

    + sudo chown -R 1962192188:58041779 /.npm
    /Users/<user>/.jenkins/workspace/pipe@tmp/durable-664f481d/script.sh: 1: 
    /Users/<user>/.jenkins/workspace/pipe@tmp/durable-664f481d/script.sh: sudo: not found
    
  3. Dockerfile 中定义一个层RUN npm install axios。这可行,但出于好奇,我想知道为什么我不能直接在 Jenkinsfile 中调用它。

    FROM node:latest
    
    RUN npm i axios
    

【问题讨论】:

标签: node.js docker jenkins npm npm-install


【解决方案1】:

解决此问题的最佳方法是使用以下方法之一(受npm install fails in jenkins pipeline in docker 启发)。这三个最终都会将默认目录.npm(即 npm 的缓存)更改为当前工作目录(即映射到 Docker 容器的 Jenkins Job 的工作空间)。

将 ENV 变量 HOME 设置为当前工作目录

声明式管道

pipeline {
    agent { docker { image 'node:latest'' } }
    environment {
        HOME = '.'
    }
    ...

脚本化管道

docker.image('node:latest').inside {
    withEnv([
        'HOME=.',
    ])
    ...

在调用npm install 时,使用附加参数--cache 更改.npm 文件夹的位置

npm install --cache npm_cache <optional:packagename>

在调用npm install之前设置npm使用的环境变量npm_config_cache

声明式管道

pipeline {
    agent { docker { image 'node:latest'' } }
    environment {
        npm_config_cache = 'npm-cache'
    }
    ...

脚本化管道

docker.image('node:latest').inside {
    withEnv([
        'npm_config_cache=npm-cache',
    ])
    ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-22
    • 2017-08-01
    • 2018-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-19
    • 1970-01-01
    相关资源
    最近更新 更多