Ошибка cannot connect to the docker daemon

I also received the error message below, after installing the docker and running: docker run hello-world
#Cannot connect to the Docker daemon at unix: /var/run/docker.sock. Is the docker daemon running?

Here’s a solution, what worked for me.
Environment

  • Windows 10 (Don’t forget to enable on windows: Settings> Update and Security> Developer mode)
  • Ubuntu 18.04 LTS
  • Docker Desktop version 2.3.0.2 (45183)
    • Enable in Docker Desktop: Expose daemon on tcp: // localhost: 2375 without TLS
    • Docker Desktop must also be running (connected to Docker Hub … just log in)

After installing ubuntu, update the repository

sudo apt-get update

To use a repository over HTTPS

sudo apt-get install apt-transport-https ca-certificates curl gnupg-agent software-properties-common

Add the official Docker GPG key:

curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -

Make sure you now have the key with the fingerprint

sudo apt-key fingerprint 0EBFCD88

Update the repository

sudo apt-get update

Update the docker repository

sudo add-apt-repository "deb [arch = amd64] https://download.docker.com/linux/ubuntu $ (lsb_release -cs) stable "

Update the repository again

sudo apt-get update

Command to install the docker in version: 5: 18.09.9 ~ 3-0 ~ ubuntu-bionic

sudo apt-get install docker-ce = 5: 18.09.9 ~ 3-0 ~ ubuntu-bionic docker-ce-cli = 5: 18.09.9 ~ 3-0 ~ ubuntu-bionic containerd.io

Command to set the DOCKER_HOST

export DOCKER_HOST="tcp://0.0.0.0:2375"

Note: put the command above in your profile to start with the ubunto
ex: echo «export DOCKER_HOST=»tcp://0.0.0.0:2375″» >> ~/.bashrc

Add user to the docker group

sudo usermod -aG docker $USER

Restart ubuntu

(Close and open the ubuntu window again)
or run:

source ~/.bashrc

Testing the installation (DO NOT use more sudo before docker commands (it will give an error), the user «root» has already been included in the docker group)

docker run hello-world

The message below should be displayed

Hello from Docker!
This message shows that your installation appears to be working correctly.

Note: if it fails, run the command again:

export DOCKER_HOST="tcp://0.0.0.0:2375"

Reference: https://docs.docker.com/engine/install/ubuntu/
Session: INSTALL DOCKER ENGINE

#For other versions of the docker that can be installed with ubuntu, see the repository using the command below:
apt-cache madison docker-ce

Then install the desired version of the docker:

sudo apt-get install docker-ce = <VERSION_STRING> docker-ce-cli = <VERSION_STRING> containerd.io

Introduction

Users new to Docker may find it difficult to use as they often encounter an issue right after installing it. The “cannot connect to the Docker daemon” error in Docker usually happens when running the docker-compose build command.

In this tutorial, we will go over possible causes of the “cannot connect to the Docker daemon” error and the ways you can solve it.

How to resolve the "cannot connect to Docker daemon" error

Prerequisites

  • Access to the command line or terminal
  • A working Docker installation

There are several ways to fix the “cannot connect to the Docker daemon” error. If one solution doesn’t work for you, move on to the next method until you resolve the issue.

Note: Not executing the command as the sudo user might invoke the «cannot connect to Docker daemon» error. Try adding the sudo command prefix to ensure this isn’t the cause of the issue.

Method 1: Check the Docker Engine

If the Docker engine is not running, docker-compose can’t access it, which produces the error.

1. First, check if the Docker engine is running:

sudo service docker status
Checking the Docker service status to resolve the "cannot connect to the docker daemon" error.

2. If the Docker engine isn’t working, start it with the following command:

sudo service docker start

3. After you start the Docker engine, try running the docker-compose build command again. If the error persists, try one of the following solutions.

Method 2: Assign Ownership to the Docker Unix Socket

The “cannot connect to the Docker daemon” error also happens if the Unix socket file for Docker doesn’t have the correct ownership assigned.

1. Check ownership for the Docker Unix socket:

sudo ls -la /var/run/docker.sock
Checking the ownership for the Docker Unix socket to resolve "cannot connect to the docker daemon" error.

2. If necessary, grant the user ownership with:

sudo chown [username]:docker /var/run/docker.sock

Method 3: Check the Ownership of Used Files

