插件窝 干货文章 教你如何配置NGINX、PM2和VPS服务器

教你如何配置NGINX、PM2和VPS服务器

NGINX sudo bash 配置 141    来源:    2025-04-11

配置NGINX、PM2和VPS服务器的完整指南

1. VPS服务器基础设置

1.1 连接到VPS

ssh root@your_server_ip

1.2 更新系统

sudo apt update && sudo apt upgrade -y

1.3 创建非root用户(推荐)

adduser username
usermod -aG sudo username

2. 安装Node.js和NPM

2.1 安装最新LTS版本

curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
sudo apt-get install -y nodejs

2.2 验证安装

node -v
npm -v

3. 安装和配置PM2

3.1 全局安装PM2

sudo npm install -g pm2

3.2 启动Node.js应用

pm2 start app.js --name "my-app"

3.3 常用PM2命令

pm2 list              # 查看运行中的应用
pm2 stop my-app       # 停止应用
pm2 restart my-app    # 重启应用
pm2 delete my-app     # 删除应用
pm2 logs              # 查看日志

3.4 设置开机自启

pm2 startup
pm2 save

4. 安装和配置NGINX

4.1 安装NGINX

sudo apt install nginx -y

4.2 启动NGINX

sudo systemctl start nginx
sudo systemctl enable nginx

4.3 配置反向代理

创建配置文件:

sudo nano /etc/nginx/sites-available/my-app

添加以下内容(根据实际情况修改):

server {
    listen 80;
    server_name yourdomain.com www.yourdomain.com;

    location / {
        proxy_pass http://localhost:3000;  # 假设Node应用运行在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 ln -s /etc/nginx/sites-available/my-app /etc/nginx/sites-enabled
sudo nginx -t  # 测试配置
sudo systemctl restart nginx

5. 安全配置

5.1 防火墙设置

sudo ufw allow ssh
sudo ufw allow http
sudo ufw allow https
sudo ufw enable

5.2 安装Let's Encrypt SSL证书

sudo apt install certbot python3-certbot-nginx -y
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com

5.3 设置自动续期

sudo certbot renew --dry-run

6. 监控和维护

6.1 PM2监控

pm2 monit

6.2 查看服务器资源使用情况

htop

6.3 日志管理

# NGINX访问日志
sudo tail -f /var/log/nginx/access.log

# NGINX错误日志
sudo tail -f /var/log/nginx/error.log

# PM2应用日志
pm2 logs

7. 常见问题解决

7.1 端口冲突

sudo netstat -tulnp | grep :80

7.2 权限问题

sudo chown -R username:username /path/to/your/app

7.3 NGINX配置错误

sudo nginx -t

通过以上步骤,你应该已经成功配置了一个基于VPS、NGINX和PM2的生产环境Node.js应用服务器。根据你的具体应用需求,可能还需要进一步调整配置。