Get a better understanding on WORKDIR instruction

What is WORKDIR

The WORKDIR instruction sets the working directory for any RUN, CMD, ENTRYPOINT, COPY and ADD instructions that follow it in the Dockerfile

https://docs.docker.com/engine/reference/builder/#workdir

WORKDIR instruction can be used multiple times

Both of the following instructions will effectively sets the working directory to /a/b.

WORKDIR /a
WORKDIR b
WORKDIR a
WORKDIR b

What if we don’t specify the WORKDIR

If we don’t specify the working directory there are two scenarios:

  • The WORKDIR will be set to /
  • Or, the WORKDIR will be used from the base image

Use the WORKDIR set in the base image

If we don’t specify the working directory, but the base image has the instruction, then it will be used the working directory sets in the base image.

FROM golang:1.7.3 AS builder
RUN pwd
docker build -t test-workdir .
Sending build context to Docker daemon  10.24kB
Step 1/2 : FROM golang:1.7.3 AS builder
 ---> ef15416724f6
Step 2/2 : RUN pwd
 ---> Running in 9f8a0dfc57e0
/go
Removing intermediate container 9f8a0dfc57e0
 ---> 4ceafd2ef636
Successfully built 4ceafd2ef636
Successfully tagged test-workdir:latest

Set the WORKDIR to /

If we don’t specify the working directory, but the base image doesn’t have the instruction, then the working directory will set to /.

FROM node:alpine3.10 AS builder
RUN pwd
docker build -t test-workdir .
Sending build context to Docker daemon  10.24kB
Step 1/2 : FROM node:alpine3.10 AS builder
alpine3.10: Pulling from library/node
89d9c30c1d48: Downloading [=>                                                 ]  59.39kB/2.787MB
89d9c30c1d48: Pull complete
7708a7b88cf9: Pull complete
1c96b50334bf: Pull complete
a0dc5889fe68: Pull complete
Digest: sha256:ebabd7c287a2852a78aaab721a6326471b9e0347c506c18fb97f7fd11ae5e41a
Status: Downloaded newer image for node:alpine3.10
 ---> 5f8b3338a759
Step 2/2 : RUN pwd
 ---> Running in 82631ae71897
/
Removing intermediate container 82631ae71897
 ---> 921767519d1a
Successfully built 921767519d1a
Successfully tagged test-workdir:latest

Leave a comment