Ownership issues can also extend to files used by your Docker build. If Docker needs to use a file it can’t access, this results in a “cannot connect to the Docker daemon” error.

1. Run the docker build command for each individual container. This gives you a detailed output that points out any potential errors.

Using the docker build command to get a more detailed output to resolve "cannot connect to the docker daemon" error.

2. Check the output for each container, keeping an eye out for an “cannot connect to the Docker daemon” error report. If there is a problem with the file ownership, the error report will list out the files that the docker build command cannot access.

3. There are several ways to resolve the issue of ownership of used files:

  • You can simply remove the files in question by deleting them, but this affects any other builds using the same files.
  • Another method is to add the .dockerignore file to your current build, thus excluding the files your build can’t access.
  •  Finally, you can change the file ownership with:
sudo chown [username]:docker /your/file/location

Method 4: Add Your User to the Docker Group

Not having the proper user privileges also triggers the error. You need to be able to access the Docker engine without using the sudo command.

1. To solve this issue, add the current user to the Docker group via usermod command:

sudo usermod -aG docker [username]

2. Log out and back in to confirm the changes.

Note: If you just installed Docker and still don’t have a docker group to which you can add the user, create the group before running the command listed above. To do so, run: sudo groupadd docker.

Method 5: Add Environment Tables on OS X

If you are running Docker on OS X, you may have to add environment variables:

1. First, start the Docker virtual machine:

docker-machine start

2. Get the environment variables for Docker with:

docker-machine env

3. Finally, set the environment variables:

eval "$(docker-machine env default)"

Conclusion

After following this tutorial, you should be aware of the potential causes of the “cannot connect to the Docker daemon” error and ways to fix each one.

Learn Docker container management best practices for an efficient and safe Docker environment.

Docker is a powerful platform for building, shipping, and running distributed applications. However, when working with Docker, you may come across an error message that says “cannot connect to the Docker daemon”. This error typically occurs when the Docker daemon is not running or the user running the command does not have permission to connect to the Docker daemon. In this article, we will cover the ways to resolve this error with proper instructions and examples.

First, let’s understand why this error occurs. The Docker daemon is a background process that manages Docker containers and images. When you run a command such as a docker run, it sends a request to the Docker daemon to perform the requested action. If the Docker daemon is not running or the user running the command does not have permission to connect to the Docker daemon, the command will fail and display the “cannot connect to the Docker daemon” error.

Solutions to Resolve Error

Solution 1: Ensure that the Docker daemon is running

The first step in resolving the error is to check if the Docker daemon is running. You can do this by running the below command. If the Docker daemon is running, you will see an output similar to the following output screenshot:

systemctl status docker

Ensuring that docker is running

If the Docker daemon is not running, you can start it by running the above command.

Solution 2: Add the current user to the docker group

On Linux systems, the user running the command must be a member of the docker group to connect to the Docker daemon. You can check if the user is a member of the docker group by running the command id. If the output shows that the user is not a member of the docker group, you can add the user to the group by running the below command:

sudo usermod -aG docker $USER

Adding current user in docker group

Solution 3: Check the Ownership of used Files

There are several ways to check the ownership of the files used by the Docker daemon on a Linux system. Here are a few methods:

1. Use the ls -l command to view the file ownership and permissions of the Docker socket:

ls -l /var/run/docker.sock

Checking the ownership of used files

2. Use the stat command to view the file ownership and permissions of the Docker socket:

stat /var/run/docker.sock

Viewing the ownership and permissions

Solution 4: Restart the Docker daemon

There are several ways to restart the Docker daemon on a Linux system, here are a few common methods:

1. Use the systemctl command to restart the Docker service:

sudo systemctl restart docker

2. Use the service command to restart the Docker service:

sudo service docker restart

Restarting Docker daemon

Solution 5: Check the status of the Docker daemon:

You can check the status of the Docker daemon by running the command “docker info” or “docker version” in the command line. This will display information about the Docker daemon, including its version number, the number of containers and images running, and the amount of memory and storage it is using. If the daemon is not running, the command will return an error message.

sudo docker info

Checking status of Docker daemon

Solution 6: Assign Ownership to the Docker Unix Socket

To assign ownership to the Docker Unix socket, you can use the chown command. The command should be executed as the root user or a user with superuser privileges.

Here is the basic syntax for the command:

