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

React生产构建部署Linux服务器:关闭Putty后应用停止运行求助

React应用部署到Linux服务器并实现后台持续运行的解决方案

一、生产环境推荐部署方式:使用Nginx(稳定可靠)

serve工具更适合开发或临时预览场景,生产环境用Nginx托管静态文件是更优选择,步骤如下:

  • 安装Nginx
    根据服务器发行版选择对应命令:

    • Debian/Ubuntu:
      sudo apt update && sudo apt install nginx
      
    • CentOS/RHEL:
      sudo dnf install nginx
      
  • 配置Nginx托管build文件夹

    1. 备份默认配置文件:
      sudo cp /etc/nginx/sites-available/default /etc/nginx/sites-available/default.bak
      
    2. 编辑默认配置:
      sudo nano /etc/nginx/sites-available/default
      
    3. 替换server块内容为以下代码(注意替换路径和服务器IP/域名):
      server {
          listen 80;
          server_name 你的服务器IP或域名;
      
          root /绝对路径/build; # 替换为你上传的build文件夹绝对路径,比如/var/www/my-react-app/build
          index index.html;
      
          # 解决React路由刷新404问题
          location / {
              try_files $uri $uri/ /index.html;
          }
      }
      
  • 启动并验证Nginx

    1. 测试配置是否正确:
      sudo nginx -t
      
    2. 重启Nginx生效:
      sudo systemctl restart nginx
      
    3. 设置开机自启:
      sudo systemctl enable nginx
      

配置完成后,直接访问服务器IP/域名就能看到你的React应用,关闭终端也不会停止服务。

二、若坚持使用serve实现后台运行

方法1:用nohup让进程脱离终端

运行以下命令:

nohup serve -s build > serve.log 2>&1 &
  • nohup:让进程不受终端关闭影响,持续运行
  • > serve.log 2>&1:把程序输出和错误日志写入serve.log,方便排查问题
  • &:让进程后台运行

要停止服务时,先查找进程ID:

ps aux | grep serve

再用kill <进程ID>终止进程。

方法2:用systemd管理服务(规范持久)

通过systemd管理服务,能实现开机自启、进程异常自动重启,步骤:

  1. 创建服务配置文件:
    sudo nano /etc/systemd/system/react-serve.service
    
  2. 写入以下内容(替换占位符):
    [Unit]
    Description=Serve React Build Folder
    After=network.target
    
    [Service]
    User=你的服务器用户名 # 比如ubuntu
    WorkingDirectory=/build文件夹的上级目录 # 比如/var/www/my-react-app
    ExecStart=$(which serve) -s build # $(which serve)会自动获取serve的安装路径
    Restart=always # 进程崩溃时自动重启
    
    [Install]
    WantedBy=multi-user.target
    
  3. 启用并启动服务:
    sudo systemctl daemon-reload
    sudo systemctl start react-serve
    sudo systemctl enable react-serve # 设置开机自启
    

查看服务状态:

sudo systemctl status react-serve

停止服务:

sudo systemctl stop react-serve

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 05:16:17