【親測有效】運行docker ps 出現Got permission denied問題的解決方案

問題描述

今天在運行 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.38/containers/json: dial unix /var/run/docker.sock: connect: permission denied

看提示信息好像是權限不夠,我們試試 root 權限:

我們發現用 root 權限就可以使用 docker 相關命令,那我們想在普通用戶下使用 docker 相關命令,這該怎麼辦呢?

我們去 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 權限才能訪問。

我們該怎麼解決這個問題呢?

解決方案一

使用 sudo 獲取管理員權限,運行 docker 命令(當然我不推薦這種方法,因爲我沒成功過,似乎還是出現瞭如上問題)

解決方案二

由於 docker 守護進程啓動的時候,會默認賦予名字爲 docker 的用戶組讀寫 Unix socket 的權限,因此只要創建 docker 用戶組,並將當前用戶加入到 docker 用戶組中,那麼當前用戶就有權限訪問 Unix socket 了,進而也就可以執行 docker 相關命令了。

我們可以使用如下命令解決問題:

sudo groupadd docker     #添加docker用戶組
sudo gpasswd -a $USER docker     #將登陸用戶加入到docker用戶組中
newgrp docker     #更新用戶組
docker ps    #測試docker命令是否可以使用sudo正常使用

然後我們可以完美地解決了這個問題,效果如下:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章