How to Fix Docker Connection Refused on Kubernetes Pod
The Root Cause
“Docker Connection Refused” within a Kubernetes pod occurs when an application inside the container attempts to connect to a Docker daemon. This typically fails because containers run in isolated environments; the Docker daemon is part of the host node’s operating system, not the pod’s filesystem, rendering access to paths like /var/run/docker.sock impossible from within the container by default.
Quick Fix (CLI)
To resolve this, mount the host’s Docker socket into the pod. This allows the containerized application to communicate with the Docker daemon running on the Kubernetes node.
-
Identify the Deployment, StatefulSet, or Pod definition you need to modify.
-
Edit the resource definition (e.g., a Deployment):
kubectl edit deployment your-deployment-name -
Add the following
volumeMountsto your container’s spec and define thedocker-socketvolume underspec.template.spec.volumes. This snippet should be inserted into the existing YAML structure.# ... inside spec.template.spec spec: containers: - name: your-container-name image: your-image:tag volumeMounts: - name: docker-socket mountPath: /var/run/docker.sock # Add 'privileged: true' if the application needs more extensive Docker-in-Docker capabilities # Or if it fails without it (e.g., specific image building tools). # privileged: true volumes: - name: docker-socket hostPath: path: /var/run/docker.sock type: Socket # ... rest of your YAML -
Save and exit the editor. Kubernetes will roll out the changes, restarting your pods with the new configuration.
Configuration Check
The modification involves two key additions to your Kubernetes YAML definition (Deployment, StatefulSet, or Pod):
-
volumeMountswithin the container spec:volumeMounts: - name: docker-socket mountPath: /var/run/docker.sockThis section specifies that a volume named
docker-socketshould be mounted at/var/run/docker.sockinside your container. -
volumeswithin the pod template spec:volumes: - name: docker-socket hostPath: path: /var/run/docker.sock type: SocketThis section defines the
docker-socketvolume, mapping it to the host node’s/var/run/docker.sock. Thetype: Socketexplicitly indicates it’s a Unix domain socket.
Verification
- Check Pod Status: Ensure your new pods are running successfully.
kubectl get pods -l app=your-app-label - Test Docker Interaction from within the Pod: Exec into a running pod and attempt a Docker command (assuming a Docker client is available in your container image).
If successful,kubectl exec -it <your-pod-name> -- docker infodocker infowill display information about the host’s Docker daemon, confirming the connection is no longer refused. - Monitor Application Logs: Check your application’s logs for any further “Docker Connection Refused” errors.
kubectl logs <your-pod-name>