Home > Back-end >  To include maven in dockerfile or not?
To include maven in dockerfile or not?

Time:09-28

I have this working simple dockerfile. FROM openjdk:8-jdk-alpine WORKDIR /data COPY target/*.jar, myapp.jar ENTRYPOINT ["java","-jar",myapp.jar]

I build my jar using maven either locally or in a pipeline then use that .jar here. I've seen many examples installing maven in the dockerfile instead of doing the build before. Doesnt that just make the image larger? Is there a benefit of doing that?

CodePudding user response:

Usually I have a CICD server which I use for building my jar file and then I generate a docker image using it. Build a jar consumes resources and doing it when you're running your docker container can take longer depending on your configuration. In a normal CICD strategy, build and deploy are different steps. I also believe your docker image should be as lean as possible.

That's my opinion.

I hope I could help you somehow.

CodePudding user response:

I think you are looking for Multi-stage builds. Example of multistage Dockerfile:

# syntax=docker/dockerfile:1
FROM golang:1.16
WORKDIR /go/src/github.com/alexellis/href-counter/
RUN go get -d -v golang.org/x/net/html  
COPY app.go ./
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app .

FROM alpine:latest  
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=0 /go/src/github.com/alexellis/href-counter/app ./
CMD ["./app"]  

Notice the COPY --from=0 ... line, it's copying the result of the build that happens in the first container to the second. These mutistage builds are good idea for builds that need to install their own tools in specific versions. Example taken from https://docs.docker.com/develop/develop-images/multistage-build/

  • Related