在阿里云轻量级应用服务器(Lightweight Application Server)上部署项目,是一个非常常见且实用的操作。轻量应用服务器是阿里云为开发者提供的开箱即用、简化运维的云服务器产品,特别适合部署小型网站、Web 应用、小程序后端等。
以下是详细的项目部署流程(以部署一个 Node.js + Nginx 的 Web 项目为例):
一、准备工作
-
购买轻量应用服务器
- 登录阿里云控制台:https://home.console.aliyun.com
- 搜索“轻量应用服务器”并购买。
- 选择操作系统(推荐:CentOS 7/8、Ubuntu 20.04、或 Alibaba Cloud Linux)。
- 设置登录密码或密钥对。
-
获取服务器信息
- 公网 IP 地址
- 登录用户名(如
root) - 密码或 SSH 密钥
二、连接服务器
使用 SSH 工具连接服务器:
ssh root@<你的公网IP>
例如:
ssh root@47.98.123.456
输入密码即可登录。
三、安装必要环境
1. 更新系统包(以 Ubuntu 为例)
sudo apt update && sudo apt upgrade -y
(如果是 CentOS,使用 yum update)
2. 安装 Node.js(以 Node.js 16 为例)
curl -fsSL https://deb.nodesource.com/setup_16.x | sudo -E bash -
sudo apt-get install -y nodejs
验证安装:
node -v
npm -v
3. 安装 PM2(Node.js 进程管理工具)
npm install -g pm2
4. 安装 Nginx(反向X_X)
sudo apt install nginx -y
启动并设置开机自启:
sudo systemctl start nginx
sudo systemctl enable nginx
查看状态:
systemctl status nginx
四、上传项目代码
方法 1:Git 克隆(推荐)
如果你的项目在 GitHub/Gitee 等平台:
git clone https://github.com/yourname/your-project.git /var/www/myapp
cd /var/www/myapp
npm install
方法 2:本地上传(使用 SCP)
在本地电脑执行:
scp -r ./your-project root@<公网IP>:/root/myapp
然后登录服务器移动到合适位置:
mv /root/myapp /var/www/myapp
cd /var/www/myapp && npm install
五、配置 Nginx 反向X_X
编辑 Nginx 配置文件:
sudo nano /etc/nginx/sites-available/default
修改 server 块内容,例如:
server {
listen 80;
server_name your-domain.com; # 或者你的公网IP
location / {
proxy_pass http://127.0.0.1:3000; # 假设你的 Node.js 服务运行在 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 nginx -t
sudo systemctl restart nginx
六、启动 Node.js 项目
进入项目目录,使用 PM2 启动:
cd /var/www/myapp
pm2 start app.js --name "myapp"
设置 PM2 开机自启:
pm2 startup
pm2 save
查看运行状态:
pm2 list
pm2 logs myapp
七、开放防火墙端口
阿里云轻量服务器默认有防火墙(安全组),需在控制台开放端口:
- 登录阿里云控制台
- 进入“轻量应用服务器” → “防火墙”
- 添加规则:
- 协议类型:
TCP - 端口范围:
80(HTTP)、443(HTTPS)、3000(如果直接访问) - 源 IP:
0.0.0.0/0(或限制特定 IP)
- 协议类型:
注意:一般只需开放 80 和 443,Node.js 服务通过 Nginx X_X,无需直接暴露 3000 端口。
八、域名绑定(可选)
- 在域名服务商处,将域名 A 记录解析到服务器公网 IP。
- 在 Nginx 配置中将
server_name改为你的域名。 - 重启 Nginx。
九、配置 HTTPS(推荐使用 Let’s Encrypt)
使用 Certbot 配置免费 SSL 证书:
sudo apt install certbot python3-certbot-nginx -y
sudo certbot --nginx -d your-domain.com
按提示操作,自动配置 HTTPS。
十、常见问题排查
-
无法访问网站?
- 检查 Nginx 是否运行:
systemctl status nginx - 检查 Node.js 是否启动:
pm2 list - 检查防火墙是否开放 80 端口
- 检查项目是否监听
0.0.0.0:3000而非localhost
- 检查 Nginx 是否运行:
-
Nginx 502 Bad Gateway?
- 通常是 Node.js 服务未启动或端口不对
- 使用
pm2 logs查看错误日志
总结
| 步骤 | 内容 |
|---|---|
| 1 | 购买并登录轻量服务器 |
| 2 | 安装 Node.js、Nginx、PM2 |
| 3 | 上传项目代码 |
| 4 | 配置 Nginx 反向X_X |
| 5 | 使用 PM2 启动 Node.js 服务 |
| 6 | 配置防火墙和域名 |
| 7 | 可选:配置 HTTPS |
如果你使用的是其他技术栈(如 Python Flask、Java Spring Boot、静态网站等),步骤类似,主要是环境安装和反向X_X配置不同。
需要我提供 Python/Django 或 Java/Spring Boot 的部署示例吗?欢迎继续提问!
云计算导航