确保Ubuntu系统为LTS版本(如24.04 LTS),以获得长期支持和稳定性。更新系统软件包并安装必要依赖:
sudo apt update && sudo apt upgrade -y
sudo apt install -y curl build-essential gcc make
使用rustup(Rust官方工具链管理器)安装Rust编译器(rustc)和包管理器(cargo):
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
安装完成后,激活环境变量(重启终端或运行以下命令):
source $HOME/.cargo/env
验证安装是否成功:
rustc --version # 查看Rust编译器版本
cargo --version # 查看Cargo包管理器版本
~/my_rust_app:cd ~/my_rust_app
cargo build
可执行文件位于target/debug/my_rust_app。cargo build --release
可执行文件位于target/release/my_rust_app。将target/release/下的可执行文件复制到目标服务器(或本地目标目录)。例如,使用scp复制到远程服务器:
scp target/release/my_rust_app user@your_server_ip:/opt/my_rust_app
可选:剥离二进制文件(减小体积,移除调试符号):
strip /opt/my_rust_app
若需将Rust应用作为系统服务(开机自启、崩溃自动重启),可创建systemd服务文件:
sudo nano /etc/systemd/system/my_rust_app.service
[Unit]
Description=My Rust Application
After=network.target
[Service]
User=ubuntu # 替换为运行应用的系统用户(避免使用root)
ExecStart=/opt/my_rust_app
Restart=always # 崩溃时自动重启
Environment=RUST_BACKTRACE=1 # 开启错误回溯(调试用)
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload # 重新加载systemd配置
sudo systemctl start my_rust_app # 启动服务
sudo systemctl enable my_rust_app # 设置开机自启
sudo systemctl status my_rust_app
若需将Rust应用打包为Deb格式(Ubuntu原生包格式),可使用cargo-deb工具:
cargo-deb:cargo install cargo-deb
Cargo.toml(添加包元数据):[package.metadata.deb]
maintainer = "Your Name <you@example.com>"
description = "A Rust application for Ubuntu"
section = "utils"
priority = "optional"
depends = "libc6 (>= 2.28)" # 指定系统依赖(如libc版本)
cargo deb --release
生成的.deb文件位于target/debian/目录(如my_rust_app_0.1.0_amd64.deb)。sudo dpkg -i target/debian/my_rust_app_0.1.0_amd64.deb
libssl),安装对应依赖:sudo apt install -y libssl-dev pkg-config
chmod +x /opt/my_rust_app
journalctl -u my_rust_app -f
通过以上步骤,即可在Ubuntu上完成Rust应用的部署,涵盖从环境准备到后台运行的全流程。根据实际需求选择调试/发布模式、系统服务或打包分发,满足不同场景的使用要求。