sudo chown <user>:<group> /var/run/docker.sock

Assign Ownership to the Docker Unix Socket

Replace <user> and <group> with the appropriate user and group to that you want to assign ownership.

Running Docker after resolving the error

Below is an example of how the error message looks like if docker is not running:

$ docker run hello-world
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?

And here is an example of how you can resolve the error by starting the Docker daemon:

$ sudo systemctl start docker
$ docker run hello-world
Hello from Docker!
This message shows that your installation appears to be working correctly.

Successful Docker Execution

Conclusion

In conclusion, the “cannot connect to the Docker daemon” error can be caused by several factors such as the Docker daemon not running or the user running the command not having permission to connect to the Docker daemon. By following the steps outlined in this article, you should be able to resolve the error and continue working with Docker.

It’s always a good practice to check the Docker daemon logs for any error messages, it might help you troubleshoot the problem. Additionally, you can refer to the official Docker documentation for more information on troubleshooting this error. Furthermore, you can also join the Docker community, where you can find answers to common problems and ask for help from other experienced users.

In short, to resolve the error “cannot connect to the Docker daemon”, check if the Docker daemon is running, ensure the user has permission to connect to the Docker daemon, restart the machine, run the command with sudo, and check the Docker daemon logs if all above steps fail.

Last Updated :
17 Apr, 2023

Like Article

Save Article

Docker – одна из ведущих платформ для создания и запуска программных контейнеров.

Он поставляется со всем необходимым для использования контейнеров как на одном узле, так и на нескольких распределенных узлах в режиме Swarm.

Docker имеет архитектуру, основанную на демонах.

Программное обеспечение, отвечающее за создание и запуск контейнеров, не зависит от процесса CLI, который принимает ваши команды.

Это означает, что вы увидите ошибки в CLI, если попытаетесь выполнить команды без активного соединения с демоном.

В этой статье мы поделимся некоторыми методами устранения этих разочаровывающих сообщений.

Симптомы проблемы

Docker CLI зависит от наличия соединения с демоном.

Он взаимодействует с демоном с помощью вызовов API.

Когда настроенный демон недоступен, команды docker, такие как docker ps, docker run и docker build, выдают сообщение об ошибке, подобное этому:

$ docker run hello-world:latest
Cannot connect to the Docker daemon at unix:///var/run/docker.sock
Is the docker daemon running?

Система показывает, что CLI пытался установить связь с демоном Docker, используя Unix-сокет /var/run/docker.sock.

Сокет не открыт, поэтому соединение не удалось.

1. Проверьте, запущена ли служба демона Docker

Демон Docker обычно управляется службой systemd, которая автоматически запускает Docker после перезагрузки хоста.

Устранение неполадок можно начать с проверки того, запущена ли эта служба:

$ sudo systemctl status docker
docker.service - Docker Application Container Engine
     Loaded: loaded (/lib/systemd/system/docker.service; enabled; vendor preset: enabled)
     Active: inactive (dead)

Служба должна сообщить Active: active (running), если демон запущен.

В примере выше показано inactive (dead), что означает, что демон остановлен.

Запустите Docker с помощью следующей команды:

$ sudo systemctl start docker

Теперь вы должны иметь возможность успешно выполнять команды docker CLI.

Вы можете обнаружить, что после перезагрузки машины Docker остается в остановленном состоянии.

Вы можете решить эту проблему, включив службу, что позволит systemd запускать ее автоматически:

$ sudo systemctl enable docker
$ sudo systemctl daemon-reload

Команда daemon-reload предписывает systemd перезагрузить свою конфигурацию, чтобы применить изменения.

2. Запуск демона вручную

Иногда вы можете использовать систему, в которой не установлена служба Docker.

Вы можете вручную запустить демон Docker с помощью команды dockerd.

Обычно ее нужно запускать от имени root.

$ sudo dockerd
INFO[2022-06-29T15:12:49.303428726+01:00] Starting up

Docker будет оставаться доступным до тех пор, пока выполняется команда.

Используйте Ctrl+C для остановки демона.

3. Проверка правильности выбора демона в CLI

Проблемы могут возникнуть, когда CLI пытается подключиться к удаленному экземпляру демона Docker.

Обычно это происходит, когда в сообщении об ошибке указывается TCP-адрес:

