Agentic AI with Java: Live Cohort
DockerDockerfile Fundamentals

WORKDIR Instruction

Understand how WORKDIR sets the working directory inside a Docker image and why it keeps Dockerfiles clean.

WORKDIR sets the working directory inside a Docker image.

It is similar to using cd in a terminal, but it is written as a Dockerfile instruction. After Docker reaches a WORKDIR line, the following instructions run from that directory.

Why WORKDIR is useful

Without WORKDIR, you may need to write long paths again and again:

COPY app.jar /app/app.jar
CMD ["java", "-jar", "/app/app.jar"]

With WORKDIR, the Dockerfile becomes cleaner:

WORKDIR /app
COPY app.jar app.jar
CMD ["java", "-jar", "app.jar"]

Now Docker understands that app.jar is inside /app.

Basic syntax

The syntax is simple:

WORKDIR /app

If the directory does not exist, Docker creates it.

That means you usually do not need to run:

RUN mkdir /app

You can directly use WORKDIR /app.

Example with a Java application

A simple Dockerfile for a Java application may look like this:

FROM eclipse-temurin:17-jre
WORKDIR /app
COPY target/myapp.jar app.jar
EXPOSE 8080
CMD ["java", "-jar", "app.jar"]

Here is what happens:

InstructionMeaning
FROMStart from a Java runtime image
WORKDIR /appUse /app as the working directory
COPYCopy the JAR into /app
EXPOSEDocument that the app uses port 8080
CMDStart the Java application

WORKDIR affects later instructions

After this line:

WORKDIR /app

These instructions use /app as the current directory:

COPY . .
RUN ls
CMD ["node", "server.js"]

So COPY . . copies files into /app, RUN ls lists files inside /app, and CMD starts from /app.

Multiple WORKDIR instructions

You can use WORKDIR more than once:

WORKDIR /app
WORKDIR logs

The second line is relative to the first, so the final working directory becomes:

/app/logs

For beginner Dockerfiles, prefer one clear absolute WORKDIR, such as /app.

Good practice

Use WORKDIR in almost every application Dockerfile.

It makes paths easier to read and prevents confusion about where commands are running.

Think of WORKDIR as the default folder inside the image. Copying files, running commands, and starting the app become easier once that folder is clear.

Written By: Shiva Srivastava

How is this guide?

Last updated on