我在Rust + Actix-web中有hello世界网络项目。我有几个问题。首先是代码的每次更改都会导致重新编译整个项目,包括下载和编译每个板条箱。我想像正常开发一样工作-这意味着缓存已编译的板条箱,仅重新编译我的代码库。第二个问题是它不会暴露我的应用程序。通过网络浏览器无法访问
Dockerfile:
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
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()
}
Cargo.toml:
[package]
name = "hello-world"
version = "0.1.0"
authors = []
edition = "2018"
[dependencies]
actix-web = "1.0"
似乎您并不孤单地通过docker build过程来缓存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()
}