$ docker run hello-world:latest
Cannot connect to the Docker daemon at tcp:///0.0.0.0:2375

В этом примере docker CLI пытается связаться с демоном Docker по адресу 0.0.0.0:2375, используя TCP, а не локальный сокет Unix Docker.

Это не удастся, если поддержка TCP демоном Docker отключена или указанный хост недоступен в сети.

Обычно эту проблему можно решить, переключившись на правильный контекст Docker CLI для соединения с демоном, которое вы хотите использовать:

$ docker context use default

Вы можете перечислить все доступные контексты и конечные точки демонов, к которым они подключаются, с помощью команды context ls:

$ docker context ls
NAME        DESCRIPTION                               DOCKER ENDPOINT             
default *   Current DOCKER_HOST based configuration   unix:///var/run/docker.sock

Выбранный в данный момент контекст выделяется звездочкой.

Неожиданные значения в колонке DOCKER ENDPOINT обычно вызваны тем, что установлена переменная окружения DOCKER_HOST.

В этом случае вы увидите предупреждение:

$ export DOCKER_HOST=1.2.3.4
$ docker context ls
NAME        DESCRIPTION                               DOCKER ENDPOINT
default *   Current DOCKER_HOST based configuration   tcp://1.2.3.4:2375
Warning: DOCKER_HOST environment variable overrides the active context. To use a context, either set the global --context flag, or unset DOCKER_HOST environment variable.

Наличие переменной окружения DOCKER_HOST в вашей оболочке переопределяет конечную точку, определенную выбранным контекстом.

В этом примере команды docker всегда будут нацелены на экземпляр демона по адресу tcp://1.2.3.4:2375.

Эту проблему можно решить, очистив переменную DOCKER_HOST:

$ export DOCKER_HOST=

Теперь Docker будет использовать конечную точку, настроенную вашим активным контекстом.

Это будет локальный Unix-сокет по умолчанию в /var/run/docker.sock, если вы вручную не настроили пользовательский контекст.

$ docker context ls
NAME        DESCRIPTION                               DOCKER ENDPOINT             
default *   Current DOCKER_HOST based configuration   unix:///var/run/docker.sock

4. Проблемы с правами

Неправильные разрешения пользователя на сокет Docker являются еще одной распространенной причиной проблем с подключением демона.

Этот вид проблемы обычно показывает немного другое сообщение об ошибке:

$ docker run hello-world:latest
Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock

Это происходит, когда вашей учетной записи пользователя Unix не хватает прав на взаимодействие с сокетом, который предоставляет API Docker.

Добавление себя в группу docker – лучший способ решения этой проблемы:

Docker is becoming more and more popular with its ability to create, deploy, and run applications using containers easily. Containers allow developers to package an application with all its libraries and dependencies before deploying it as one full package. Installing Docker on Linux is relatively easy. All you need to do is run a couple of commands in the Terminal, and you are good to go.

Docker connection error

If the Docker daemon is not running, you can start it by running the above command.

Solution 2: Add the current user to the docker group

On Linux systems, the user running the command must be a member of the docker group to connect to the Docker daemon. You can check if the user is a member of the docker group by running the command id. If the output shows that the user is not a member of the docker group, you can add the user to the group by running the below command:

sudo usermod -aG docker $USER

Adding current user in docker group

Solution 3: Check the Ownership of used Files

There are several ways to check the ownership of the files used by the Docker daemon on a Linux system. Here are a few methods:

1. Use the ls -l command to view the file ownership and permissions of the Docker socket:

ls -l /var/run/docker.sock

Checking the ownership of used files

2. Use the stat command to view the file ownership and permissions of the Docker socket:

stat /var/run/docker.sock

Viewing the ownership and permissions

Solution 4: Restart the Docker daemon

There are several ways to restart the Docker daemon on a Linux system, here are a few common methods:

1. Use the systemctl command to restart the Docker service:

sudo systemctl restart docker

2. Use the service command to restart the Docker service:

sudo service docker restart

Restarting Docker daemon

Solution 5: Check the status of the Docker daemon:

You can check the status of the Docker daemon by running the command “docker info” or “docker version” in the command line. This will display information about the Docker daemon, including its version number, the number of containers and images running, and the amount of memory and storage it is using. If the daemon is not running, the command will return an error message.

sudo docker info

Checking status of Docker daemon

