Linux服务器配置支持Rust应用的实操指南
一 环境准备与工具链安装
sudo dnf update -y && sudo dnf install -y gcc make openssl-devel pkgconfig gitsudo dnf install -y rust-toolset,验证:rustc --version、cargo --versionexport RUSTUP_DIST_SERVER=https://mirrors.ustc.edu.cn/rust-staticexport RUSTUP_UPDATE_ROOT=https://mirrors.ustc.edu.cn/rust-static/rustupcurl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | shsource $HOME/.cargo/env,验证:rustc --version、cargo --version二 获取代码与构建发布版本
scp -r ./your-rust-project user@your-server-ip:/home/user/git clone https://your-git-repo.git && cd your-rust-projectcargo build --release,产物位于 target/release/your-binary-namescp target/release/your_binary user@remote:/opt/yourapp/三 以 systemd 托管与运行
[Unit]
Description=My Rust App
After=network.target
[Service]
Type=simple
User=appuser
Group=appuser
WorkingDirectory=/home/appuser/your-rust-project
ExecStart=/home/appuser/your-rust-project/target/release/your-binary-name
Restart=always
RestartSec=5
Environment=RUST_LOG=info
Environment=RUST_BACKTRACE=1
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reloadsudo systemctl enable --now yourapp.servicesudo systemctl status yourapp.servicesudo journalctl -u yourapp.service -f四 网络与反向代理配置
sudo firewall-cmd --permanent --add-port=8080/tcp && sudo firewall-cmd --reloadsudo dnf install -y nginx && sudo systemctl enable --now nginxserver {
listen 80;
server_name your-domain.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;
}
}
sudo nginx -s reload五 容器化与运维实践
FROM rust:1.75-slim AS builder
WORKDIR /app
COPY . .
RUN cargo build --release
FROM debian:bookworm-slim
RUN apt-get update && apt-get install -y ca-certificates && rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY --from=builder /app/target/release/your-binary-name /usr/local/bin/
CMD ["your-binary-name"]
docker build -t my-rust-app . && docker run -d -p 8080:8080 my-rust-appjournalctl -u yourapp.service -f,必要时设置 RUST_BACKTRACE=1