8

These are the first 2 lines of a Dockerfile:

FROM node:12
WORKDIR /code

Here are some things I don't understand: From docker's documentation I know that the 2nd line sets the working directory to /code. Where does this process occur? Does it happen when docker runs the second line of the Dockerfile, while creating the image? If /code doesn't exist, does it get created by docker? Where will /code be created? In the root directory of the image?

youhatch
  • 141
  • 3
  • 7

3 Answers3

13

The Dockerfile WORKDIR directive

... sets the working directory.... If the WORKDIR doesn’t exist, it will be created even if it’s not used in any subsequent Dockerfile instruction.

I occasionally see SO questions that RUN mkdir a directory before switching WORKDIR to it. Since WORKDIR will create the directory, this isn't necessary.

All paths in a Dockerfile are always inside the image, except for the source paths for COPY and ADD instructions, which are inside the build context directory on the host. Absolute paths like /code will be directly inside the root directory in the image, following normal Unix conventions.

You can run temporary containers off of your image to examine this, even if the Dockerfile isn't complete yet.

host$ docker build -t my-image .
host$ docker run --rm my-image ls -l /
host$ docker run --rm -it my-image /bin/sh
0123456789ab# ls -l /
0123456789ab# exit

(This will always work, assuming the image includes core tools like sh and ls. docker exec requires the container to be running first; while you're refining the Dockerfile this may not be possible yet.)

David Maze
  • 130,717
  • 29
  • 175
  • 215
3

The Workdir /path will be created inside the container.

To test this you can do sh into your container.

Steps:

docker exec -it <container-id> sh

ls (Here you will see WORKDIR)

If you want to view the intermediate image layers from your custom image

docker image inspect < image-name >

GnanaJeyam
  • 2,780
  • 16
  • 27
1

The default WORKDIR driectory if this is not specified, is the / directory.

More info at the following link, https://www.geeksforgeeks.org/docker-workdir-instruction/

Shaqil Ismail
  • 1,794
  • 1
  • 4
  • 5