Solution 6: Assign Ownership to the Docker Unix Socket

To assign ownership to the Docker Unix socket, you can use the chown command. The command should be executed as the root user or a user with superuser privileges.

Here is the basic syntax for the command:

sudo chown <user>:<group> /var/run/docker.sock

Assign Ownership to the Docker Unix Socket

Replace <user> and <group> with the appropriate user and group to that you want to assign ownership.

Running Docker after resolving the error

Below is an example of how the error message looks like if docker is not running:

$ docker run hello-world
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?

And here is an example of how you can resolve the error by starting the Docker daemon:

$ sudo systemctl start docker
$ docker run hello-world
Hello from Docker!
This message shows that your installation appears to be working correctly.

Successful Docker Execution

Conclusion

In conclusion, the “cannot connect to the Docker daemon” error can be caused by several factors such as the Docker daemon not running or the user running the command not having permission to connect to the Docker daemon. By following the steps outlined in this article, you should be able to resolve the error and continue working with Docker.

It’s always a good practice to check the Docker daemon logs for any error messages, it might help you troubleshoot the problem. Additionally, you can refer to the official Docker documentation for more information on troubleshooting this error. Furthermore, you can also join the Docker community, where you can find answers to common problems and ask for help from other experienced users.

In short, to resolve the error “cannot connect to the Docker daemon”, check if the Docker daemon is running, ensure the user has permission to connect to the Docker daemon, restart the machine, run the command with sudo, and check the Docker daemon logs if all above steps fail.

Last Updated :
17 Apr, 2023

Like Article

Save Article

Docker – одна из ведущих платформ для создания и запуска программных контейнеров.

Он поставляется со всем необходимым для использования контейнеров как на одном узле, так и на нескольких распределенных узлах в режиме Swarm.

Docker имеет архитектуру, основанную на демонах.

Программное обеспечение, отвечающее за создание и запуск контейнеров, не зависит от процесса CLI, который принимает ваши команды.

Это означает, что вы увидите ошибки в CLI, если попытаетесь выполнить команды без активного соединения с демоном.

В этой статье мы поделимся некоторыми методами устранения этих разочаровывающих сообщений.

Симптомы проблемы

Docker CLI зависит от наличия соединения с демоном.

Он взаимодействует с демоном с помощью вызовов API.

Когда настроенный демон недоступен, команды docker, такие как docker ps, docker run и docker build, выдают сообщение об ошибке, подобное этому:

$ docker run hello-world:latest
Cannot connect to the Docker daemon at unix:///var/run/docker.sock
Is the docker daemon running?

Система показывает, что CLI пытался установить связь с демоном Docker, используя Unix-сокет /var/run/docker.sock.

Сокет не открыт, поэтому соединение не удалось.

1. Проверьте, запущена ли служба демона Docker

Демон Docker обычно управляется службой systemd, которая автоматически запускает Docker после перезагрузки хоста.

Устранение неполадок можно начать с проверки того, запущена ли эта служба:

$ sudo systemctl status docker
docker.service - Docker Application Container Engine
     Loaded: loaded (/lib/systemd/system/docker.service; enabled; vendor preset: enabled)
     Active: inactive (dead)

Служба должна сообщить Active: active (running), если демон запущен.

В примере выше показано inactive (dead), что означает, что демон остановлен.

Запустите Docker с помощью следующей команды:

$ sudo systemctl start docker

Теперь вы должны иметь возможность успешно выполнять команды docker CLI.

Вы можете обнаружить, что после перезагрузки машины Docker остается в остановленном состоянии.

Вы можете решить эту проблему, включив службу, что позволит systemd запускать ее автоматически:

$ sudo systemctl enable docker
$ sudo systemctl daemon-reload

Команда daemon-reload предписывает systemd перезагрузить свою конфигурацию, чтобы применить изменения.

2. Запуск демона вручную

Иногда вы можете использовать систему, в которой не установлена служба Docker.

Вы можете вручную запустить демон Docker с помощью команды dockerd.

Обычно ее нужно запускать от имени root.

$ sudo dockerd
INFO[2022-06-29T15:12:49.303428726+01:00] Starting up

Docker будет оставаться доступным до тех пор, пока выполняется команда.

Используйте Ctrl+C для остановки демона.

3. Проверка правильности выбора демона в CLI

