zh

Node.js VPS托管:部署和扩展Node应用完整指南

Node.js是全球最流行的服务端JavaScript运行时,被无数Web应用、API服务和实时应用所采用。在离岸VPS上托管Node.js应用不仅能提升性能和可控性,还能享受不受单一国家法律限制的数据主权保护。Anubiz Host的冰岛VPS方案为Node.js开发者提供高性能NVMe存储、充足带宽和完整根权限,是部署Node.js生产环境的理想选择。

Need this done for your project?

We implement, you ship. Async, documented, done in days.

Start a Brief

在VPS上安装Node.js环境

连接SSH后,首先更新系统并安装Node.js。推荐通过NodeSource官方源安装最新LTS版本,确保安全性和长期支持:
apt update && apt upgrade -y
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
apt install -y nodejs
node --version
npm --version
安装完成后,验证版本输出。Node.js 20 LTS是当前推荐的生产环境版本。同时安装构建工具以支持需要编译的npm包:
apt install -y build-essential git
如果项目使用特定Node版本,推荐安装NVM(Node Version Manager)以便在多个版本间切换:
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
source ~/.bashrc
nvm install 20
nvm use 20

使用PM2管理Node.js进程

PM2是Node.js生产环境的标准进程管理器,提供进程守护、自动重启、日志管理和集群模式等功能。全局安装PM2并配置系统启动自动运行:
npm install -g pm2
cd /var/www/myapp
pm2 start app.js --name "myapp"
pm2 startup
pm2 save
PM2集群模式可利用多核CPU提升吞吐量:
pm2 start app.js -i max --name "myapp-cluster"
常用PM2管理命令:
pm2 list          # 查看所有进程
pm2 logs myapp    # 查看实时日志
pm2 restart myapp # 重启应用
pm2 monit         # 实时监控面板
配置ecosystem.config.js文件可以管理环境变量和部署配置,是团队协作和CI/CD集成的推荐方式。PM2的日志轮转插件(pm2-logrotate)可防止日志文件无限增长占满磁盘空间。

Nginx反向代理配置

在生产环境中,Node.js应用通常监听内部端口(如3000),通过Nginx反向代理向外暴露标准HTTP/HTTPS端口。安装并配置Nginx:
apt install -y nginx
nano /etc/nginx/sites-available/myapp
写入以下配置:
server {
    listen 80;
    server_name yourdomain.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_set_header X-Real-IP $remote_addr;
        proxy_cache_bypass $http_upgrade;
    }
}
启用配置并安装SSL证书:
ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled/
apt install -y certbot python3-certbot-nginx
certbot --nginx -d yourdomain.com
systemctl reload nginx

Node.js VPS性能优化建议

在Anubiz Host VPS上优化Node.js应用性能需要从多个层面入手。环境变量方面,始终设置NODE_ENV=production,这会触发Express等框架的生产模式优化,禁用调试输出并启用视图缓存:
export NODE_ENV=production
pm2 start app.js --env production
内存管理方面,根据VPS的RAM配置Node.js的堆内存上限,避免进程因内存不足而崩溃:
node --max-old-space-size=512 app.js  # 适用于2GB RAM VPS
对于高并发场景,结合PM2集群模式和Nginx的负载均衡可以充分利用多核CPU。建议在VPS上配置swap分区作为内存缓冲:
fallocate -l 2G /swapfile
chmod 600 /swapfile
mkswap /swapfile
swapon /swapfile
echo '/swapfile none swap sw 0 0' >> /etc/fstab
Anubiz Host的冰岛VPS提供NVMe SSD存储,I/O性能远超传统HDD,非常适合需要频繁文件操作的Node.js应用场景。

Why Anubiz Host

100% async — no calls, no meetings
Delivered in days, not weeks
Full documentation included
Production-grade from day one
Security-first approach
Post-delivery support included

Ready to get started?

Skip the research. Tell us what you need, and we'll scope it, implement it, and hand it back — fully documented and production-ready.

Anubiz Chat AI

Online