Azure DevOps容器代理执行npm命令提示‘command not found’问题解决
问题描述
我将Azure容器实例用作Azure DevOps代理,在代理的Dockerfile中通过NVM安装了Node.js和npm。从Azure门户连接到容器实例后,执行npm install -g sass可正常运行:
root@SandboxHost-638173989121880372:/azp# npm install -g sass changed 17 packages in 926ms 2 packages are looking for funding run `npm fund` for details
但在Azure DevOps流水线中执行如下Bash任务时,却报错找不到npm命令:
- task: Bash@3 displayName: 'npm install sass' inputs: targetType: 'inline' script: 'npm install -g sass'
错误信息如下:
Starting: npm install sass ============================================================================== Task : Bash Description : Run a Bash script on macOS, Linux, or Windows Version : 3.214.0 Author : Microsoft Corporation Help : https://docs.microsoft.com/azure/devops/pipelines/tasks/utility/bash ============================================================================== Generating script. Script contents: npm install -g sass ========================== Starting Command Output =========================== /usr/bin/bash /azp/_work/_temp/fcfde5dd-1d1f-40c7-ba8f-9b6b3e0fb87f.sh /azp/_work/_temp/fcfde5dd-1d1f-40c7-ba8f-9b6b3e0fb87f.sh: line 1: npm: command not found ##[error]Bash exited with code '127'. Finishing: npm install sass
原因分析
通过NVM安装Node.js时,NVM的环境变量(如PATH)仅在安装时的Shell会话中生效。而Azure DevOps代理运行任务时使用的是非交互式Shell,不会加载NVM的初始化脚本(比如~/.bashrc或~/.profile),导致npm的路径未被加入系统全局PATH,因此任务执行时无法找到该命令。
解决方法
替换NVM安装方式,直接通过包管理器安装Node.js和npm,这样npm会被添加到系统全局PATH中,无论哪种Shell环境都能正常访问。修改Dockerfile中的安装步骤为:
#### - Node and NPM - #### RUN curl -fsSL https://deb.nodesource.com/setup_20.x | bash - && \ apt-get install -y nodejs && rm -rf /var/lib/apt/lists/*
修改完成后重新构建容器镜像,更新Azure容器实例代理,流水线任务即可正常执行npm命令。
内容的提问来源于stack exchange,提问作者MadSkeletor
相关产品推荐
相关产品推荐

