Unable to read file inside Docker image using std::fs methods


#1

I have a simple rust application which reads JSON files like below

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());
}

The file when run with cargo run returns the correct file path, but when I add the files inside a docker image similar to one mentioned here (https://github.com/emk/rust-musl-builder/blob/master/examples/using-diesel/Dockerfile),I get below errors:

Canonicalized pathErr(Os { code: 2, kind: NotFound, message: “No such file or directory” })
Does path exist false

My Dockerfile looks like this:

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 

Does anyone else face same issue with reading file inside a Docker image?


#2

Just a guess but you may not have the environment in the docket container configured as you expect. You can execute the pwd shell command from your app and pipe its stdout to see where the kernel thinks the process’s current working directory is; probably /.

That would mean the environment isn’t configured appropriately for the relative path to work. You should usually use absolute paths to avoid this issue, or (less preferred) change the image entry point to a shell script that cds to the correct working directory and configures the rest of the runtime environment needed by the application.


#3

To follow up on the excellent pwd suggestion: it might be simpler to use env::current_dir.


#4

Thanks @parasyte @mgeisler. I found the root cause of the issue . It was because the WORKDIR was not set inside the Docker container and adding it fixed the issue