确保Linux系统已安装基础工具(如curl、git),若未安装可通过包管理器安装(以Ubuntu为例):
sudo apt update && sudo apt install -y curl git
使用Rustup(Rust官方推荐的安装工具)安装最新稳定版Rust:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
按照终端提示操作(选择默认安装选项即可)。安装完成后,激活环境变量:
source $HOME/.cargo/envsource $HOME/.zshrc验证安装是否成功:
rustc --version # 查看Rust编译器版本
cargo --version # 查看Cargo(Rust包管理器)版本
在本地开发环境中创建或进入Rust项目目录,使用Cargo构建优化后的发布版本(--release会启用编译器优化,提升运行性能):
cargo new my_rust_app # 创建新项目(可选,若已有项目可跳过)
cd my_rust_app
cargo build --release # 构建发布版本
构建完成后,可执行文件会生成在target/release/目录下(文件名与项目名一致,如my_rust_app)。
将构建好的可执行文件传输到目标服务器(以scp为例,替换user、server_ip和路径为实际值):
scp target/release/my_rust_app user@server_ip:/opt/my_rust_app
登录服务器,检查文件权限(确保可执行):
chmod +x /opt/my_rust_app
openssl、libssl-dev),需提前安装(以Ubuntu为例):sudo apt install -y libssl-dev pkg-config
systemd创建服务,实现应用开机自启、崩溃自动重启。
sudo nano /etc/systemd/system/my_rust_app.service
/opt/my_rust_app为实际路径,user为运行用户):[Unit]
Description=My Rust Application
After=network.target
[Service]
User=user
ExecStart=/opt/my_rust_app
Restart=always
Environment=RUST_BACKTRACE=1 # 开启崩溃时的堆栈跟踪(调试用)
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl start my_rust_app
sudo systemctl enable my_rust_app # 设置开机自启
sudo systemctl status my_rust_app
通过服务器IP或域名访问应用(若为Web服务,需确保端口开放,如80或443):
curl http://localhost # 替换为实际访问地址
若为命令行工具,可直接在服务器终端运行:
/opt/my_rust_app
以上步骤覆盖了Rust项目从本地开发到Linux服务器部署的全流程,其中**cargo build --release是构建高性能可执行文件的关键,systemd服务管理**则确保了应用的稳定运行。