在 CentOS 中解决 Node.js 依赖的实用指南
一 安装 Node.js 与包管理器
sudo yum update -y && sudo yum groupinstall -y "Development Tools"curl -fsSL https://rpm.nodesource.com/setup_16.x | sudo bash -
sudo yum install -y nodejs
node -v && npm -v
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
source ~/.bashrc
nvm install --lts
nvm use --lts
node -v && npm -v
npm install -g yarn
yarn -v
以上步骤完成后,系统即具备运行与安装 Node.js 依赖的 node/npm/yarn 环境。
二 安装与维护项目依赖
npm init -y
npm install express # 生产依赖
npm install webpack --save-dev # 开发依赖
yarn init -y
yarn add express
yarn add webpack --dev
npm update # 更新依赖
npm uninstall pkg # 移除依赖
npm ci # 以 package-lock.json 为准的干净安装(CI/生产推荐)
npm audit fix # 自动修复已知漏洞(必要时再执行)
三 常见依赖问题与修复
sudo yum groupinstall -y "Development Tools"
sudo yum install -y gcc-c++ make openssl-devel
npm cache clean --force
npm install
/lib64/libc.so.6: version 'GLIBC_2.28' not found(常见于 CentOS 7 上误装 Node.js 18+)# 1) 移除高版本 NodeSource 源
sudo rm -f /etc/yum.repos.d/nodesource*.repo
# 2) 清理缓存
sudo yum clean all && sudo rm -rf /var/cache/yum
# 3) 安装与系统兼容的版本(如 16.x)
curl -fsSL https://rpm.nodesource.com/setup_16.x | sudo bash -
sudo yum install -y nodejs
node -v
mkdir -p ~/.npm-global
npm config set prefix '~/.npm-global'
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc
source ~/.bashrc
npm config set registry https://registry.npmmirror.com
yarn config set registry https://registry.npmmirror.com
以上措施覆盖了 编译工具链、版本兼容 与 权限/镜像 等高频问题。
四 生产环境运行与反向代理
sudo npm install -g pm2
pm2 start app.js --name myapp
pm2 startup systemd -u $USER --hp $HOME
pm2 save && pm2 status
sudo yum install -y nginx
sudo systemctl enable --now nginx
编辑 /etc/nginx/conf.d/default.conf:server {
listen 80;
server_name your_domain.com;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
sudo systemctl reload nginx
上述方案可提升 可用性 与 可维护性,适合长期运行的服务。