解决WSL2的ubuntu20.04中安装docker出现无法连接的问题(Cannot connect to the Docker daemon)

时间:2025-03-24 16:10:46

wsl2的ubuntu20.04系统安装docker可以参考官网教程操作,我个人喜欢参考其中的离线安装方式:Install from a package。只需要按照官网一步步操作即可,跟普通的ubuntu20.04的安装是一样的步骤。

在安装完以后,发现一旦使用docker相关命令会出现下述问题:

Cannot connect to the Docker daemon at unix:///var/run/. Is the docker daemon running?

说明docker没有正常启动。这个原因主要是wsl2造成的。

解决方法很简单,首先输入下述命令:

sudo update-alternatives --config iptables

然后会输出下述信息:

  Selection    Path                       Priority   Status
------------------------------------------------------------
* 0            /usr/sbin/iptables-nft      20        auto mode
  1            /usr/sbin/iptables-legacy   10        manual mode
  2            /usr/sbin/iptables-nft      20        manual mode

Press <enter> to keep the current choice[*], or type selection number: 

此时输入1即可。

最后重新启动docker:

sudo service docker start

这样问题就解决了。