在 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。cargo build --release,产物位于 target/release/。scp target/release/my_rust_app user@your_server_ip:/path/to/deploy。二 服务器运行与进程管理
./my_rust_app。/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。sudo ufw allow 8080/tcp。三 打包为 Debian 包便于分发与复用
cargo install cargo-deb;系统依赖 dpkg-dev、liblzma-dev。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。Cargo.toml 增加[package.metadata.deb.systemd-units]
my_rust_app.service = { path = "deploy/my_rust_app.service", enabled = true }
打包时单元文件会随 .deb 部署并启用。四 常见问题与排查
ufw allow 8080/tcp)。journalctl -u my_rust_app -xe 查看详细错误;注意 WorkingDirectory、Environment 与可执行文件路径是否正确。sudo apt-get update,再 sudo apt-get install -f 自动补齐依赖。