The WORKDIR instruction

We have seen the WORKDIR instruction used in some of the examples used to demonstrate other instructions. It is sort of like a combination of the Linux cd and mkdir commands. The WORKDIR instruction will change the current working directory in the image to the value provided in the instruction. If any segment of the path in the parameter of the WORKDIR instruction does not yet exist, it will be created as part of the execution of the instruction. The syntax for the WORKDIR instruction is as follows:

# WORKDIR instruction syntax
WORKDIR instruction syntax
WORKDIR /path/to/workdir

The WORKDIR instruction can use ENV or ARG parameter values for all or part of its parameter. A Dockerfile can have more than one WORKDIR instruction, and each subsequent WORKDIR instruction will be relative to the previous one (if a relative path is used). Here is an example that demonstrates this possibility:

# WORKDIR instruction Dockerfile for Docker Quick Start
FROM alpine
# Absolute path...
WORKDIR /
# relative path, relative to previous WORKDIR instruction
# creates new folder
WORKDIR sub-folder-level-1
RUN touch file1.txt
# relative path, relative to previous WORKDIR instruction
# creates new folder
WORKDIR sub-folder-level-2
RUN touch file2.txt
# relative path, relative to previous WORKDIR instruction
# creates new folder
WORKDIR sub-folder-level-3
RUN touch file3.txt
# Absolute path, creates three sub folders...
WORKDIR /l1/l2/l3
CMD ["sh"]

Building the image from this Dockerfile will result in the image having three levels of nested folders. Running a container from the image and listing the files and folders will look like this:

The WORKDIR instruction will create a zero-byte-sized layer in the resulting image.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.116.101