react如何部署linux
部署 React 应用至 Linux 服务器的步骤
准备工作
确保 Linux 服务器已安装 Node.js 和 npm(或 yarn)。若未安装,可通过以下命令安装:
curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
sudo apt-get install -y nodejs
检查版本:
node -v
npm -v
构建 React 应用
在本地开发目录中,运行构建命令生成生产环境代码:
npm run build
生成的文件默认位于 build/ 目录。
传输文件至服务器
使用 scp 或 rsync 将构建文件上传至服务器。例如:
scp -r build/ user@your_server_ip:/path/to/target_directory
配置 Web 服务器
推荐使用 Nginx 或 Apache 托管静态文件。以 Nginx 为例:
-
安装 Nginx:
sudo apt-get install nginx -
编辑配置文件(通常位于
/etc/nginx/sites-available/default):server { listen 80; server_name your_domain.com; root /path/to/build; index index.html; location / { try_files $uri $uri/ /index.html; } } -
重启 Nginx:
sudo systemctl restart nginx
可选:使用 PM2 管理 Node.js 服务
若项目包含后端(如 Express),可通过 PM2 守护进程:
-
安装 PM2:
npm install -g pm2 -
启动服务:
pm2 start server.js --name "react-app" -
设置开机自启:
pm2 startup pm2 save
验证部署
访问服务器 IP 或域名,确认应用正常运行。若遇问题,检查以下日志:
- Nginx 错误日志:
/var/log/nginx/error.log - PM2 日志:
pm2 logs
通过以上步骤,React 应用可稳定运行于 Linux 环境。







