user1807815
user1807815

Reputation: 93

To include maven in dockerfile or not?

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. Doesn't that just make the image larger? Is there a benefit of doing that?

Upvotes: 2

Views: 1536

Answers (2)

leoconco
leoconco

Reputation: 291

I think you are looking for Multi-stage builds. Example of a 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/.

With the multistage build, the maven dependencies wouldn't bloat the image as the first stage is discarded after copying the jar into the second stage. However, building the jar using CI/CD is more efficient and preferable most of the time.

Upvotes: 3

Rodrigo Silva
Rodrigo Silva

Reputation: 583

Usually I have a CI/CD 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 CI/CD strategy, build and deploy are different steps. I also believe your docker image should be as lean as possible.

Upvotes: 7

Related Questions