应用案例:后台服务管理

第一种方式:使用nohup后台运行服务

1
2
3
4
5
6
7
8
9
10
11
# 进入项目目录
cd ~/project

# 激活虚拟环境
source venv/bin/activate

# 使用nohup后台启动服务,并将输出重定向到日志文件
nohup uvicorn api_active:app --host 0.0.0.0 --port 8000 --workers 4 > api.log 2>&1 &

# 显示后台作业编号
echo "服务已启动,作业ID: $!"

第二种方式:使用screen管理会话(推荐用于开发)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 安装screen(如果未安装)
sudo apt update && sudo apt install screen

# 创建名为api的screen会话
screen -S api

# 在screen会话中启动服务
cd ~/project
source venv/bin/activate
uvicorn api_active:app --host 0.0.0.0 --port 8000 --workers 4

# 按 Ctrl+A 然后按 D 分离会话(服务继续运行)

# 重新连接到screen会话
screen -r api

# 查看所有screen会话
screen -ls

第三种方式:使用systemd管理服务(生产环境最佳)

  1. 创建systemd服务文件

    1
    2
    # 创建systemd服务文件
    sudo nano /etc/systemd/system/api-active.service
  2. 编写服务配置

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    [Unit]
    Description=API Active Service
    After=network.target

    [Service]
    Type=simple
    User=ubuntu
    Group=ubuntu
    WorkingDirectory=/home/ubuntu/project
    Environment=PATH=/home/ubuntu/project/venv/bin
    ExecStart=/home/ubuntu/project/venv/bin/uvicorn api_active:app --host 0.0.0.0 --port 8000 --workers 4
    Restart=always
    RestartSec=5
    StandardOutput=journal
    StandardError=journal

    [Install]
    WantedBy=multi-user.target
  3. 管理服务

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    #
    编辑系统服务配置命令
    sudo nano /etc/systemd/system/api-active.service
    用sudo nano /etc/systemd/system/api-active.service配置后,
    要重新加载服务配置,加载服务配置后再启动服务即可,
    如果修改后没有重新加载服务配置系统会提示
    Warning: The unit file, source configuration file or drop-ins of api-active.service changed on disk. Run 'systemctl daemon-reload' to reload units.


    # 重新加载systemd配置
    sudo systemctl daemon-reload

    # 启用开机自启
    sudo systemctl enable api-active

    # 启动服务
    sudo systemctl start api-active

    # 查看服务状态
    sudo systemctl status api-active

    # 查看服务日志
    sudo journalctl -u api-active -f

    # 停止服务
    sudo systemctl stop api-active

    # 重启服务
    sudo systemctl restart api-active

验证服务是否运行

1
2
3
4
5
6
7
8
9
10
11
# 检查进程
ps aux | grep uvicorn

# 检查端口
netstat -tlnp | grep 8000
# 或
ss -tlnp | grep 8000

# 测试API
curl http://localhost:8000