gpt4 book ai didi

file - 无法使用 std::fs 方法读取 Docker 镜像中的文件

转载 作者:行者123 更新时间:2023-11-29 08:36:14 26 4
gpt4 key购买 nike

我有一个简单的 Rust 应用程序,它读取如下 JSON 文件:

fn main() {
let config_dir = std::path::PathBuf::from("config/endpoints.json");
println!(">>>>>>> Canonicalized path {:?}", std::fs::canonicalize(&config_dir));

println!(">>>>>>>>read endpoint file");
println!("Does file exist? {}", std::path::Path::new("config/endpoints.json").exists());
}

应用程序在使用 cargo run 运行时返回正确的文件路径,但是当我将文件添加到类似于 the rust-musl-builder 的 Docker 镜像中时,我得到错误:

Canonicalized pathErr(Os { code: 2, kind: NotFound, message: "No such file or directory" })

Does path exist false

我的 Dockerfile 看起来像这样

FROM ekidd/rust-musl-builder AS builder

# Add our source code.
ADD . ./

RUN sudo chown -R rust:rust /home/rust

RUN cargo build --release

FROM alpine:latest

RUN apk --no-cache add ca-certificates

EXPOSE 3001

COPY --from=builder \
/home/rust/src/config/ \
/usr/local/bin/config/

COPY --from=builder \
/home/rust/src/target/x86_64-unknown-linux-musl/release/app \
/usr/local/bin/

RUN chmod a+x /usr/local/bin/app

ENV RUST_BACKTRACE=1

CMD /usr/local/bin/app

如何读取 Docker 镜像中的文件?

最佳答案

我根据 larsks comment above 找到了这个问题的解决方案:

Also: you seem to be using relative paths in your code. Are you certain those relative paths are going to be correct in your container? You don't have any WORKDIR directives, so you working directory is /.

问题是没有定义 WORKDIR,因此文件读取发生在路径 / 中。像下面这样更改 Dockerfile(注意 WORKDIR/usr/local/bin)解决了这个问题:

FROM alpine:latest

RUN apk --no-cache add ca-certificates

EXPOSE 3001

WORKDIR /usr/local/bin

COPY --from=builder \
/home/rust/src/config/ \
/usr/local/bin/config/

COPY --from=builder \
/home/rust/src/target/x86_64-unknown-linux-musl/release/app \
/usr/local/bin/

RUN chmod a+x /usr/local/bin/app

ENV RUST_BACKTRACE=1

CMD /usr/local/bin/app

关于file - 无法使用 std::fs 方法读取 Docker 镜像中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50670951/

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