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

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

主要的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 汤姆:

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

[dependencies]
actix-web = "1.0"

推荐答案

似乎不止你一个人在努力通过docker构建过程缓存依赖关系.这里有一篇很好的文章可以帮助你:https://blog.mgattozzi.dev/caching-rust-docker-builds/

要点是你需要一个假人.还有你的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()
}

Rust相关问答推荐

如何在tauri—leptos应用程序中监听后端值的变化?""

trait声明中的生命周期参数

无法在线程之间安全地发送future (&Q;)&错误

如何装箱生命周期相关联的两个对象?

rust 蚀生命周期 行为

为什么`Vec i64`的和不知道是`Option i64`?

默认特征实现中的生命周期问题

在使用AWS SDK for Rust时,如何使用硬编码访问密钥ID和密钥凭据?

为什么我们需要std::thread::scope,如果我们可以使用thread.join()在函数的生命周期内删除引用?

类型批注需要静态生存期

如何修复数组中NewType导致的运行时开销

try 创建随机数以常量

Rust wasm 中的 Closure::new 和 Closure::wrap 有什么区别

如何返回 struct 体中向量的切片

如何保存指向持有引用数据的指针?

bcrypt 有长度限制吗?

切片不能被 `usize` 索引?

如何创建递归borrow 其父/创建者的 struct ?

如果我不想运行析构函数,如何移出具有析构函数的 struct ?

如何为返回正确类型的枚举实现 get 方法?