gpt4 book ai didi

docker - 使用 Docker 构建缓存 Rust 依赖项

转载 作者:行者123 更新时间:2023-11-29 08:17:28 24 4
gpt4 key购买 nike

我在 Rust + Actix-web 中有一个 hello world web 项目。我有几个问题。首先是代码的每次更改都会导致重新编译整个项目,包括下载和编译每个 crate 。我想像正常开发一样工作——这意味着缓存编译的箱子并且只重新编译我的代码库。第二个问题是它没有公开我的应用程序。无法通过网络浏览器访问

docker 文件:

FROM rust

WORKDIR /var/www/app

COPY . .

EXPOSE 8080

RUN cargo run

docker-compose.yml:

version: "3"
services:
app:
container_name: hello-world
build: .
ports:
- '8080:8080'
volumes:
- .:/var/www/app
- registry:/root/.cargo/registry

volumes:
registry:
driver: local

主要.rs:

extern crate actix_web;

use actix_web::{web, App, HttpServer, Responder};

fn index() -> impl Responder {
"Hello world"
}

fn main() -> std::io::Result<()> {
HttpServer::new(|| App::new().service(web::resource("/").to(index)))
.bind("0.0.0.0:8080")?
.run()
}

cargo .toml:

[package]
name = "hello-world"
version = "0.1.0"
authors = []
edition = "2018"

[dependencies]
actix-web = "1.0"

最佳答案

似乎您并不是唯一一个通过 docker 构建过程缓存 rust 依赖项的人。这是一篇很棒的文章,可以帮助您一路走来:https://blog.mgattozzi.dev/caching-rust-docker-builds/

它的要点是你首先需要一个 dummy.rs 和你的 Cargo.toml,然后构建它来缓存依赖项,然后稍后复制你的应用程序源代码,以免每次构建都使缓存无效。

Dockerfile

FROM rust
WORKDIR /var/www/app
COPY dummy.rs .
COPY Cargo.toml .
RUN sed -i 's#src/main.rs#dummy.rs#' Cargo.toml
RUN cargo build --release
RUN sed -i 's#dummy.rs#src/main.rs#' Cargo.toml
COPY . .
RUN cargo build --release
CMD ["target/release/app"]

CMD 应用程序名称“app”基于您在 Cargo.toml 中为二进制文件指定的名称。

dummy.rs

fn main() {}

Cargo.toml

[package]
name = "app"
version = "0.1.0"
authors = ["..."]
[[bin]]
name = "app"
path = "src/main.rs"

[dependencies]
actix-web = "1.0.0"

src/main.rs

extern crate actix_web;

use actix_web::{web, App, HttpServer, Responder};

fn index() -> impl Responder {
"Hello world"
}

fn main() -> std::io::Result<()> {
HttpServer::new(|| App::new().service(web::resource("/").to(index)))
.bind("0.0.0.0:8080")?
.run()
}

关于docker - 使用 Docker 构建缓存 Rust 依赖项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58473606/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com