Rust的官方安装工具是rustup,它能方便地管理Rust版本及工具链。
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
脚本会引导完成安装(接受许可协议、选择默认路径),安装完成后会提示是否更新PATH环境变量,输入y确认。source $HOME/.cargo/env
验证安装是否成功:rustc --version # 查看Rust编译器版本
cargo --version # 查看包管理器版本
rustup,可通过Linux发行版的包管理器安装(如Ubuntu/Debian):sudo apt update && sudo apt install rustc cargo
验证方式同上。cargo创建项目目录(以hello_rust为例):cargo new hello_rust
cd hello_rust
项目结构会自动生成(包含src/main.rs和Cargo.toml配置文件)。src/main.rs文件,添加业务逻辑(如经典的“Hello World”):fn main() {
println!("Hello from Rust on Linux!");
}
cargo run
若终端输出Hello from Rust on Linux!,说明代码运行正常。生产环境需要优化编译的二进制文件,使用--release标志构建:
cargo build --release
构建完成后,可执行文件会生成在target/release目录下(如hello_rust)。
将构建好的二进制文件传输到目标Linux服务器,常用工具为scp:
scp target/release/hello_rust user@your_server_ip:/path/to/deploy
替换user、your_server_ip和/path/to/deploy为实际的用户名、服务器IP和部署路径。
chmod +x /path/to/deploy/hello_rust
openssl),需提前在服务器上安装对应开发包(以Ubuntu为例):sudo apt install build-essential libssl-dev pkg-config
具体依赖可根据项目的Cargo.toml文件调整。/path/to/deploy/hello_rust
应用会在终端前台运行,关闭终端则会终止进程。nohup命令:nohup /path/to/deploy/hello_rust > output.log 2>&1 &
日志会输出到output.log文件中。为了让应用随系统启动、崩溃自动重启,可创建systemd服务文件:
sudo nano /etc/systemd/system/hello_rust.service
[Unit]
Description=Hello Rust Application
After=network.target
[Service]
ExecStart=/path/to/deploy/hello_rust
Restart=always
User=your_username
Group=your_groupname
Environment=ENV_VAR_NAME=value # 可选:设置环境变量
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload # 重新加载systemd配置
sudo systemctl start hello_rust # 启动服务
sudo systemctl enable hello_rust # 设置开机自启
sudo systemctl status hello_rust
若显示active (running),说明服务已正常运行。nohup,可通过tail -f output.log实时查看日志;若使用systemd,用journalctl -u hello_rust查看服务日志。systemctl restart hello_rust)。top、htop或Prometheus+Grafana等工具监控应用的CPU、内存占用情况。以上流程覆盖了Rust在Linux系统中的完整部署生命周期,从环境准备到生产运行,兼顾了基础需求与高级管理场景。