案发现场
[tanpeng@tanpeng001 ~]$ docker ps
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.40/containers/json: dial unix /var/run/docker.sock: connect: permission denied
原因分析
摘自docker mannual
上的一段话
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.
大概的意思就是:docker
进程使用Unix Socket
而不是TCP
端口。而默认情况下,Unix socket
属于root
用户,需要root
权限才能访问
解决方案
-
方法1
使用sudo
获取管理员权限,运行docker
命令 -
方法2
docker
守护进程启动的时候,会默认赋予名字为docker
的用户组读写Unix socket
的权限
因此只要创建docker
用户组,并将当前用户加入到docker
用户组中
那么当前用户就有权限访问Unix socket
了,进而也就可以执行docker
相关命令
# 添加docker用户组 (默认情况下在安装 docker 时,已经默认为我们创建好了这个用户组)
sudo groupadd docker
# 将登陆用户加入到docker用户组中
sudo gpasswd -a $USER docker
# 更新用户组
newgrp docker
# 测试docker命令是否可以直接使用
docker ps