The RUN instruction executes an operating-system command inside a temporary container while Docker builds an image. The command must exist in the base image named by FROM, and its output becomes part of an image layer. If the command fails, the build fails. section 4.1
RUN is useful for installing dependencies, compiling source code, generating files, and running tests. Each command creates a build step, so expensive operations can be placed after stable COPY instructions to benefit from Docker's layer cache. section 4.2
A practical RUN workflow includes:
- Choose a base image containing the command or tool that RUN will invoke. section 4.1
- Separate stable, expensive operations such as dependency retrieval from frequently changing source-code steps. section 4.2
- Use RUN in builder stages when compilation or testing should stay out of the final runtime image. section 4.1
- Check commands for platform portability: OS commands that work on Linux may not work on Windows or another architecture. section 12.6
Building a Java application
A builder stage runs `mvn -B dependency:go-offline` after copying `pom.xml`, then runs `mvn package` after copying the source. Docker can reuse the dependency layer when the Maven definition has not changed; a failed dependency download or compilation stops the build. section 4.2
Listing 4.2 Dockerfile for building a Java app with Maven
FROM diamol/maven:2e AS builder WORKDIR /usr/src/iotd COPY pom.xml . RUN mvn -B dependency:go-offline COPY . . RUN mvn package # app FROM diamol/openjdk:2e WORKDIR /app COPY --from=builder /usr/src/iotd/target/iotd-service-0.1.0.jar . EXPOSE 80 ENTRYPOINT ["java", "-jar", "/app/iotd-service-0.1.0.jar"]
Inspect the complete Maven Dockerfile to see RUN placement, builder-stage compilation, and copying the resulting JAR into a runtime stage. section 4.2

