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

问题描述 投票:-2回答:1

我有一个简单的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”})

路径是否存在错误

我的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镜像中的文件?

file docker rust
1个回答
0
投票

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

另外:您似乎在代码中使用相对路径。你确定你的容器中的相对路径是否正确?你没有任何WORKDIR指令,所以你的工作目录是/

问题是没有定义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
© www.soinside.com 2019 - 2024. All rights reserved.