Failed to attach docker event listener error connect eacces var run docker sock

Visual Studio Code Docker development troubleshooting tips and tricks

This article covers troubleshooting tips and tricks for the Visual Studio Code Docker extension. See the Overview and quickstart articles for Node.js, Python, or ASP.NET for details on setting up and working with Docker.

Running as a non-root user

For security reasons, we recommend selecting the default ports when executing the Add Dockerfiles to Workspace command, or otherwise opting for a port greater than 1023 whenever possible. This will allow VS Code to configure the Dockerfile with non-root access and prevent a malicious user from elevating permissions in the container. In some cases, there is no port selection, so the Docker extension configures non-root access by default. In all cases, you must ensure each resource (such as ports and files) modified or used by your application can be accessed by a non-root user in your container.

If you select a port less than 1024 when adding Dockerfiles to the workspace, the Docker extension cannot create a Dockerfile that runs the container as a non-root user. This is because ports in this range are called well-known or system ports and must execute with root privileges in order to bind a network socket to an IP address.

The Add Dockerfiles to Workspace command sets up non-root privileges if you choose a non-system port. If your current Dockerfile and tasks.json is not set up for non-root usage, try running the command Add Dockerfiles to Workspace, and select a port greater than 1023. This command overwrites your current Dockerfile and tasks.json. For some project types, such as Python: General, you might still need to modify your Dockerfile and tasks.json. Within the Dockerfile, you must expose a non-system port, create a working directory for your app code, and then add a non-root user with access to the app directory. Ensure that your exposed port is updated wherever it is referenced. In the example below, the Gunicorn port had to be updated to match the exposed port:

# 1024 or higher
EXPOSE 1024

# ... other directives such as installing requirements.txt file

# Creates /app in container if it does not already exist
# Ports code into /app
WORKDIR /app
ADD . /app

# Creates a non-root user and adds permission to access the /app folder
RUN adduser -u 5678 --disabled-password --gecos "" appuser && chown -R appuser /app
USER appuser

CMD ["gunicorn", "--bind", "0.0.0.0:1024", "pythonPath.to.wsgi"]

Next, ensure the docker run task in tasks.json also expects the same port. You can usually search for any occurrences of the old port number in tasks.json and replace it with the new port number. The following example shows the required changes in the case of a Python Django app:

{
  "type": "docker-run",
  "label": "docker-run: debug",
  "dependsOn": ["docker-build"],
  "python": {
    "args": [
      "runserver",
      "0.0.0.0:1024", //<- Change the number after the colon
      "--nothreading",
      "--noreload"
    ],
    "file": "manage.py"
  }
}

Error «connect EACCES /var/run/docker.sock» on Linux

Since VS Code runs as a non-root user, you will need to follow the steps in «Manage Docker as a non-root user» from Post-installation steps for Linux to access Docker from the extension.

Docker containers and images have disappeared from Docker view

This is most likely caused by a conflict with another extension called Docker Explorer (not authored by Microsoft). To resolve this issue, use a workaround described vscode-docker issue #1609.

The extension does not find Docker on a remote machine

Error message «Failed to connect. Is Docker installed and running?»

  1. Make sure Docker engine is installed on the remote machine and that Docker CLI works (run docker ps from the terminal and ensure it does not return any errors).
  2. If you are using a remote development environment (remote machine via SSH, WSL subsystem, GitHub Codespace), make sure the Docker extension is installed remotely as well as locally.

Invalid URL errors

If you have a need to connect to a remote Docker daemon, we recommend using Docker contexts instead of a docker.environment attribute in the settings. Check out this guide to learn how to create and use a context to communicate with a remote Docker daemon.

