You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js REST API本地运行正常后,部署至真实服务器的下一步建议

Node.js REST API 部署分步指南

一、本地代码预检查

  • 拆分依赖:将开发工具(如nodemon、eslint)放在devDependencies,运行必需包放在dependencies,部署时仅安装生产依赖:npm install --production
  • 环境变量配置:用dotenv管理敏感信息(数据库密钥、端口号等),本地用.env文件,部署时直接在服务器设置环境变量,避免硬编码
  • 验证生产模式运行:执行npm run start(而非开发环境的npm run dev),确认API在本地生产模式下能正常响应请求

二、服务器准备

  • 选择云服务器:优先选Ubuntu系统的云主机,通过SSH登录服务器:ssh your-username@server-public-ip
  • 更新系统:登录后先执行系统包更新:sudo apt update && sudo apt upgrade -y

三、安装服务器环境

  • 安装Node.js和npm:
    curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
    sudo apt-get install -y nodejs
    
    验证安装:node -v、npm -v,确保版本和本地开发环境一致或兼容
  • 安装进程管理器PM2:用于后台托管API服务,避免终端关闭后进程终止
    npm install pm2 -g
    

四、上传代码到服务器

  • Git克隆(推荐):如果代码托管在Git仓库,直接在服务器克隆:git clone your-repository-url
  • SCP上传:若不想用Git,可打包本地代码后上传:scp -r ./your-api-folder your-username@server-public-ip:/home/your-username/
  • 进入代码目录,安装生产依赖:cd your-api-folder && npm install --production

五、启动并托管API

  • 启动服务:用PM2启动入口文件(如app.js或server.js):pm2 start app.js
  • 查看状态:pm2 status,确认服务处于online状态
  • 设置开机自启:执行pm2 startup,按照终端提示运行生成的命令,确保服务器重启后服务自动恢复
  • 保存进程配置:pm2 save,避免PM2重启后丢失进程信息

六、配置Nginx反向代理

  • 安装Nginx:sudo apt install nginx -y
  • 创建API配置文件:sudo nano /etc/nginx/sites-available/your-api
  • 写入以下配置(替换域名和API端口):
    server {
        listen 80;
        server_name your-domain.com;
    
        location / {
            proxy_pass http://localhost:3000; # 替换为你的API运行端口
            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/your-api /etc/nginx/sites-enabled/
  • 验证配置:sudo nginx -t,无报错则重启Nginx:sudo systemctl restart nginx

七、域名与SSL配置

  • 域名解析:将你的域名A记录指向服务器公网IP
  • 安装SSL证书(免费):用Certbot配置HTTPS
    sudo apt install certbot python3-certbot-nginx -y
    sudo certbot --nginx -d your-domain.com
    
    按终端提示完成配置,Certbot会自动修改Nginx配置,强制跳转到HTTPS

八、日常维护

  • 查看API日志:pm2 logs,排查运行时错误
  • 更新代码:拉取最新代码后,执行pm2 restart app.js重启服务
  • 定期更新:每月执行sudo apt update && sudo apt upgrade -y更新系统包,按需升级Node.js版本

内容的提问来源于stack exchange,提问作者Florian Saliba

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 02:15:35