在阿里云服务器上快速配置 Node.js 开发环境,可以按照以下步骤进行操作。假设你使用的是 ECS(Elastic Compute Service) 实例,并且操作系统为 Ubuntu 20.04/22.04 或 CentOS 7/8。
✅ 步骤一:登录到阿里云 ECS 实例
- 登录 阿里云控制台
- 进入 ECS 控制台
- 找到你的实例,获取公网 IP 地址
- 使用 SSH 登录:
ssh root@<你的公网IP>
# 如果设置了密钥,则使用:
ssh -i /path/to/your-key.pem root@<公网IP>
✅ 步骤二:更新系统包(以 Ubuntu 为例)
sudo apt update && sudo apt upgrade -y
若是 CentOS/RHEL 系统:
sudo yum update -y
✅ 步骤三:安装 Node.js 和 npm
推荐使用 NodeSource 提供的 PPA 源 安装指定版本的 Node.js。
方法一:使用 NodeSource(推荐)
例如安装 Node.js 18.x:
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt install -y nodejs
其他版本替换
setup_18.x为setup_16.x或setup_20.x
验证安装:
node --version
npm --version
方法二:使用 nvm(Node Version Manager,适合多版本管理)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
重启 shell 或执行:
source ~/.bashrc
然后安装 Node.js:
nvm install 18 # 安装 v18
nvm use 18 # 使用 v18
验证:
node -v
npm -v
✅ 步骤四:安装 PM2(生产环境推荐)
PM2 是 Node.js 应用的进程管理器,用于后台运行和守护进程。
npm install -g pm2
常用命令:
pm2 start app.js
pm2 list
pm2 logs
pm2 startup
pm2 save
✅ 步骤五:开放安全组端口
- 回到阿里云控制台 → ECS → 安全组
- 找到实例关联的安全组,点击「配置规则」
- 添加安全组规则,放行你的应用端口(如 3000、80、443 等)
示例规则:
| 协议类型 | 端口范围 | 授权对象 |
|---|---|---|
| 自定义 TCP | 3000 | 0.0.0.0/0 |
生产建议仅对必要 IP 开放,避免全网开放。
✅ 步骤六:部署简单的 Node.js 应用(测试)
创建一个测试文件:
mkdir myapp && cd myapp
nano app.js
写入以下内容:
const http = require('http');
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello from Alibaba Cloud!n');
});
const PORT = 3000;
server.listen(PORT, '0.0.0.0', () => {
console.log(`Server running at http://0.0.0.0:${PORT}/`);
});
运行应用:
node app.js
或使用 PM2:
pm2 start app.js --name "my-node-app"
✅ 步骤七:(可选)配置 Nginx 反向X_X
如果你希望使用域名或 80/443 端口访问,建议安装 Nginx 做反向X_X。
安装 Nginx:
sudo apt install nginx -y # Ubuntu
# 或
sudo yum install nginx -y # CentOS
配置反向X_X(编辑配置文件):
sudo nano /etc/nginx/sites-available/default
添加如下 server 块(确保监听 80):
server {
listen 80;
server_name your-domain.com; # 或公网IP
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_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_cache_bypass $http_upgrade;
}
}
重启 Nginx:
sudo systemctl restart nginx
✅ 最终访问
浏览器中访问:
http://<你的公网IP>:3000 # 直接访问
# 或
http://<你的公网IP> # 使用 Nginx X_X后
🔐 安全建议
- 不要长期使用 root 用户,创建普通用户并配置 sudo
- 定期更新系统和软件
- 使用防火墙(如 ufw 或 firewalld)
- 配置 HTTPS(可用 Let’s Encrypt + Certbot)
📦 一键脚本(Ubuntu 快速部署)
你可以将以下命令保存为脚本运行:
#!/bin/bash
# 快速部署 Node.js 环境(Ubuntu)
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt install -y nodejs nginx
npm install -g pm2
echo "Node.js $(node --version) and PM2 installed."
echo "Nginx installed. Please configure reverse proxy as needed."
完成以上步骤后,你就拥有了一个可用于开发或生产的 Node.js 环境!
如有需要,我也可以提供自动化部署脚本或 Docker 部署方案。
云服务器