If you still need to override the Docker context you are currently using, make sure your DOCKER_HOST environment variable or docker.environment.DOCKER_HOST attribute includes a protocol in the URL (for example, ssh://myuser@mymachine or tcp://1.2.3.4).

Note: Keep in mind that your docker.environment.DOCKER_HOST attribute will override your Docker context and the DOCKER_HOST environment variable will override both the docker.environment.DOCKER_HOST attribute and your Docker context.

Tip: In Powershell you can change your Docker environment variable with $ENV:DOCKER_HOST = 'ssh://username@1.2.3.4'

Questions and feedback

We love your feedback! If you have any ideas or suggestions, report an issue.

12/21/2022

Troubleshooting

Contributing to Docker extension

Clone this wiki locally

I’m on Linux and get the error «connect EACCES /var/run/docker.sock»

Since VS Code runs as a non-root user, you will need to follow the steps in «Manage Docker as a non-root user» from Post-installation steps for Linux for the extension to be able to access docker.

Docker containers and images have disappeared from Docker view

This is most likely caused by a conflict with another extension called Docker Explorer (not authored by Microsoft). We are working with the author of that extension to have it fixed permanently. In the meantime, use a workaround described here.

The extension does not find Docker on a remote machine («Failed to connect. Is Docker installed and running?» error)

  1. Make sure Docker engine is installed on the remote machine and that Docker CLI works (do docker ps and ensure it does not return any errors).
  2. If using a remote development environment (remote machine via SSH, WSL subsystem, GitHub Codespace), ensure that Docker extension is installed remotely in addition to being installed locally.

Invalid URL Errors

If you have a need to connect to a remote Docker daemon, we highly recommend using Docker contexts instead of a docker.host attribute in the settings. Check out this guide to learn how to create and use a context to communicate with a remote Docker daemon.

If you still need to override the Docker context you are currently using, make sure your DOCKER_HOST environment variable or docker.host attribute includes a protocol in the URL (e.g ssh://myuser@mymachine or tcp://1.2.3.4).

Important Note: Keep in mind that your docker.host attribute will override your Docker context and the DOCKER_HOST environment variable will override both the docker.host attribute and your Docker context.

Tip: In Powershell you can change your docker environment variable with $ENV:DOCKER_HOST = ‘ssh://username@1.2.3.4’

Maintaining good quality documentation is a priority for the Docker extension team. If you find missing or inaccurate content, or if you’d like to extend the wiki with a topic or tutorial, please let us know by opening an issue.

Источник

Docker Tools Tips and Tricks

This article covers troubleshooting tips and tricks for the Visual Studio Code Docker extension. See the Overview and quickstart articles for Node.js, Python, or ASP.NET for details on setting up and working with Docker.

Running as a non-root user

For security reasons, we recommend selecting the default ports when executing the Add Dockerfiles to Workspace command, or otherwise opting for a port greater than 1023 whenever possible. This will allow VS Code to configure the Dockerfile with non-root access and prevent a malicious user from elevating permissions in the container. In some cases, there is no port selection, so the Docker extension configures non-root access by default. In all cases, you must ensure each resource (such as ports and files) modified or used by your application can be accessed by a non-root user in your container.

If you select a port less than 1024 when adding Dockerfiles to the workspace, the Docker extension cannot create a Dockerfile that runs the container as a non-root user. This is because ports in this range are called well-known or system ports and must execute with root privileges in order to bind a network socket to an IP address.

The Add Dockerfiles to Workspace command sets up non-root privileges if you choose a non-system port. If your current Dockerfile and tasks.json is not set up for non-root usage, try running the command Add Dockerfiles to Workspace, and select a port greater than 1023. This command overwrites your current Dockerfile and tasks.json . For some project types, such as Python: General, you might still need to modify your Dockerfile and tasks.json . Within the Dockerfile, you must expose a non-system port, create a working directory for your app code, and then add a non-root user with access to the app directory. Ensure that your exposed port is updated wherever it is referenced. In the example below, the Gunicorn port had to be updated to match the exposed port:

Next, ensure the docker run task in tasks.json also expects the same port. You can usually search for any occurrences of the old port number in tasks.json and replace it with the new port number. The following example shows the required changes in the case of a Python Django app:

Error «connect EACCES /var/run/docker.sock» on Linux

Since VS Code runs as a non-root user, you will need to follow the steps in «Manage Docker as a non-root user» from Post-installation steps for Linux to access Docker from the extension.

Docker containers and images have disappeared from Docker view

This is most likely caused by a conflict with another extension called Docker Explorer (not authored by Microsoft). To resolve this issue, use a workaround described vscode-docker issue #1609.

The extension does not find Docker on a remote machine

Error message «Failed to connect. Is Docker installed and running?»

  1. Make sure Docker engine is installed on the remote machine and that Docker CLI works (run docker ps from the terminal and ensure it does not return any errors).
  2. If you are using a remote development environment (remote machine via SSH, WSL subsystem, GitHub Codespace), make sure the Docker extension is installed remotely as well as locally.

Invalid URL errors

If you have a need to connect to a remote Docker daemon, we recommend using Docker contexts instead of a docker.environment attribute in the settings. Check out this guide to learn how to create and use a context to communicate with a remote Docker daemon.

If you still need to override the Docker context you are currently using, make sure your DOCKER_HOST environment variable or docker.environment.DOCKER_HOST attribute includes a protocol in the URL (for example, ssh://myuser@mymachine or tcp://1.2.3.4 ).

Note: Keep in mind that your docker.environment.DOCKER_HOST attribute will override your Docker context and the DOCKER_HOST environment variable will override both the docker.environment.DOCKER_HOST attribute and your Docker context.

Tip: In Powershell you can change your Docker environment variable with $ENV:DOCKER_HOST = ‘ssh://username@1.2.3.4’

Questions and feedback

We love your feedback! If you have any ideas or suggestions, report an issue.

Источник

Error Message: connect EACCES /var/run/docker.sock #1193

Comments

baiyutang commented Aug 8, 2019

Action: vscode-docker.images.prune
Error type: EACCES
Error Message: connect EACCES /var/run/docker.sock

Version: 0.7.0
OS: linux
Product: Visual Studio Code
Product Version: 1.36.1
Language: en

Is this reason that vscode is not in the group docker ?

The text was updated successfully, but these errors were encountered:

ejizba commented Aug 8, 2019

@baiyutang yeah make sure you follow the steps in “Manage Docker as a non-root user” from Post-installation steps for Linux for the extension to be able to access docker.

baiyutang commented Aug 9, 2019

@EricJizbaMSFT ok,I will read it,then have a try.Thant you.

andreheringer commented Aug 9, 2019

Having the same issue. I’ve followed the steps in the linux post installation but the problem persisted. Tried to reinstall the extension but no luck.

Also tired to reload the extension on a fresh installation of vscode 1.37 and the problem persisted.
Downloading and installing older version of the extension and no progress so far.

StephenWeatherford commented Aug 9, 2019

Can you successfully run ‘docker’ on a Linux terminal?

andreheringer commented Aug 10, 2019

I’ve updated my system and rebooted, and now it works. Does docker require a reboot so it can finish its installation?

Anyways, thank you guys for the attention.

baiyutang commented Aug 10, 2019

@baiyutang yeah make sure you follow the steps in “Manage Docker as a non-root user” from Post-installation steps for Linux for the extension to be able to access docker.

My problem is solved,Thank you.

luozhouyang commented Aug 28, 2019

Can you successfully run ‘docker’ on a Linux terminal?

I can run all the docker commands in terminal, but the problem persisted.

I have been using docker for months and every thing is ok. But I try the vs code remote container, the error message occurs: connect EACCES /var/run/docker.sock

baiyutang commented Aug 28, 2019

Can you successfully run ‘docker’ on a Linux terminal?

I can run all the docker commands in terminal, but the problem persisted.

I have been using docker for months and every thing is ok. But I try the vs code remote container, the error message occurs: connect EACCES /var/run/docker.sock

Did you have a try like this ?

Footer

© 2023 GitHub, Inc.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

Docker is not running #18

Comments

GeorgSteyn commented May 23, 2017

Hello,
Docker is installed cleanly on a Ubuntu 16.04.2. When I installed DockStation and run it, it says docker isn’t running. Though I can run docker run hello-world and get a response am I missing something.

The text was updated successfully, but these errors were encountered:

igor-lemon commented May 23, 2017

GeorgSteyn commented May 23, 2017

. WOW. I feel stupid, sorry bit new to Docker still. Played around a little with it few months ago. Helps when one reads the Docs.

Sorry and Thank you for your quick response.

igor-lemon commented May 23, 2017

You are welcome. 🙂

MarkRabey-Work commented May 25, 2017

I followed those step, and am able to run docker run hello-world without an issue. But, I’m still getting this error. Any other suggestions?

igor-lemon commented May 25, 2017

Hi @MarkRabey-Work
Can you give more information?

  1. OS
  2. Docker version and Docker Compose version

GeorgSteyn commented May 25, 2017

Did you remember to Logout and back in again and or Restart?

igor-lemon commented Jul 30, 2018

Hi @srlopez. Can you run docker & docker-compose commands via your logged user without sudo ?
Because I remember I could get only a version of Docker & Docker Compose without sudo . After running any command I had the same error. I resolved my issue with the solution that I posted above. If you can to run any command like docker-compose up but the app doesn’t still work, let’s me know about that, we’ll try to find a solution.

enriquebran commented Aug 10, 2018 •

sudo dockstation
if you don’t like execute with sudo, then:
sudo setfacl -m user:#usuario#:rw /var/run/docker.sock

#usuario# replace with your user. Example:
sudo setfacl -m user:enriquebran:rw /var/run/docker.sock

mzenios commented Dec 6, 2018 •

Hi,
If i do not run the dockstation as sudo, docker-compose cannot be found.
I have already access to run docker-compose without sudo, and also changed setfacl to docker.sock
Anything else i should know?
I assume this is related to this thread. If not let me know

c-thomasFR commented Jul 8, 2019

I have the same error on Windows

EduardoHidalgoGarcia commented Oct 10, 2019

matiaslopezd commented Feb 11, 2021

The issue was resolve with the command suggest @enriquebran!

Copy and paste:
sudo setfacl -m user:$:rw /var/run/docker.sock

Also, is not recommended to use docker as root, so you need to add the user to the docker group with this command sudo usermod -aG docker $ .

$ set your current username in the command, if you want to apply to another user, change with the name.

Источник

После выполнения следующего кода dockerode npm появляется ошибка «Подключите EACCES /var/run/docker.sock» в ubuntu 14.04.

Я выполняю следующий код, чтобы получить список всех контейнеров с помощью npm dockerode на машине Ubuntu 14.04. Контейнер Docker работает правильно.

Error connect EACCES /var/run/docker.sock

Это происходит потому, что у вас недостаточно прав для доступа к Docker. Есть два решения:

Выполните команду с помощью sudo. (не рекомендуется)

Добавьте текущего пользователя в группу docker с помощью этой команды:

Выйдите из системы и снова войдите в систему, как только вы запустите эту команду, и попробуйте снова запустить свой код. (рекомендуемые)

Помните, что возможность запускать любые команды Docker подразумевает неограниченный root-доступ на хосте; требовать для этого sudo — неплохая идея.

@DavidMaze Согласен. Но становится немного неудобно использовать sudo и многократно вводить пароль. Добавление пользователя в группу — более элегантный метод.

Источник

I want to work in a container in a remote server.
But it doesn’t work.

Environment:

Local: Windows 10

Local Terminal for ssh: WSL in Windows 10

Server: Ubuntu 18.04

I checked these two articles.

https://code.visualstudio.com/docs/remote/containers-advanced
https://code.visualstudio.com/docs/containers/ssh

I followed these steps.

  1. I installed [Remote Development] extension in VS Code.
  2. Remote-SSH: Connect to host. It works fine.
  3. I Installed [Docker] extension on the remoter server.
  4. Now I can see my containers and images in a docker tab.
  5. I clicked one container and clicked [Attach Visual Studio Code] and it says There are no running containers to attach to.

enter image description here

Ryan M's user avatar

Ryan M

17.3k30 gold badges60 silver badges71 bronze badges

asked Feb 27, 2020 at 1:28

Hakjin Lee's user avatar

3

I resolved this problem by switching to the remote server’s Docker context on my local machine:

docker context create some-context-label --docker "host=ssh://user@remote_server_ip"

docker context use some-context-label

docker ps
# A list of remote containers on my local machine! It works!

After that:

  1. Connect via Remote-SSH to the container server
  2. Right click relevant container -> the «Attach Visual Studio Code»

That works for me.

(Note: One would think that I should be able to just use my local VSCode (skip step 1) to connect to said remote container after switching my local context, but VSCode complains Failed to connect. Is docker running? in the Docker control pane.)

answered Sep 9, 2020 at 14:58

Daniel's user avatar

DanielDaniel

6225 silver badges8 bronze badges

1

I solve this issue using SSH tunneling following the steps found in https://florian-kriegel.de/blog/?p=234

Summarizing:

  1. Set (or add) «docker.host»: «tcp://localhost:23750» in settings.json
    in VSCode.
  2. Open a SSH tunnel like this in your local machine
    changing the user and hostname by the remote machine (where the docker daemon is running) credentials:
    ssh -NL localhost:23750:/var/run/docker.sock user@hostname.
  3. Now, in the docker tab, you will be able to see and attach to containers in the remote machine.

Note that the Remote SSH Extension is not used in this case.

answered May 11, 2020 at 11:36

cantonjf's user avatar

cantonjfcantonjf

711 silver badge3 bronze badges

8

This might sound very strange, but for me, I had to open a folder on the remote SSH server prior to using the Remote Containers extension in VS Code. If I didn’t do that, then it would constantly try to find the docker service running locally, even though the terminal tab was connected to the remote SSH server.

This seems very weird, because if you’re conncted via SSH in VS Code, then the extension should assume you’re trying to attach to the container on the remote server. Shouldn’t have to open a remote folder first.

By «opening a folder» on the remote server, the Remote Containers extension was then able to attach VS code to the container running on the remote SSH server. I didn’t have to do any of the steps in any of those articles. Just simply use Remote SSH to connect VS Code remotely via SSH, open a folder, and then use Remote Containers.

answered Apr 16, 2021 at 19:21

LewlSauce's user avatar

LewlSauceLewlSauce

4,9746 gold badges38 silver badges78 bronze badges

3

Solution using the «Remote SSH» and the «Remote Explorer» extension in Visual Studio Code.

Following the steps above (https://stackoverflow.com/a/61728799/11687201) I figured out how to make use of the SSH Remote and Remote Explorer Extension. The first step is the same as above:

  1. Open the settings.json file in VSCode, press F1 and select «>Preferences: Open Settings (JSON)» and add/edit the following line:
    "docker.host": "tcp://localhost:23750"
  2. Open the ssh config file, click on the «Remote Explorer» Extension, then click on the «SSH Targets» «Configure» button and open the ssh config file.
    Add the following line to your ssh connection:
    LocalForward localhost:23750 /var/run/docker.sock

Remark: Previously I used the solution described earlier in this thread (https://stackoverflow.com/a/61728799/11687201). I had to reboot both machines the local machine and remote machine before the solution described below worked out.

Afterwards I have to use multiple VSCode Windows:

  1. Local Machine: Start VSCode and use the «Remote Explorer» to connect to the remote machine using a new VSCode window

  2. VSCode window connected to remote (SSH)
    → startup the Docker container of your choice
    (I was not able to «Attach Visual Studio Code» from this VSCode window)

  3. VSCode window connected to local machine
    → Click on the «Docker» extension, the docker containers running on the remote get listed. Attach VSCode to a running container using one of the folling options:

    • Right-click on the desired container and chose «Attach Visual Studio Code»
    • Press F1 and chose»>Remote-Containers: Attach to Running Container…» and select the container of your choice afterwards

    A third VSCode window will open being attached to the Docker container.

Pros and cons of this solution

(+) Using the «Remote Explorer» extension I can directly connect and open a previously used project folder on my remote machine with one click

(-) 3 VSCode windows (local machine, remote ssh and remote container) are needed instead of 2 VSCode windows

Dharman's user avatar

Dharman

29.3k21 gold badges80 silver badges131 bronze badges

answered May 14, 2020 at 7:57

ai2ys's user avatar

ai2ysai2ys

1,0318 silver badges17 bronze badges

3

For some reason, this problem is fixed for me when I open a folder in the remote window before trying to attach to a container.

answered Jun 29, 2021 at 18:37

Mas's user avatar

I found Daniel’s answer really helpful but didn’t work for me. I put my two cents.

TL;DR

  1. Create a new docker context for the remote machine where remote container is running.
docker context create some-context-label --docker "host=ssh://user@remote_server_ip"

docker context use some-context-label
  1. Just open VSC, go to Docker (you should have installed the extension) tab and you’ll see listed all running containers from the remote context you recently created.
  2. Right click on your desired container and attach visual studio code

You can also use the remote-explorer tab, just select containers from the dropdown at the top left.

Why not to ssh remote host

When attaching visual studio code to a container, you can check logs by clicking the notification Setting up Remote-Containers (show log) at the bottom left. There, you can check that:

...
[26154 ms] Start: Run: ssh some-remote-host /bin/sh
[26160 ms] Start: Run in host: id -un

Here, my guess is that it’s trying to ssh to the remote host from itself ,since we already connected via remote-ssh.

Dharman's user avatar

Dharman

29.3k21 gold badges80 silver badges131 bronze badges

answered Mar 10, 2022 at 14:48

Alberto Rincon's user avatar

If you can reach the remote node running Docker engine via SSH why you need yet another SSH server inside the container? From the host running your container, it is possible and safe to use tty, i.e. attach.

I don’t think that this is not a good idea to use SSHD running inside the container although it is possible. To be useful SSHD has to listen to non-conflict port in every container. Otherwise, 2 containers occasionally exposing the same port on the same node will conflict like any other service running on same the node.

Of course, ports can be randomized using -P option but it is not so convenient. It is also less convenient to manage keys and users at the container level than at host level where all machinery is provided by the Host software.

Loading every container with SSHD increases the container size. In Kubernetes, every container is reachable without any SSHD running inside containers via pass Pod->Container because Pod, has IP and containers are attachable by id, i.e. «Docker-host->container»

7uc1f3r's user avatar

7uc1f3r

27.6k17 gold badges30 silver badges50 bronze badges

answered Jun 17, 2020 at 17:01

Pavel Sosin's user avatar

Step 1 — Docker daemon on the remote machine

  • make sure your remote Docker daemon can accept connections from your host
  • for testing purposes, I use the following command on the remote
    machine to force Docker daemon to listen on port 4243 on all IPs,
    beware this is not secure

There is no support for reading a file from /etc/sysconfig or elsewhere to modify the command line. Fortunately, systemd gives us the tools we need to change this behavior.
The simplest solution is probably to create the file /etc/systemd/system/docker.service.d/docker-external.conf (the exact filename doesn’t matter; it just needs to end with .conf) with the following contents:

[Service]
ExecStart=
ExecStart=/usr/bin/dockerd -H tcp://0.0.0.0:4243 -H unix:///var/run/docker.sock

And then:

systemctl daemon-reload
systemctl restart docker

Step 3 — Opening Docker Ports Using FirewallD

firewall-cmd --permanent --zone=public --change-interface=docker0
firewall-cmd --permanent --zone=public --add-port=4243/tcp
firewall-cmd --reload

Step 4 — Set (or add) "docker.host": "tcp://localhost:4243" in settings.json in VSCode.

answered Aug 17, 2020 at 12:20

Ali Motallebi's user avatar

Recommend Projects

  • React photo

    React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo

    Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo

    Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo

    TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo

    Django

    The Web framework for perfectionists with deadlines.

  • Laravel photo

    Laravel

    A PHP framework for web artisans

  • D3 photo

    D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Visualization

    Some thing interesting about visualization, use data art

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo

    Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo

    Microsoft

    Open source projects and samples from Microsoft.

  • Google photo

    Google

    Google ❤️ Open Source for everyone.

  • Alibaba photo

    Alibaba

    Alibaba Open Source for everyone

  • D3 photo

    D3

    Data-Driven Documents codes.

  • Tencent photo

    Tencent

    China tencent open source team.

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.

Понравилась статья? Поделить с друзьями:
  • Failed at step exec spawning exec format error
  • Failed api setaction error 0x80070057 параметр задан неверно
  • Failed an error occurred during host configuration esxi snmp
  • Failed a general system error occurred vim fault filenotfound
  • Failed a general system error occurred missing vstor2 driver or not started