Проблемы могут возникнуть, когда CLI пытается подключиться к удаленному экземпляру демона Docker.

Обычно это происходит, когда в сообщении об ошибке указывается TCP-адрес:

$ docker run hello-world:latest
Cannot connect to the Docker daemon at tcp:///0.0.0.0:2375

В этом примере docker CLI пытается связаться с демоном Docker по адресу 0.0.0.0:2375, используя TCP, а не локальный сокет Unix Docker.

Это не удастся, если поддержка TCP демоном Docker отключена или указанный хост недоступен в сети.

Обычно эту проблему можно решить, переключившись на правильный контекст Docker CLI для соединения с демоном, которое вы хотите использовать:

$ docker context use default

Вы можете перечислить все доступные контексты и конечные точки демонов, к которым они подключаются, с помощью команды context ls:

$ docker context ls
NAME        DESCRIPTION                               DOCKER ENDPOINT             
default *   Current DOCKER_HOST based configuration   unix:///var/run/docker.sock

Выбранный в данный момент контекст выделяется звездочкой.

Неожиданные значения в колонке DOCKER ENDPOINT обычно вызваны тем, что установлена переменная окружения DOCKER_HOST.

В этом случае вы увидите предупреждение:

$ export DOCKER_HOST=1.2.3.4
$ docker context ls
NAME        DESCRIPTION                               DOCKER ENDPOINT
default *   Current DOCKER_HOST based configuration   tcp://1.2.3.4:2375
Warning: DOCKER_HOST environment variable overrides the active context. To use a context, either set the global --context flag, or unset DOCKER_HOST environment variable.

Наличие переменной окружения DOCKER_HOST в вашей оболочке переопределяет конечную точку, определенную выбранным контекстом.

В этом примере команды docker всегда будут нацелены на экземпляр демона по адресу tcp://1.2.3.4:2375.

Эту проблему можно решить, очистив переменную DOCKER_HOST:

$ export DOCKER_HOST=

Теперь Docker будет использовать конечную точку, настроенную вашим активным контекстом.

Это будет локальный Unix-сокет по умолчанию в /var/run/docker.sock, если вы вручную не настроили пользовательский контекст.

$ docker context ls
NAME        DESCRIPTION                               DOCKER ENDPOINT             
default *   Current DOCKER_HOST based configuration   unix:///var/run/docker.sock

4. Проблемы с правами

Неправильные разрешения пользователя на сокет Docker являются еще одной распространенной причиной проблем с подключением демона.

Этот вид проблемы обычно показывает немного другое сообщение об ошибке:

$ docker run hello-world:latest
Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock

Это происходит, когда вашей учетной записи пользователя Unix не хватает прав на взаимодействие с сокетом, который предоставляет API Docker.

Добавление себя в группу docker – лучший способ решения этой проблемы:

Docker is becoming more and more popular with its ability to create, deploy, and run applications using containers easily. Containers allow developers to package an application with all its libraries and dependencies before deploying it as one full package. Installing Docker on Linux is relatively easy. All you need to do is run a couple of commands in the Terminal, and you are good to go.

Docker connection error

Docker connection error

