Changing users and working directory

Introduction to Docker

Tim Sangster

Software Engineer @ DataCamp

Dockerfile instruction interaction

FROM, RUN, and COPY interact through the file system.

COPY /projects/pipeline_v3/start.sh /app/start.sh
RUN /app/start.sh

Some influence other instructions directly:

  • WORKDIR: Changes the working directory for all following instructions
  • USER: Changes the user for all following instructions
Introduction to Docker

WORKDIR - Changing the working directory

Starting all paths at the root of the file system:

COPY /projects/pipeline_v3/ /app/

Becomes cluttered when working with long paths:

COPY /projects/pipeline_v3/ /home/my_user_with_a_long_name/work/projects/app/

Alternatively, use WORKDIR:

WORKDIR /home/my_user_with_a_long_name/work/projects/
COPY /projects/pipeline_v3/ app/
Introduction to Docker

RUN in the current working directory

Instead of using the full path for every command:

RUN /home/repl/projects/pipeline/init.sh
RUN /home/repl/projects/pipeline/start.sh

Set the WORKDIR:

WORKDIR /home/repl/projects/pipeline/
RUN ./init.sh
RUN ./start.sh
Introduction to Docker

Changing the startup behavior with WORKDIR

Instead of using the full path:

CMD /home/repl/projects/pipeline/start.sh

Set the WORKDIR:

WORKDIR /home/repl/projects/pipeline/
CMD start.sh

Overriding command will also be run in WORKDIR:

docker run -it pipeline_image start.sh
Introduction to Docker

Linux permissions

  • Permissions are assigned to users.
  • Root is a special user with all permissions.

$$

Best practice

  • Use root to create new users with permissions for specific tasks.
  • Stop using root.
Introduction to Docker

Changing the user in an image

Best practice: Don't run everything as root

Ubuntu -> root by default

FROM ubuntu         --> Root user by default
RUN apt-get update  --> Run as root

USER Dockerfile instruction:

FROM ubuntu         --> Root user by default
USER repl           --> Changes the user to repl
RUN apt-get update  --> Run as repl
Introduction to Docker

Changing the user in a container

Dockerfile setting the user to repl:

FROM ubuntu         --> Root user by default
USER repl           --> Changes the user to repl
RUN apt-get update  --> Run as repl 

Will also start containers with the repl user:

docker run -it ubuntu bash
repl@container: whoami
repl
Introduction to Docker

Summary

Usage Dockerfile Instruction
Change the current working directory WORKDIR <path>
Change the current user USER <user-name>
Introduction to Docker

Time for practice!

Introduction to Docker

Preparing Video For Download...