利用systemd启动部署在服务器上的web应用

0.背景

系统环境: Ubuntu 22.04
web应用情况: 前后端分类,前端采用react,后端采用fastapi

1.具体配置

1.1 前端配置

开发态运行(启动命令是npm run dev),创建systemd服务文件

bash 复制代码
sudo nano /etc/systemd/system/frontend.service

内容如下:

bash 复制代码
[Unit]
Description=React Frontend Dev Server
After=network.target

[Service]
User=youruser
WorkingDirectory=/home/yourusr/yourweb/frontend
ExecStart=/usr/bin/npm run dev
Restart=always
RestartSec=3

[Install]
WantedBy=multi-user.target

如果你使用了nvm来管理Node.js,那么你应该做如下修改

bash 复制代码
[Unit]
Description=React Frontend Dev Server
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=/home/yourusr/yourweb/frontend
Environment="NVM_DIR=/root/.nvm"
ExecStart=/bin/bash -c 'source $NVM_DIR/nvm.sh && nvm use 22.15.0 && npm run dev'
Restart=always
RestartSec=3

[Install]
WantedBy=multi-user.target

1.2后端配置

编写fastapi启动脚本,在/home/youruser/backend/start_backend.sh写入:

bash 复制代码
#!/bin/bash
cd /home/yourweb/backend
source venv/bin/activate
exec uvicorn server:app --host 0.0.0.0 --port 8000 --workers 1

如果使用conda管理环境,脚本文件的内容写入如下:

bash 复制代码
#!/bin/bash

cd /home/yourweb/backend
# 加载 conda 环境(确保 conda 可用)
source /home/youruser/miniconda3/etc/profile.d/conda.sh

# 激活 conda 虚拟环境
conda activate myenv

# 启动 Uvicorn
exec uvicorn server:app --host 0.0.0.0 --port 8000 --workers 1

Tip: 把 /home/youruser/miniconda3 替换为你实际的 conda 安装路径(可用 which conda 看一下)

然后授予可执行权限

bash 复制代码
chmod +x /home/yourweb/backend/start_backend.sh

创建systemd服务文件

bash 复制代码
sudo nano /etc/systemd/system/backend.service

内容如下:

bash 复制代码
[Unit]
Description=FastAPI Backend Service
After=network.target

[Service]
Type=simple
User=youruser
ExecStart=/home/youruser/yourweb/backend/start_backend.sh
WorkingDirectory=/home/youruser/yourweb/backend
Restart=always
RestartSec=3

[Install]
WantedBy=multi-user.target

2.启停管理

2.1 前端服务启停

命令如下:

bash 复制代码
sudo systemctl daemon-reload
sudo systemctl start frontend
sudo systemctl enable frontend
sudo systemctl status frontend #查看运行状态

2.2 后端服务启停

命令如下:

bash 复制代码
sudo systemctl daemon-reload
sudo systemctl start backend
sudo systemctl enable backend
sudo systemctl status backend # 查看运行状态
相关推荐
林shir5 分钟前
3-15-前端Web实战(Vue工程化+ElementPlus)
前端·javascript·vue.js
一位赵15 分钟前
小练2 选择题
linux·运维·windows
qq_3129201118 分钟前
Nginx+Keepalived双主架构:消除单点故障的最佳实践
运维·nginx·架构
zhaoyin199430 分钟前
Fiddler弱网实战
前端·测试工具·fiddler
LucDelton1 小时前
Java 读取无限量文件读取的思路
java·运维·网络
Lw老王要学习1 小时前
CentOS 7.9达梦数据库安装全流程解析
linux·运维·数据库·centos·达梦
蓝队云计算2 小时前
蓝队云部署OpenClaw深度指南:避坑、优化与安全配置,从能用做到好用
运维·安全·云计算
Kaede62 小时前
提示dns服务器未响应,需要做哪些事?
运维·服务器
CRUD酱2 小时前
CentOS的yum仓库失效问题解决(换镜像源)
linux·运维·服务器·centos
换日线°2 小时前
前端炫酷展开效果
前端·javascript·vue