However, this might not be the same for all users, even after a successful installation. One of the most common arising error is: Cannot connect to the Docker daemon at (unix:///var/run/docker.sock. Is the docker daemon running?) This error can arise when running various docker commands like docker run, docker info, docker pull, docker stop, etc.

What causes the Error: Cannot Connect to the Docker Daemon?

After receiving numerous developers’ complaints, we decided to dive in and come up with effective solutions. Some of the reasons that trigger this error include:

  • The Docker daemon is not running.
  • Docker doesn’t shutdown cleanly.
  • Lack of root privileges to start the docker service.

Now that you have a basic understanding of the problem cause, let’s look at the various solutions available for you.

Solution 1: Start the Docker service with systemctl

If you have just completed a Docker’s fresh installation on Ubuntu or rebooted your PC, there is a high probability chance the Docker service is not running. Docker daemon (dockerd) is the system service for docker. This service handles various Docker objects like images, containers, networks, and volumes and listens to the Docker API requests.

The Systemctl command comes to replace the old SysV init system, and it manages systemd services running on Linux systems. If you don’t have systemctl in your system, don’t worry; use the service command as described below.

Note: This method only works for users who installed Docker with the APT package manager. If you installed Docker via SNAP, refer to Solution 5 below.

  1. Open the Terminal and execute the first command – unmask docker.
sudo systemctl unmask docker

If we try to start docker service when docker is masked, we might face the error ‘Failed to start docker.service: Unit is masked.’ Mask can be considered a more robust version of disabling. When a unit file is masked, the unit is linked to ‘dev/null.’ You can list the state of all unit files with the command – ‘$ systemctl list-unit-files

2. Once the docker unit is unmasked, we can start the docker daemon with the systemctl command. The docker daemon manages docker objects like Images, Containers, and Docker API requests. Execute the command below on the command-line.

systemctl start docker

Start Docker Service

Start Docker Service

3. To verify whether the docker service is active and running. We will use the systemctl status command, which shows the current status of the particular service. Execute the command below on your Terminal.

systemctl status docker

Docker service status

Docker service status

From the above image, we can see that the docker is active and running.

Solution 2: Clean a ‘Failed Docker Pull’ and Start Docker service

There are cases where you might unexpectedly close Docker while pulling a container. Such situations will mask the docker.service and docker .socket files. Docker.socket is a file located at ‘/var/run/docker.sock’ and is used to communicate with the Docker daemon. We will need to unmask the two-unit files – docker .service and docker.daemon before proceeding to start docker.

  1. Launch the Terminal and execute the commands below:
systemctl unmask docker.service
systemctl unmask docker.socket
systemctl start docker.service

Start Docker Service

Start Docker Service

If you are still experiencing the error even after executing the commands below, we will need to delete the files in the Containerd directory before starting Docker again. Containerd was a feature introduced in Docker 1.11 and is used to manage Docker images life-cycle.

2. Open Terminal and execute the commands below. Ensure you know the root password since we will need elevated privileges to execute the commands.

sudo su
service docker stop
cd /var/run/docker/libcontainerd
rm -rf containerd/*
rm -f docker-containerd.pid
service docker start

Restart docker service

Restart docker service

Solution 3: Start Dockerd (Docker Daemon) Service

Dockerd is the Docker daemon which listens to Docker APIs and manages the various Docker objects. Dockerd can be used as an alternative to the command ‘$ systemctl start docker‘ which is also used to start the Docker daemon.

  1. Open Terminal and start dockerd by executing the command below:
sudo dockerd

Start dockerd

Start dockerd

Solution 4: Start Docker with the Service command

If you are using the SysV init system, then the systemctl command will not work for you. We will need to use the service command to start docker daemon.

  1. launch the Terminal and execute the commands below:
sudo service --status-all
sudo service docker start

Start Docker service

Start Docker service

Solution 5: Start the Docker Service with Snap

If you installed Docker with the Snap package manager, you would need to use the snap command to manage the docker daemon.

Generally, Snap manage their services automatically. However, in situations such as this error, it will require manual intervention. Some of the arguments you can use with the snap command include stop, start, and restart. In our case, we will use the start parameter.

  1. Open Terminal and execute the command below to start Docker.
sudo snap start docker

Start Docker

Start Docker

2. Execute the command below to verify whether the Docker service was started.

sudo snap services

That will list all running snap services.

Snap Services

Snap Services

If the above commands don’t work for you, try connecting the docker:home plug since it’s not auto-connected by default. Once done, start the Docker service.

3. Launch the Terminal and run the commands below:

sudo snap connect docker:home :home
sudo snap start docker

Start Docker

Start Docker

Solution 6: Start Docker for users without Root Privileges

The error might also arise due to lack of elevated privileges and the user doesn’t have access to ‘unix:///var/run/docker.sock.’ Luckily there is a workaround. We will export the Docker Host variable to the localhost via port 2375.

  1. Open the Terminal and run the command below:
export DOCKER_HOST=tcp://localhost:2375

Export DockerHost

Export Docker Host

Solution 7: Reinstall Docker

If the above solutions don’t solve the error, there is a high probability chance that you might have installation errors. To correctly install Docker in your Linux system, follow the steps from the Docker official website.

Понравилась статья? Поделить с друзьями:
  • Ошибка c3 1414 samsung k2200
  • Ошибка c29 suzuki gsx r
  • Ошибка c2804 бинарный operator имеет слишком много параметров
  • Ошибка c28 suzuki gsx r 1000
  • Ошибка c2731 winmain функция не может быть перегружена