在部署前,需确保本地开发环境已完成Rust工具链安装及项目构建。
rustup安装最新稳定版Rust,命令如下:curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env # 激活环境变量
rustc --version # 验证安装(显示版本号即成功)
cargo build --release生成优化后的可执行文件,位于target/release目录下。该模式会启用编译器优化(如LLVM优化),提升运行性能。将本地构建的target/release/your_project(Windows为.exe)复制到服务器。常用工具:
scp target/release/your_project user@remote_host:/path/to/deploy
rsync -avz target/release/your_project user@remote_host:/path/to/deploy
chmod +x /path/to/deploy/your_project
.env文件(需配合dotenv crate)或在服务器直接导出:export DATABASE_URL=postgres://user:password@localhost:5432/mydb
export RUST_LOG=info # 日志级别(可选)
/path/to/deploy/your_project
nohup或tmux保持进程运行(即使终端关闭):nohup /path/to/deploy/your_project > app.log 2>&1 &
为确保项目开机自启、崩溃自动重启,建议创建systemd服务:
sudo nano /etc/systemd/system/your_project.service
[Unit]
Description=Your Rust Project
After=network.target
[Service]
User=your_username # 替换为实际用户
WorkingDirectory=/path/to/deploy
ExecStart=/path/to/deploy/your_project
Restart=always # 崩溃后自动重启
Environment="DATABASE_URL=postgres://user:password@localhost:5432/mydb" # 环境变量
RestartSec=5s # 重启间隔
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload # 重新加载配置
sudo systemctl start your_project # 启动服务
sudo systemctl enable your_project # 开机自启
sudo systemctl status your_project # 查看运行状态
journalctl -u your_project -f # 实时查看日志
若项目为Web应用(如Actix-Web、Axum),建议用Nginx/Apache作为反向代理,处理HTTP请求转发、SSL加密及静态资源服务。
sudo apt install nginx # Ubuntu/Debian
sudo yum install nginx # CentOS/RHEL
/etc/nginx/conf.d/your_project.conf,添加以下内容:server {
listen 80;
server_name your_domain.com; # 替换为域名或IP
location / {
proxy_pass http://localhost:8080; # 转发到Rust应用端口
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
sudo systemctl restart nginx
sudo certbot --nginx -d your_domain.com
若项目包含静态资源(HTML/CSS/JS/图片),可通过以下方式简化部署:
rust-embed宏将静态文件编译到可执行文件中,无需单独传输。
cargo add rust-embeduse rust_embed::RustEmbed;
#[derive(RustEmbed)]
#[folder = "static"] // 指向静态资源目录
struct Asset;
Asset::get("index.html")访问资源。FileServer中间件服务静态目录(开发环境推荐):use actix_files::Files;
use actix_web::{App, HttpServer};
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.service(Files::new("/static", "static").show_files_listing()) // 静态资源目录
.route("/", web::get().to(index_handler))
})
.bind("0.0.0.0:8080")?
.run()
.await
}
journalctl查看systemd日志,或使用log crate将日志输出到文件,配合logrotate实现日志轮转。top、htop监控CPU/内存占用,或集成Prometheus+Grafana实现可视化监控。以上步骤覆盖了Linux环境下Rust项目从本地构建到服务器部署的全流程,涵盖了进程管理、反向代理、静态资源优化等关键环节,可根据项目实际需求调整配置。