Using docker socket in Kubernetes pod

10/30/2019

I want to prune docker images, I wrote a small Docker image using node-docker-api and I was able to test it locally with success.
As I've deployed the DaemonSet to Kubernetes, the pod fails to access the Docker socket:

Error: connect EACCES /var/run/docker.sock

The deployment.yaml looks as following:

apiVersion: extensions/v1beta1
kind: DaemonSet
metadata:
  labels:
    name: docker-image-cleanup
  name: docker-image-cleanup
spec:
  template:
    metadata:
      labels:
        app: docker-image-cleanup 
    spec:
      volumes:
        - name: docker-sock
          hostPath:
            path: "/var/run/docker.sock"
            type: File
        - name: docker-directory
          hostPath:
            path: "/var/lib/docker"

      containers:
        - name: docker-image-cleanup
          image: image:tag
          securityContext:
            privileged: true
          env:
            - name: PRUNE_INTERVAL_SECONDS
              value: "30"
            - name: PRUNE_DANGLING
              value: "true"
          volumeMounts:
            - mountPath: /var/run/docker.sock
              name: docker-sock
              readOnly: false
            - mountPath: "/var/lib/docker"
              name: docker-directory
              readOnly: false

Running AKS v1.13.10 - if relevant

-- SagiLow
azure-aks
docker
kubernetes
kubernetes-pod

2 Answers

10/30/2019

I've added runAsUser: 0 to the container properties:

containers:
  - name: docker-image-cleanup
    image: image:tag
    securityContext:
      privileged: true
      runAsUser: 0

Now it works

-- SagiLow
Source: StackOverflow

10/30/2019

There is no guarantee that your kubernetes cluster is actually using docker as container engine. As there are many alternatives like cri-o and kata containers your application/deployment should make no assumptions about the underlying container engine.

Kubernetes takes care about cleaning up unused container images automatically. See documentation on how to configure it, if you run the cluster yourself: https://kubernetes.io/docs/concepts/cluster-administration/kubelet-garbage-collection/

Aside from that it looks like you have a simple permission problem with the socket: Make sure your application in the cleanup container runs as root or has appropriate user to access the socket.

-- Thomas
Source: StackOverflow