Non-Root User¶
Docker containers run as root by default, unless the developer specifies a non-root user or non-default user when run a container. It is a form of privilege escalation, containers run as root even when the container is initiated by a non-root user.
However it is needed to initialize containers as root, since only root has sufficient capabilities to create namespaces in order to containerize processes and isolate resources completely from the host. Also container need operate as root to install software using package managers like yum or apt. After packages are installed, developer could add a USER command in later step in the Dockerfile, so that the image is configured to run under a non-root user ID.
The following example shows how you can specify that the default user identity for running containers based on this image isn't root.
- Create a Dockerfile:
FROM alpine:latest
RUN adduser -S example_user
# privileged installation operations...
USER example_user
ENTRYPOINT [ "/bin/sh" ]
You can now build and run the container with these commands in the terminal
# Tag Container Name as myapp
docker build -t myapp
docker run -it myapp
/ $ whoami
>>> example_user
- In addition to the Dockerfile, you can also create another docker-compose.yml under the same directory
version: '2.4'
services:
myapp:
image: myapp:latest
And run these commands in the terminal
docker-compose run --entrypoint /bin/sh myapp
>>> Creating myapp_run ... done
/ $ whoami
>>> example_user