温馨提示×

怎样用debian跑rust项目

小樊
44
2026-10-08 02:43:25
栏目: 编程语言

下面给你一份从 零开始在 Debian 上运行 Rust 项目 的实用流程,覆盖常见情况(新项目 / 已有项目 / 服务器运行)。


一、在 Debian 上安装 Rust

1. 更新系统

sudo apt update
sudo apt upgrade -y

2. 安装依赖(编译需要)

sudo apt install -y build-essential curl git

3. 安装 Rust(官方推荐方式)

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

按提示选择 1) Default installation

4. 加载环境变量

source $HOME/.cargo/env

5. 验证

rustc --version
cargo --version

二、运行一个新的 Rust 项目

1. 创建项目

cargo new my_project
cd my_project

目录结构:

my_project
├── Cargo.toml
└── src
    └── main.rs

2. 运行项目

cargo run

输出类似:

Hello, world!

三、运行已有的 Rust 项目(从 Git 拉取)

git clone https://github.com/xxx/xxx.git
cd xxx
cargo run

如果是 release 模式(性能更好):

cargo run --release

四、只编译不运行

cargo build
# 或
cargo build --release

生成文件:

target/debug/项目名
target/release/项目名

直接运行:

./target/release/项目名

五、在 Debian 服务器上长期运行(后台)

方式 1:nohup

cargo build --release
nohup ./target/release/项目名 &

方式 2:systemd(推荐)

创建服务文件:

sudo nano /etc/systemd/system/rustapp.service

示例:

[Unit]
Description=Rust App
After=network.target

[Service]
User=youruser
WorkingDirectory=/home/youruser/my_project
ExecStart=/home/youruser/my_project/target/release/项目名
Restart=always

[Install]
WantedBy=multi-user.target

启用:

sudo systemctl daemon-reload
sudo systemctl enable rustapp
sudo systemctl start rustapp

查看状态:

sudo systemctl status rustapp

六、常见问题

1. cargo: command not found

source $HOME/.cargo/env

或写入 .bashrc:

echo 'source $HOME/.cargo/env' >> ~/.bashrc

2. 编译太慢

  • 使用 --release
  • 或换国内镜像(如 tuna / ustc)

3. 需要特定 Rust 版本

rustup install 1.75.0
rustup default 1.75.0

如果你愿意,可以告诉我:

  • 是 桌面 Debian 还是服务器
  • 是 Web / CLI / 后台服务
  • 是否使用 Docker

我可以直接给你更精确的运行方案。

0 踩