Debian上Rust项目的部署方法
一 准备与构建
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh,完成后执行 source $HOME/.cargo/env,并用 rustc --version、cargo --version 验证安装。为后续打包,建议安装构建依赖:sudo apt update && sudo apt install -y build-essential gcc make。如使用国内网络,可设置镜像加速:export RUSTUP_DIST_SERVER=https://mirrors.ustc.edu.cn/rust-static、export RUSTUP_UPDATE_ROOT=https://mirrors.ustc.edu.cn/rust-static/rustup2。构建发布版本:cargo build --release,产物位于 target/release/。如使用第三方库,确保系统具备对应的 C 库 与头文件(例如数据库驱动、压缩库等)。二 传输与运行
scp target/release/my_rust_app user@your_server_ip:/path/to/deploy。在服务器上运行:./my_rust_app。如监听网络端口,确保云厂商安全组与服务器防火墙已放行对应端口(例如放行 8080/tcp)。日志与故障排查可直接查看标准输出,或使用 journalctl 跟踪服务日志(见下一节 systemd)。三 以 systemd 托管为系统服务
sudo nano /etc/systemd/system/my_rust_app.service,示例内容:[Unit]
Description=My Rust Application
After=network.target
[Service]
Type=simple
User=www-data
Group=www-data
ExecStart=/path/to/deploy/my_rust_app
WorkingDirectory=/path/to/deploy
Restart=always
Environment=RUST_BACKTRACE=1
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、sudo systemctl restart my_rust_app、journalctl -u my_rust_app -f(实时日志)、journalctl -u my_rust_app --since "2025-12-03 10:00:00"(按时间过滤)。如需开机自启,确保 WantedBy=multi-user.target 并执行 enable。四 打包为 Debian 包便于分发与复用
cargo install cargo-deb(建议 Rust ≥ 1.63;系统准备 dpkg-dev、liblzma-dev 等)。在项目根目录生成包:cargo deb,产物位于 target/debian/。安装与修复依赖:sudo dpkg -i target/debian/*.deb,如依赖不满足执行 sudo apt-get -f install。调试符号与 systemd 集成:在 Cargo.toml 的 [profile.release] 中设置 debug = true 可保留调试信息;使用 cargo deb --separate-debug-symbols 将调试符号分离到 /usr/lib/debug/。若项目包含 systemd 单元,可在 Cargo.toml 增加 [package.metadata.deb.systemd-units] 配置,打包时自动包含单元文件,便于一致化部署与开机自启。五 实用建议与常见问题
Environment= 注入 PORT、RUST_LOG 等关键配置,便于不同环境复用同一单元文件。端口与防火墙:若应用监听 8080/tcp,使用 sudo ufw allow 8080/tcp 放行,并确认云安全组策略一致。构建与运行架构一致:避免跨架构直接运行(例如在 amd64 主机运行 arm64 二进制),必要时使用交叉编译或在目标架构上构建。日志与排错:优先使用 journalctl -u <svc> -f 实时查看,必要时开启 RUST_BACKTRACE=1 获取堆栈信息。