Practical Use Cases and Examples
Assigning fine-grained permissions to non-root users in Docker can be beneficial in a variety of scenarios. Here are some practical use cases and examples:
Scenario 1: Running a Web Server
Suppose you have a web application running in a Docker container, and you want the non-root user to have the necessary permissions to start and manage the web server process.
## Dockerfile
FROM ubuntu:22.04
RUN useradd -ms /bin/bash myuser
RUN apt-get update && apt-get install -y nginx
RUN chown -R myuser:myuser /var/www/html
USER myuser
CMD ["nginx", "-g", "daemon off;"]
In this example, the myuser
non-root user is granted ownership of the /var/www/html
directory, which is the default location for the Nginx web server. This allows the non-root user to start and manage the Nginx process within the container.
Scenario 2: Accessing Sensitive Files
If your container needs to access sensitive files or directories, you can grant the non-root user the necessary permissions to read or write to those locations.
## Run container with specific volume permissions
docker run -it --user myuser -v /path/to/sensitive/files:/sensitive:rw,uid=1000,gid=1000 ubuntu:22.04 bash
In this example, the non-root user with a user ID of 1000
and a group ID of 1000
is granted read and write access to the /path/to/sensitive/files
directory within the container.
Scenario 3: Interacting with the Docker Daemon
If your non-root user needs to interact with the Docker daemon, you can add them to the "docker" group within the container.
## Dockerfile
FROM ubuntu:22.04
RUN useradd -ms /bin/bash myuser
RUN usermod -aG docker myuser
USER myuser
This Dockerfile
creates a non-root user named myuser
and adds them to the "docker" group, allowing them to perform Docker-related tasks, such as building and managing containers.
Scenario 4: Executing Privileged Commands
In some cases, your non-root user may need to execute privileged commands that require specific capabilities. You can use the --cap-add
flag to grant the necessary capabilities to the non-root user.
## Run container with specific capability
docker run -it --user myuser --cap-add=SYS_ADMIN ubuntu:22.04 bash
In this example, the non-root user is granted the "CAP_SYS_ADMIN" capability, which allows them to perform system administration tasks that require elevated privileges.
By understanding these practical use cases and examples, you can effectively grant fine-grained permissions to non-root users in Docker, ensuring that they have the necessary access to perform their tasks while maintaining a secure and isolated environment.