How to use Docker multi-stage build in your project

What is Docker multi-stage build?

- Docker multi-stage build allows you to use temporary images in the same Dockerfile. This is known as stages.

 

- Temporary images can be used to generate static artifacts - executable files, JS bundles, JAR files - running tests, generate static analysis, etc, before building the final image.

 

- Typically, teams use CI jobs to do that or more than one Dockerfile.

 

- The entire release process can be automated in the same Dockerfile reducing the number and size of layers in the final image.

Demo with Java

FROM maven:3.8.4-openjdk-17 AS builder

WORKDIR /app

COPY . ./

RUN mvn clean package


FROM openjdk:17-alpine

COPY --from=builder /app/target/rest-api-0.0.1-SNAPSHOT.war app.war

EXPOSE 8081

CMD ["java","-jar","/app.war"]
mvn archetype:generate \
	-DarchetypeGroupId=org.apache.maven.archetypes \
	-DarchetypeArtifactId=maven-archetype-quickstart \
	-DarchetypeVersion=1.4
docker run -it --rm my-java-app:latest
docker images | grep my-java

Demo with React JS

FROM node:16.13.2-alpine AS builder

WORKDIR /app

COPY package.json ./
RUN npm install

COPY . ./

RUN npm run test
RUN npm run build


FROM nginx:1.21.5-alpine

COPY --from=build /app/build /usr/share/nginx/html/

EXPOSE 80

CMD ["nginx", "-g", "daemon off;"]
npx create-react-app my-app

cd my-app
npm start
docker run -it --rm -p 80:80 my-react-app:latest
docker images | grep my-react

Use case

- About our scenery

 

- Training a complex Kaldi-ASR model

Thanks

https://github.com/johnidm

How to use Docker multi-stage build in your project

By Johni Douglas Marangon

How to use Docker multi-stage build in your project

  • 140