skip to Main Content

How can I build a Docker image of my Rust project containing local dependencies?

My Cargo.toml looks like this:

[package]
name = "backend"
version = "0.1.0"
edition = "2021"


[dependencies]
actix-web = "4"
juniper = "0.15.10"
my_libs = {path = "/Users/dev/projects/api/api_libs/"}

And my Dockerfile:

FROM rust:1.60.0-slim-buster as builder
WORKDIR /app
ENV CARGO_HOME=/workdir/.cargo
COPY ./Cargo.toml ./Cargo.lock ./

COPY . .

RUN cargo build --release

When I run docker build, I get the following error:

error: failed to get my_libs as a dependency of package backend v0.1.0 (/app)

How can I fix this?

2

Answers


  1. The path you’ve given will be interpreted by docker as a path inside the container, so it’s normal that it does not exist.

    You’re also not able to copy files that do not exist within the directory of the Dockerfile.

    Either publish your lib on crates.io or make it available via a git url (i.e.: github) which can be installed with cargo.

    Or copy the lib locally so that you can copy it into your container.

    Login or Signup to reply.
  2. Well of course you have to copy your local dependencies to the container as well.
    If I recall correctly docker doesn’t work that great with absolute paths so I’ve moved the api_libs folder into the one for external and adjusted the Cargo.toml to:

    api_libs = {path = "./api_libs/"}
    

    now when we do the copy

    COPY . .
    

    we copy the dependencies as well and thus docker build . succeeds.

    By the way your first COPY ./Cargo.toml ./Cargo.lock ./ is redundant since COPY . . would copy them anyways and you do nothing in between.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search