03 May 2019

Multi-stage build in Docker

Multi-stage build allows multiple FROM statements in a Dockerfile. The instructions follows each FROM statement until the next one & creates an intermediate image. The final FROM statement is the final base image.
Artifacts from intermediate stages can be copied using COPY --from='stageName' starting from 0 for the first base image. The artifacts not copied over are discarded. This allows to keep the final image light and only include the relevant artifacts.

FROM syntax is updated to specify stage name using 'as' 
FROM maven:3.5-jdk-8 as build

This allows to use the stage name instead of the number with --from option

lets take a look on a sample Dockerfile:

FROM maven:3.5-jdk-8 as build
COPY src /usr/src/myapp/src
COPY pom.xml /usr/src/myapp
RUN mvn -f /usr/src/myapp/pom.xml clean package
FROM jboss/wildfly:10.1.0 Final
COPY --from=BUILD /usr/src/myapp/target/people-1.0-SNAPSHOT.war \
/opt/jboss/wildfly/standalone/deployments/people.war

In this Dockerfile:

There are two FROM instructions. This means it is a two-stage build.
maven:3.5-jdk-8 is the base image for the first build. This is used to build the WAR file for the application. The first stage is named as BUILD.
jboss/wildfly:10.1.0.Final is the second and the final base image for the build. WAR file generated in the first stage is copied over to this stage using COPY --from syntax. The file is directly copied in the WildFly deployments directory.

Br
Punit

No comments:

Post a comment