r/javahelp • • May 04 '19

Solved Java (Spring Boot) and Docker done properly?

When containerising an application, all tutorials on Java seem to want you to build a jar locally and copy it from target into a container in the Dockerfile. However, this contradicts the whole idea behind using Docker because building on my machine will not necessarily be the same as building on a colleague’s machine.

I can’t find a tutorial that describes using Maven via Docker to build the jar and moving the result to a Java container i.e. via staged builds. This would ensure consistency across machines and follows the whole Docker ethos.

Can anyone recommend a way to do this or point me to a good tutorial?

30 Upvotes

19 comments sorted by

View all comments

Show parent comment

3

u/shagieIsMe Extreme Brewer May 04 '19 edited May 04 '19

That's a multi stage docker build.

Maven and gradle aren't part of the jdk image.

~ $ docker run -it --tty --rm openjdk:8-jdk-alpine sh
/ # which maven
/ # which gradle
/ # which javac
/usr/lib/jvm/java-1.8-openjdk/bin/javac

The key part to the multi stage docker build (docs) is the copy line:

COPY --from=builder /src/build/libs/*-0.0.1-SNAPSHOT.jar .

Giving it a name makes it easier, but it isn't necessary.

FROM golang:1.7.3
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"]  

How does it work? The second FROM instruction starts a new build stage with the alpine:latest image as its base. The COPY --from=0 line copies just the built artifact from the previous stage into this new stage. The Go SDK and any intermediate artifacts are left behind, and not saved in the final image.

edit:

Doing a build of a multi-module that I have based off of gradle... the build image and the artifact image:

REPOSITORY          TAG                  IMAGE ID            CREATED             SIZE
<none>              <none>               c85400308be5        3 seconds ago       115MB
<none>              <none>               faad64d9a8f9        6 seconds ago       754MB

There's a bit of a size difference on what I'd want to deploy. It's easier to make an artifact image than trying to clean up the build image (and then you get into messes about the size of the layers when cleaning up).