新建网站部署流程
1. 新建 Node 服务,指定端口并代理前端静态资源
操作步骤:
- 初始化 Node 项目
mkdir my-website && cd my-website npm init -y npm install express
- 创建
app.js
(示例代码)const express = require('express'); const app = express(); const PORT = 3000; // 指定服务端口// 代理前端静态资源(假设前端文件在 `dist` 目录) app.use(express.static('dist'));// 处理前端路由(如单页应用) app.get('*', (req, res) => {res.sendFile(__dirname + '/dist/index.html'); });app.listen(PORT, () => {console.log(`Server running on http://localhost:${PORT}`); });
- 测试服务
访问node app.js
http://服务器IP:3000
确认服务正常运行。
2. 上传前端项目到指定目录
操作步骤:
- 构建前端项目(以 Vue/React 为例)
npm run build # 生成 `dist` 或 `build` 目录
- 上传到服务器
scp -r ./dist user@服务器IP:/path/to/my-website/
- 确保目录结构与 Node 服务的
express.static
路径一致。
- 确保目录结构与 Node 服务的
3. 使用 PM2 代理 Node 进程
操作步骤:
- 全局安装 PM2
npm install pm2 -g
- 启动服务并设为守护进程
pm2 start app.js --name "my-website"
- 设置开机自启
pm2 startup pm2 save
- 常用命令
pm2 logs my-website # 查看日志 pm2 restart my-website # 重启服务
4. 新增服务器二级域名(A记录解析)
操作步骤:
- 在域名管理平台(如阿里云DNS、Cloudflare)添加A记录
- 主机名:
subdomain
(如blog
) - 记录值:服务器公网IP
- TTL:默认(600秒)
- 主机名:
- 验证解析生效
ping subdomain.your-domain.com
5. 开放服务器端口并设置防火墙
操作步骤:
- 检查端口占用
sudo netstat -tulnp | grep 3000
- 开放端口(以UFW为例)
sudo ufw allow 3000/tcp # 放行Node服务端口 sudo ufw enable # 启用防火墙 sudo ufw status # 验证规则
- 云服务器安全组(如AWS/阿里云)
- 在控制台添加入站规则:允许
TCP 3000
。
- 在控制台添加入站规则:允许
6. 配置 Nginx 反向代理
操作步骤:
- 创建 Nginx 配置文件
sudo nano /etc/nginx/conf.d/my-website.conf
- 配置内容(示例)
server {listen 80;server_name subdomain.your-domain.com;location / {proxy_pass http://localhost:3000; # 转发到Node服务proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;}# 可选:静态文件直接由Nginx处理location /static {alias /path/to/my-website/dist/static;} }
- 测试并重启 Nginx
sudo nginx -t # 检查语法 sudo systemctl restart nginx
7. 访问调试与日志排查
操作步骤:
- 访问二级域名
浏览器打开http://subdomain.your-domain.com
,检查页面和网络请求。 - 查看服务日志
pm2 logs my-website # Node服务日志 sudo tail -f /var/log/nginx/error.log # Nginx错误日志
- 常见问题
- 502 Bad Gateway:检查 Node 服务是否运行、端口是否匹配。
- 403 Forbidden:确认 Nginx 有权限访问
dist
目录(chmod 755
)。 - DNS未生效:等待解析或本地修改 hosts 文件临时测试。
补充优化建议
- HTTPS 配置
使用 Let’s Encrypt 免费证书:sudo apt install certbot python3-certbot-nginx sudo certbot --nginx -d subdomain.your-domain.com
- 静态文件缓存
在 Nginx 配置中添加缓存策略:location /static {expires 365d;add_header Cache-Control "public"; }
- 进程监控
使用pm2 monit
实时监控资源占用。
流程图
按此流程操作,即可完成从代码到线上服务的完整部署!