beginners/dockerfile/WORKDIR_instruction.md
The WORKDIR directive in Dockerfile defines the working directory for the rest of the instructions in the Dockerfile. The WORKDIR instruction wont create a new layer in the image but will add metadata to the image config. If the WORKDIR doesn’t exist, it will be created even if it’s not used in any subsequent Dockerfile instruction. you can have multiple WORKDIR in same Dockerfile. If a relative path is provided, it will be relative to the previous WORKDIR instruction.
WORKDIR /path/to/workdir
If no WORKDIR is specified in the Dockerfile then the default path is /. The WORKDIR instruction can resolve environment variables previously set in Dockerfile using ENV.
Dockerfile
FROM alpine:3.9.3
LABEL maintainer="Collabnix"
WORKDIR /opt
$ docker build -t workdir:v1 .
$ docker run -it workdir:v1 pwd
Dockerfile
FROM alpine:3.9.3
LABEL maintainer="Collabnix"
WORKDIR /opt
RUN echo "Welcome to Docker Labs" > opt.txt
WORKDIR folder1
RUN echo "Welcome to Docker Labs" > folder1.txt
WORKDIR folder2
RUN echo "Welcome to Docker Labs" > folder2.txt
$ docker build -t workdir:v2 .
$ docker run -it workdir:v2 pwd
Dockerfile
FROM alpine:3.9.3
LABEL maintainer="Collabnix"
WORKDIR /opt/folder1
RUN echo "Welcome to Docker Labs" > opt.txt
WORKDIR /var/tmp/
$ docker build -t workdir:v3 .
$ docker run -it workdir:v3 pwd
Dockerfile
FROM alpine:3.9.3
LABEL maintainer="Collabnix"
ENV DIRPATH /myfolder
WORKDIR $DIRPATH
$ docker build -t workdir:v4 .
$ docker run -it workdir:v4 pwd
Next >> Lab #7: RUN instruction