Running Commands as a Different User in a Docker Container
Running the commands as a different user is one of the best practices which is followed by everyone in the production server. The reasons are mentioned below.
- Security: Minimizes the risk of privilege escalation attacks by avoiding the use of the root user for everyday operations.
- Isolation: Enhances the isolation of processes, ensuring that different applications and services run with appropriate permissions.
Docker community prefers this practice, Use the following command to run the docker commands as an another user
docker exec --user ec2-user <Name of the container> yum update
Example
The following command will run the docker command in the docker container as an ec2-user and it will update the yum package.
docker exec --user myuser mycontainer apt update
Docker exec
In containerization, the `docker exec` command stands out as a powerful tool for interacting with running Docker containers. This article explores the capabilities and usage of `docker exec`, detailing how it facilitates seamless communication and control over containerized applications.
Before trying to run the Docker commands ensure that the Docker software is set up and the service is active. Check the status of the docker service with the command `systemctl status docker` If the status is active then the docker service is ready to use and perform the container operations and management. To start the docker service try to run the following command
systemctl start docker
( or ) To automatically start the docker service, Once the base OS is started try to use this command:
systemctl enable docker --now
For Installation refer to the Article – How to Install Docker on Linux Distributions
Table of Content
- What is Docker Exec?
- Options of Docker Exec
- Examples of Docker Exec Command
- How to start and run a Docker Container?
- Finding the Name of a Docker Container
- Running an Interactive Shell in a Docker Container
- Running a Command Non-interactively in a Docker Container
- Running Commands in an Alternate Directory in a Docker Container
- Running Commands as a Different User in a Docker Container
- Passing Environment Variables into a Docker Container
- Run a Command from Outside the Container
- Access the Running Container’s Shell
- Difference between Docker run and Docker exec