Docker/Image/Multi-stage builds

Aus Foxwiki
Version vom 20. November 2026, 11:15 Uhr von Dirkwagner (Diskussion | Beiträge) (Die Seite wurde neu angelegt: „== Multi-stage builds == Multi-stage builds are an incredibly powerful tool to help use multiple stages to create an image * There are several advantages for them :* Separate build-time dependencies from runtime dependencies :* Reduce overall image size by shipping only what your app needs to run === Maven/Tomcat example === When building Java-based applications, you need a JDK to compile the source code to Java bytecode * However, that JDK isn't needed…“)
(Unterschied) ← Nächstältere Version | Aktuelle Version (Unterschied) | Nächstjüngere Version → (Unterschied)
Wechseln zu:Navigation, Suche

Multi-stage builds

Multi-stage builds are an incredibly powerful tool to help use multiple stages to create an image

  • There are several advantages for them
  • Separate build-time dependencies from runtime dependencies
  • Reduce overall image size by shipping only what your app needs to run

Maven/Tomcat example

When building Java-based applications, you need a JDK to compile the source code to Java bytecode

  • However, that JDK isn't needed in production
  • Also, you might be using tools like Maven or Gradle to help build the app
  • Those also aren't needed in your final image
  • Multi-stage builds help
# syntax=docker/dockerfile:1
FROM maven AS build
WORKDIR /app
COPY . 
RUN mvn package
FROM tomcat
COPY --from=build /app/target/file.war /usr/local/tomcat/webapps

In this example, you use one stage (called build) to perform the actual Java build using Maven

  • In the second stage (starting at FROM tomcat), you copy in files from the build stage
  • The final image is only the last stage being created, which can be overridden using the --target flag

React example

When building React applications, you need a Node environment to compile the JS code (typically JSX), SASS stylesheets, and more into static HTML, JS, and CSS

  • If you aren't doing server-side rendering, you don't even need a Node environment for your production build

You can ship the static resources in a static nginx container

# syntax=docker/dockerfile:1
FROM node:lts AS build
WORKDIR /app
COPY package* yarn.lock ./
RUN yarn install
COPY public ./public
COPY src ./src
RUN yarn run build
FROM nginx:alpine
COPY --from=build /app/build /usr/share/nginx/html

In the previous Dockerfile example, it uses the node:lts image to perform the build (maximizing layer caching) and then copies the output into an nginx container