温馨提示×

Rust程序在Debian上如何部署

小樊
33
2025-12-13 02:07:15
栏目: 编程语言

在 Debian 上部署 Rust 程序的实用流程

一 准备环境与构建发布版

  • 安装 Rust 工具链(rustup):执行 curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh,完成后执行 source $HOME/.cargo/env,并用 rustc --versioncargo --version 验证安装。
  • 安装构建依赖(可选,用于本地编译或交叉编译场景):sudo apt update && sudo apt install -y build-essential gcc make
  • 获取代码并构建发布版:在项目根目录执行 cargo build --release,产物位于 target/release/
  • 传输到目标服务器:例如 scp target/release/my_rust_app user@your_server_ip:/path/to/deploy

二 服务器运行与进程管理

  • 直接运行:在服务器上进入部署目录并执行 ./my_rust_app
  • 使用 systemd 托管(推荐):创建服务文件 /etc/systemd/system/my_rust_app.service,示例:
    [Unit]
    Description=My Rust Application
    After=network.target
    
    [Service]
    ExecStart=/path/to/deploy/my_rust_app
    WorkingDirectory=/path/to/deploy
    User=your_user
    Restart=always
    Environment=PORT=8080
    
    [Install]
    WantedBy=multi-user.target
    
    启用与启动:sudo systemctl daemon-reload && sudo systemctl enable --now my_rust_app
  • 常用运维:查看状态 sudo systemctl status my_rust_app;实时日志 journalctl -u my_rust_app -f;重启 sudo systemctl restart my_rust_app
  • 防火墙放行(如监听 8080 端口):sudo ufw allow 8080/tcp

三 打包为 Debian 包便于分发与复用

  • 安装打包工具:确保 Rust ≥ 1.63,然后 cargo install cargo-deb;系统依赖 dpkg-devliblzma-dev
  • 生成 .deb:在项目根目录执行 cargo deb,产物位于 target/debian/<项目名><版本>-1<架构>.deb
  • 安装与修复依赖:sudo dpkg -i target/debian/*.deb,若依赖不满足执行 sudo apt-get install -f
  • 调试符号:默认已剥离;如需保留,可在 Cargo.toml[profile.release] 中设置 debug = true,或使用 cargo deb --separate-debug-symbols
  • systemd 单元随包安装:在 Cargo.toml 增加
    [package.metadata.deb.systemd-units]
    my_rust_app.service = { path = "deploy/my_rust_app.service", enabled = true }
    
    打包时单元文件会随 .deb 部署并启用。

四 常见问题与排查

  • 端口未开放:确认应用监听 0.0.0.0:端口 而非 127.0.0.1,并在云厂商安全组与系统防火墙放行对应端口(如 ufw allow 8080/tcp)。
  • 权限与运行用户:服务文件中的 User 需存在;可执行文件与目录权限建议为 755/644,数据目录可设为该用户所有。
  • 构建失败缺少头文件或链接器:安装 build-essential 等基础编译工具。
  • systemd 启动失败:使用 journalctl -u my_rust_app -xe 查看详细错误;注意 WorkingDirectoryEnvironment 与可执行文件路径是否正确。
  • .deb 安装依赖错误:先 sudo apt-get update,再 sudo apt-get install -f 自动补齐依赖。

0