What is a Dockerfile and what are the key instructions?
Fast recall
Quick revision
Core answer
FROM, WORKDIR, COPY, RUN, ARG, ENV, USER, EXPOSE, ENTRYPOINT, and CMD. Instructions affect filesystem state or image metadata, but it is inaccurate to say every instruction creates a filesystem layer.Interview-ready guide
Interview answer
A Dockerfile is a text build definition for creating an image from a base and a build context. FROM selects a base or starts a new stage. WORKDIR sets the working directory, COPY adds context files, and RUN executes a build step. ARG provides build-time input, while ENV records environment defaults. USER, EXPOSE, ENTRYPOINT, and CMD configure runtime behavior or metadata.
For a Spring Boot service I can use a JDK build stage to test and package the JAR, then copy it into a smaller runtime stage, set a non-root user, and use exec-form ENTRYPOINT. A .dockerignore keeps irrelevant files out of the build context.
Not every instruction creates a filesystem layer—some change image configuration. I also avoid baking secrets into ARG, ENV, or RUN, pin trusted base images, combine package-manager update/install safely, and rebuild the image rather than editing a live container.
What is a Dockerfile and what are the key instructions
Direct Answer
A Dockerfile is a text build definition that turns a base image and build context into an image. Common instructions are FROM, WORKDIR, COPY, RUN, ARG, ENV, USER, EXPOSE, ENTRYPOINT, and CMD. Instructions affect filesystem state or image metadata, but it is inaccurate to say every instruction creates a filesystem layer.
Code Example
FROM eclipse-temurin:17-jre-alpine
WORKDIR /app
COPY target/order-service-0.0.1-SNAPSHOT.jar app.jar
EXPOSE 8080
ENV SPRING_PROFILES_ACTIVE=prod
ENTRYPOINT ["java", "-jar", "app.jar"]
Common Mistakes & Pitfalls
- Too many layers from separate RUN commands: Running apt-get update in one RUN and apt-get install in another creates two layers instead of one. Combine related commands with && to reduce layers: RUN apt-get update && apt-get install -y curl.
- Copying everything before dependencies: If you COPY the entire project directory first, then run mvn package, Docker invalidates the cache every time any file changes. Instead, copy pom.xml first, run mvn dependency:go-offline to cache dependencies, then copy source code.
- Not using multi-stage builds for Spring Boot: Freshers often copy the target JAR from their local machine into the image. Better: use a multi-stage Dockerfile that runs mvn package inside a builder stage, then copies only the final JAR to a slim runtime stage, avoiding bloated images with Maven and source code.
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.