Mvn Command Not Running from Dockerfile

I am trying to run “mvn clean install -e” in my Dockerfile after fetching the the codebase from GIT. But for some reason I get an error saying:

/bin/sh: mvn: not found

My Dockerfile looks something like this:

# AS <NAME> to name this stage as maven
FROM scratch
LABEL MAINTAINER="Sam"

#SETUP Ubuntu ENVIRONMENT
FROM ubuntu:latest as ubuntu

RUN export http_proxy=MY_HTTP_PROXY && export https_proxy=MY_HTTPS_PROXY

#INSTALL MAVEN
RUN mkdir -p $HOME/maven3 && cd $HOME/maven3
FROM maven:3.8.6-eclipse-temurin-11-alpine AS maven
ENV M2_HOME=$HOME/maven3

#INSTALL JAVA
RUN mkdir -p $HOME/jdk11 && cd $HOME/jdk11
FROM eclipse-temurin:11-jdk-alpine AS jdk
ENV JAVA_HOME=$HOME/jdk11

ENV PATH=$PATH:$M2_HOME/bin:$JAVA_HOME/bin

RUN apk update && apk add git && apk add net-tools procps openssh-client openssh-server

RUN mkdir -p $HOME/images/lib/ && cd $HOME/images/lib/

RUN git clone MY_GIT_URL

RUN mvn clean install -e

But when I run docker build I get the following error at the end:


Step 15/15 : RUN mvn clean install -e
 ---> Running in 264c505d131a
/bin/sh: mvn: not found
The command '/bin/sh -c mvn clean install -e' returned a non-zero code: 127

I am new to Docker, so learning it as I got along. But this one got me stumped. Any help would be appreciated.

I have just realized I had my response as a draft without actually sending it. Sorry about that. I guess you have already solved this issue, but this is what I wanted to send.

You don’t have maven in your last stage where you want to use it. A stage is just a definition of one build. Programs in the previous stages will not be in the last stage.

Hello,

not sure why using multistage when you have maven, jdk and alpine available in below simple Dockerfile

# AS <NAME> to name this stage as maven
FROM scratch
LABEL MAINTAINER="Sam"
FROM maven:3.8.6-eclipse-temurin-11-alpine AS maven
RUN apk update && apk add git && apk add net-tools procps openssh-client openssh-server
RUN mkdir -p $HOME/images/lib/ && cd $HOME/images/lib/
#RUN git clone MY_GIT_URL
RUN mvn --version
RUN mvn clean install -e

if you have specific requirement for ubuntu and eclipse-temurin image you have to make the docker file properly with below command in Dockerfile

COPY --from=<previous-stage-name> <source> <destination>

Hope this helps.

1 Like

Probably because running the application does not require Maven, only Java, so the image could be smaller without installing build dependencies. The problem was that the stages were used wrong without using those in the final stage, which I haven’t noticed then, only the fact that maven was not in the final image.

So as you rigthly pointed out, COPY --from is one of the keys of using multi-stage builds correctly.