You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AWS EC2 Ubuntu服务器user-data中nvm无法更新Node.js问题

AWS EC2 User-Data中NVM安装Node.js LTS失败的解决方法

在AWS EC2 Ubuntu服务器的user-data脚本中尝试通过NVM安装最新Node.js LTS版本时失败,执行nvm命令会提示“Command 'nvm' not found, but there are 14 similar ones.”,但在常规命令行窗口执行相同操作却能正常完成。

用户尝试的两段脚本如下:

第一段尝试代码

#!/bin/bash

yes | sudo apt update

yes | sudo apt upgrade

yes | sudo apt install nodejs

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash

source ~/.bashrc

nvm install --lts

第二段尝试代码

#!/bin/bash
yes | sudo apt update
yes | sudo apt upgrade
# Node.js 
yes | sudo apt install nodejs
# NVM 
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
nvm install --lts

问题根源

user-data脚本以非交互式shell运行,和手动登录的交互式shell环境存在差异:

  1. 第一段脚本中的source ~/.bashrc在非交互式环境下无效——Ubuntu默认的.bashrc开头有判断逻辑,非交互式时会直接退出,无法加载nvm的环境配置。
  2. 第二段脚本虽手动加载nvm.sh,但未明确用户上下文:user-data默认以root用户执行,若路径或环境变量传递不完整,会导致nvm命令无法被识别。

修正后的解决方案

以root用户执行的脚本

#!/bin/bash
# 更新系统包
apt update -y
apt upgrade -y

# 安装curl(确保能下载nvm脚本)
apt install -y curl

# 安装nvm
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash

# 手动加载nvm环境,明确指定root用户的nvm路径
export NVM_DIR="/root/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"

# 安装最新LTS版本的Node.js
nvm install --lts

# 设置默认Node.js版本为LTS
nvm alias default lts/*

以普通用户(如ubuntu)执行的脚本

如果需要切换到普通用户安装,需调整路径并通过su命令切换上下文:

#!/bin/bash
apt update -y
apt upgrade -y
apt install -y curl

# 切换到ubuntu用户执行nvm相关操作
su - ubuntu -c "
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
export NVM_DIR=\"/home/ubuntu/.nvm\"
[ -s \"\$NVM_DIR/nvm.sh\" ] && \. \"\$NVM_DIR/nvm.sh\"
nvm install --lts
nvm alias default lts/*
"

关键调整说明

  • 用-y参数替代yes |,自动确认安装/更新操作,更简洁可靠
  • 明确安装curl,避免系统默认未预装导致nvm脚本下载失败
  • 针对执行用户明确指定NVM_DIR路径,确保环境变量加载正确
  • 添加设置默认Node版本的步骤,后续登录无需手动切换版本

内容的提问来源于stack exchange,提问作者Günay Yağcı

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 17:12:56