Docker RUN fails while working in docker command line

I am trying to build an image for my executable. The Dockerfile looks like

FROM ocaml/opam:debian-12-ocaml-4.13

USER root
RUN sudo apt-get -y install m4 libev-dev

RUN mkdir -p /usr/src/lib
COPY lib/ /usr/src/lib

RUN opam install ocamlfind camlp5 yojson num opium
RUN eval $(opam config env)
WORKDIR /usr/src/lib
RUN make

when building image, it fails with error ERROR: failed to solve: process "/bin/sh -c make" did not complete successfully: exit code: 2.

When I try to build image without final RUN command

FROM ocaml/opam:debian-12-ocaml-4.13

USER root
RUN sudo apt-get -y install m4 libev-dev

RUN mkdir -p /usr/src/lib
COPY lib/ /usr/src/lib

RUN opam install ocamlfind camlp5 yojson num opium
RUN eval $(opam config env)
WORKDIR /usr/src/lib

the build succeeds, and I can then execute my RUN command with docker run -i -t gfca make (gfca is the name of my container) – succeeds too.

Why it succeeds when running command afterwards and not in Dockerfile ?
Is there some difference when running the command and specifying command in Dockerfile ?

Each RUN instruction in the dockerfile starts a new temporary container. You cant use an eval command to export variables and try to use the variables in a new container. That is why you should see chaining commnads in a single RUN instruction

WORKDIR /usr/src/lib
RUN eval $(opam config env) \
 && make

When you ran the docker run command, the make command in the container ranwithout exporting variables before it. Whether it worked properly without it, I have no idea.

It solve my case.
I wasn’t aware that RUN instruction created a new container and then env variables were not accessible from there.
Thanks a lot!

Alternatively, if you need that environment variable to persist for all containers created from the image you can use the ENV instruction

That would of course persist to all RUN steps coming afterwards