root Permission Acquisition Method in docker Container

  • 2021-10-25 00:11:57
  • OfStack

First of all, your container must be running

You can view the container's CONTAINER ID through sudo docker container ls or sudo docker ps

Execute the command last (where 7509371edd48 is the CONTAINER ID found above)


sudo docker exec -ti -u root 7509371edd48 bash

Supplement: Resolve the problem that non-root users do not have permission to run docker commands

Problem description:

"Got permission denied while trying to connect to the Docker daemon
socket at unix:///var/run/docker.sock: Get
http://%2Fvar%2Frun%2Fdocker.sock/v1.26/images/json: dial unix
/var/run/docker. sock: connect: permission denied "

Reason (from docker manual):

Manage Docker as a non-root user

The docker daemon binds to a Unix socket instead of a TCP port. By
default that Unix socket is owned by the user root and other users can
only access it using sudo. The docker daemon always runs as the root
user.

If you don't want to use sudo when you use the docker command, create
a Unix group called docker and add users to it. When the docker daemon
starts, it makes the ownership of the Unix socket read/writable by the
docker group.

The obvious answer is to use root users or create a user group called docker and add non-root users you need to use docker to that group. If you can't do it yet, keep looking.

Method 1:

Use sudo to get administrator privileges and run docker commands. This method has many limitations when executing docker commands through scripts

Method 2:

When the docker daemon is started, the user group named docker will be given the permission to read and write Unix socket by default. Therefore, as long as the docker user group is created and the current user is added to the docker user group, the current user will have the permission to access Unix socket, and then the relevant commands of docker can be executed


sudo groupadd docker   # Add docker User group 
sudo gpasswd -a $USER docker   # Add the logged-in user to the docker User group 
newgrp docker   # Update user groups 

Related articles: