Rust 服务 → Docker → K8s
将 Rust 构建的高性能服务容器化后部署到 K8s,包含健康检查、资源限制、滚动更新
你将学到
- 构建 Rust Web 服务
- 多阶段 Docker 构建
- 部署到 K8s 集群
- 生产级配置
前置知识
架构设计
┌─────────────────────────────────────┐
│ Kubernetes │
├─────────────────────────────────────┤
│ ┌─────────┐ ┌─────────────┐ │
│ │ Rust │ │ Service │ │
│ │ App │──────│ ClusterIP │ │
│ └─────────┘ └─────────────┘ │
│ │ │
│ ┌────┴────┐ │
│ │ Pods │ (3 replicas) │
│ └─────────┘ │
└─────────────────────────────────────┘
实现步骤
第一步:Rust Web 服务
// src/main.rs
use actix_web::{web, App, HttpServer, HttpResponse};
use serde::Serialize;
#[derive(Serialize)]
struct HealthResponse {
status: String,
}
#[derive(Serialize)]
struct InfoResponse {
app: String,
version: String,
rust_version: String,
}
async fn health() -> HttpResponse {
HttpResponse::Ok().json(HealthResponse {
status: "healthy".to_string(),
})
}
async fn info() -> HttpResponse {
HttpResponse::Ok().json(InfoResponse {
app: "rust-web".to_string(),
version: "1.0.0".to_string(),
rust_version: "1.75.0".to_string(),
})
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
println!("Starting server on port 8000...");
HttpServer::new(|| {
App::new()
.route("/health", web::get().to(health))
.route("/info", web::get().to(info))
.route("/", web::get().to(|| async { "Hello from Rust!" }))
})
.bind("0.0.0.0:8000")?
.run()
.await
}
# Cargo.toml
[package]
name = "rust-web"
version = "0.1.0"
edition = "2021"
[dependencies]
actix-web = "4"
serde = { version = "1", features = ["derive"] }
第二步:多阶段 Dockerfile
# Dockerfile
# 构建阶段
FROM rust:1.75 as builder
WORKDIR /app
COPY Cargo.toml Cargo.lock ./
COPY src ./src
# 构建 release 版本
RUN cargo build --release
# 运行阶段
FROM debian:bookworm-slim
# 安装运行时依赖
RUN apt-get update && apt-get install -y \
ca-certificates \
&& rm -rf /var/lib/apt/lists/*
# 创建非 root 用户
RUN groupadd -r appuser && useradd -r -g appuser appuser
WORKDIR /app
# 从构建阶段复制二进制文件
COPY --from=builder /app/target/release/rust-web .
# 切换用户
USER appuser
EXPOSE 8000
HEALTHCHECK --interval=30s --timeout=3s --retries=3 \
CMD curl -f http://localhost:8000/health || exit 1
CMD ["./rust-web"]
第三步:K8s 部署文件
# k8s/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: rust-web
labels:
app: rust-web
spec:
replicas: 3
selector:
matchLabels:
app: rust-web
template:
metadata:
labels:
app: rust-web
spec:
containers:
- name: rust-web
image: username/rust-web:1.0
ports:
- containerPort: 8000
resources:
requests:
memory: "64Mi"
cpu: "50m"
limits:
memory: "128Mi"
cpu: "200m"
livenessProbe:
httpGet:
path: /health
port: 8000
initialDelaySeconds: 10
periodSeconds: 10
readinessProbe:
httpGet:
path: /health
port: 8000
initialDelaySeconds: 5
periodSeconds: 5
# k8s/service.yaml
apiVersion: v1
kind: Service
metadata:
name: rust-web-service
spec:
selector:
app: rust-web
ports:
- protocol: TCP
port: 80
targetPort: 8000
type: ClusterIP
第四步:构建和部署
# 构建镜像
docker build -t rust-web:1.0 .
# 打标签并推送
docker tag rust-web:1.0 username/rust-web:1.0
docker push username/rust-web:1.0
# 部署到 K8s
kubectl apply -f k8s/
# 查看状态
kubectl get pods -l app=rust-web
# 查看日志
kubectl logs -f deployment/rust-web
# 更新镜像
kubectl set image deployment/rust-web rust-web=username/rust-web:2.0
完整项目结构
rust-web/
├── src/
│ └── main.rs
├── Cargo.toml
├── Cargo.lock
├── Dockerfile
└── k8s/
├── deployment.yaml
└── service.yaml
最佳实践
- 多阶段构建:分离编译和运行环境
- 最小基础镜像:debian:bookworm-slim 比 ubuntu 小很多
- 资源限制:Rust 应用内存占用低,可以设置较小的限制
- 健康检查:确保应用真正可用
- 非 root 用户:安全最佳实践
常见问题
Q: Rust 镜像为什么这么大? A: 使用多阶段构建,只复制编译后的二进制文件。
Q: 如何优化编译速度? A: 使用 cargo-chef 缓存依赖编译。
Q: 如何处理跨平台编译? A: 使用 cross 或 Docker buildx。
扩展挑战
- 实现零停机部署
- 添加 Prometheus 指标
- 实现分布式追踪
相关课程
| 课程 | 相关章节 |
|---|---|
| Rust | 异步编程:async/await |
| Docker | 多阶段构建 |
| K8s | Deployment |
| K8s | Service |