搬瓦工部署 Actix Rust Web 框架教程

Actix Web 是 Rust 语言生态中最受欢迎的 Web 框架之一,以极高的性能和内存安全著称。Rust 编译生成的原生二进制文件运行效率极高,资源占用极低,非常适合在 VPS 上部署高性能 Web 服务。本文将介绍如何在搬瓦工 VPS 上编译和部署 Actix Web 应用。购买搬瓦工 VPS 请参考 全部方案,使用优惠码 NODESEEK2026 可享受 6.77% 的折扣。

一、安装 Rust 工具链

apt update && apt upgrade -y
apt install build-essential pkg-config libssl-dev -y

# 安装 Rust
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
source $HOME/.cargo/env
rustc --version
cargo --version

二、创建 Actix Web 项目

cd /opt
cargo new myapi
cd myapi

2.1 配置依赖

cat > /opt/myapi/Cargo.toml << 'EOF'
[package]
name = "myapi"
version = "0.1.0"
edition = "2021"

[dependencies]
actix-web = "4"
actix-rt = "2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio = { version = "1", features = ["full"] }
env_logger = "0.11"
log = "0.4"

[profile.release]
opt-level = 3
lto = true
codegen-units = 1
EOF

2.2 编写主程序

cat > /opt/myapi/src/main.rs << 'EOF'
use actix_web::{web, App, HttpServer, HttpResponse, middleware};
use serde::{Deserialize, Serialize};

#[derive(Serialize)]
struct ApiResponse {
    status: String,
    message: String,
}

async fn health() -> HttpResponse {
    HttpResponse::Ok().json(ApiResponse {
        status: "ok".to_string(),
        message: "Service is running".to_string(),
    })
}

async fn hello(name: web::Path) -> HttpResponse {
    HttpResponse::Ok().json(ApiResponse {
        status: "ok".to_string(),
        message: format!("Hello, {}!", name),
    })
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    env_logger::init();
    let bind_addr = std::env::var("BIND_ADDR").unwrap_or_else(|_| "127.0.0.1:8080".to_string());

    println!("Starting server at {}", bind_addr);

    HttpServer::new(|| {
        App::new()
            .wrap(middleware::Logger::default())
            .route("/health", web::get().to(health))
            .route("/hello/{name}", web::get().to(hello))
    })
    .bind(&bind_addr)?
    .run()
    .await
}
EOF

三、编译与运行

# Release 模式编译
cargo build --release

# 编译产物在 target/release/myapi
ls -la target/release/myapi

Rust Release 编译后的二进制文件通常只有几 MB,运行时内存占用也极低。

四、创建 Systemd 服务

cp /opt/myapi/target/release/myapi /usr/local/bin/myapi

cat > /etc/systemd/system/actix-api.service << 'EOF'
[Unit]
Description=Actix Web API Service
After=network.target

[Service]
Type=simple
ExecStart=/usr/local/bin/myapi
Environment=BIND_ADDR=127.0.0.1:8080
Environment=RUST_LOG=info
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable actix-api
systemctl start actix-api

五、Nginx 反向代理

apt install nginx -y

cat > /etc/nginx/sites-available/actix.conf << 'EOF'
server {
    listen 80;
    server_name api.yourdomain.com;

    location / {
        proxy_pass http://127.0.0.1:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}
EOF

ln -sf /etc/nginx/sites-available/actix.conf /etc/nginx/sites-enabled/
rm -f /etc/nginx/sites-enabled/default
nginx -t && systemctl restart nginx

六、SSL 证书与部署脚本

apt install certbot python3-certbot-nginx -y
certbot --nginx -d api.yourdomain.com

cat > /opt/myapi/deploy.sh << 'EOF'
#!/bin/bash
cd /opt/myapi
git pull origin main
cargo build --release
systemctl stop actix-api
cp target/release/myapi /usr/local/bin/myapi
systemctl start actix-api
echo "[$(date)] Actix API deployed"
EOF
chmod +x /opt/myapi/deploy.sh

七、常见问题

编译时间长

Rust Release 编译可能需要较长时间(5-15分钟),特别是在低配 VPS 上。可以考虑在本地编译后上传二进制文件,或使用交叉编译。编译时内存需求较大,建议至少 2GB 内存或配置 Swap。

内存不足编译失败

fallocate -l 4G /swapfile
chmod 600 /swapfile
mkswap /swapfile
swapon /swapfile

总结

Actix Web 是性能最强的 Web 框架之一,编译后的二进制文件资源占用极低,非常适合在搬瓦工 VPS 上部署高性能 API 服务。其他框架教程包括 Gin GoPhoenix ElixirLaravel 等。购买搬瓦工 VPS 请访问 bwh81.net,使用优惠码 NODESEEK2026 可享受 6.77% 的折扣。

关于本站

搬瓦工VPS中文网(bwgvps.com)是非官方中文信息站,整理搬瓦工的方案、优惠和教程。我们不销售主机,不提供技术服务。

新手必读
搬瓦工优惠码

NODESEEK2026(优惠 6.77%)

购买时填入即可抵扣。