Mac 编译rust程序在Centos上运行
在Mac 上写的Rust程序,在Mac下编译出来的可执行程序是不能直接在Centos 上运行的,必须在Centos环境下编译的程序才能在Centos上运行,一个办法可以把代码上传到Centos在服务上编译,这个办法不太优雅,最好的办法是在Centos容器中编译
用 Docker 在 CentOS 容器里编译
拉一下centos:7镜像
dock pull centos:7
启动 CentOS 7 容器并挂盘
docker run -it -v ~/Mac源码目录:/src -w /src centos:7 bash
容器里一次性的安装脚本
# 装编译依赖
yum install -y gcc openssl-devel pkg-config
# 装 Rust
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
source $HOME/.cargo/env
如果安装依赖的时候提示: Cannot find a valid baseurl for repo: base/7/x86_64 CentOS 7 中出现的“无法为仓库找到有效的 baseurl”错误,通常是因为在 CentOS 7 于 2024 年 6 月 30 日达到生命周期终点后,官方镜像已迁移至归档库。主要的解决方案包括更新您的仓库配置文件以使用归档库镜像。
更新您的仓库配置文件以使用归档库镜像
sudo sed -i 's/mirrorlist/#mirrorlist/g' /etc/yum.repos.d/CentOS-Base.repo
sudo sed -i 's/#baseurl=http:\/\/mirror.centos.org/baseurl=http:\/\/vault.centos.org/g' /etc/yum.repos.d/CentOS-Base.repo
清除缓存
sudo yum clean all
sudo yum update
这就可以安装依赖了
编译
cargo build --release
退出容器后,二进制就在 ~/Mac源码目录/target/release/,直接拷到 CentOS 服务器即可运行,glibc 依赖完全匹配,无需再折腾
在Centos中使用systemctl管理你的程序
创建 systemd 单元文件
vim /etc/systemd/system/myapp.service
内容(按需改路径/端口/用户):
[Unit]
Description=My Axum App
After=network.target
[Service]
Type=simple
User=appuser # 建议单独建用户,不要用 root
Group=appuser
WorkingDirectory=/opt/myapp
ExecStart=/opt/myapp/myapp
Restart=always
RestartSec=5
Environment="RUST_LOG=info"
# 如果监听 80/443 需 root,可把 User/Group 注释掉,再加:
# AmbientCapabilities=CAP_NET_BIND_SERVICE
[Install]
WantedBy=multi-user.target
保存后:
systemctl daemon-reload
systemctl enable --now myapp # 立即启动并设开机自启
日常运维命令
systemctl status myapp # 看运行状态
journalctl -u myapp -f # 实时日志
systemctl restart myapp # 重启
systemctl stop myapp # 停止
systemd 会自动把进程拉起,日志也会集中进 journal,不需要再装 supervisor、pm2 之类的额外守护进程
文档信息
版权声明:可自由转载(请注明转载出处)-非商用-非衍生
发表时间:2026年1月4日 17:11