How to Fix Docker Connection Refused on AWS EC2


The Root Cause This error commonly occurs on AWS EC2 instances when the Docker daemon is not running, or the user lacks the necessary permissions to access the Docker socket /var/run/docker.sock. By default, newly provisioned EC2 instances, even with Docker installed, may not automatically add the default user to the docker group, leading to permission denied errors often masked as “connection refused.”

Quick Fix (CLI)

  1. Start and Enable Docker Daemon:
    sudo systemctl start docker
    sudo systemctl enable docker
  2. Add Current User to the docker Group:
    sudo usermod -aG docker $USER
  3. Apply Group Changes:
    newgrp docker
    # For changes to persist across sessions, log out and log back into the EC2 instance.

Configuration Check File: /etc/docker/daemon.json

If this file exists, ensure it is correctly configured to include the default Unix socket. If it does not exist, Docker will typically use its default configuration, which includes the Unix socket. If it exists and explicitly excludes the Unix socket or contains errors, connection refused can occur.

{
  "hosts": ["unix:///var/run/docker.sock"]
  // Add other configurations as needed (e.g., "log-driver", "data-root").
  // If you also need TCP access, add it like: "tcp://0.0.0.0:2375"
}

After modifying or creating daemon.json, restart the Docker daemon:

sudo systemctl restart docker

Verification

docker ps

A successful output will display a list of running containers or an empty list with no error message, confirming successful communication with the Docker daemon.

sudo systemctl status docker

Confirm the Docker daemon service is reported as active (running).