Docker-in-Docker with GitHub Actions

Are you trying to build and push a Docker image from GitHub Actions?

Perhaps you’re getting an error like this:

Cannot connect to the Docker daemon at unix:///var/run/docker.sock.

followed by

Is the docker daemon running?

No problem. This means that the Docker client is failing to connect to the Docker daemon. Here are two options to fix that.

The first thing that’s required is to set up a separate Docker-in-Docker service. Once that’s sorted you need to configure the mode of communication with that sevice. There are two alternatives: socket or port.

Using a Socket

To use a socket to communicate with the Docker-in-Docker service you need to volume mount /var/run/docker.sock.

name: Test Docker on GitHub Actions

on:
  pull_request:
  push:
    branches: 
      - master

jobs:
  push_container:
    runs-on: ubuntu-latest
    services:
      docker:
        image: docker:dind
        options: --privileged --shm-size=2g
        volumes:
          - /var/run/docker.sock:/var/run/docker.sock:ro
    container:
      image: ubuntu:latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Install Docker
        run: |
          apt-get update
          apt-get install -y docker.io          

      - name: Test Docker
        run: |
          docker version
          docker info          

Using a Port

To connect via TCP port 2375 you need to expose that port from the service.

name: Test Docker on GitHub Actions

on:
  pull_request:
  push:
    branches: 
      - master

jobs:
  push_container:
    runs-on: ubuntu-latest
    services:
      docker:
        image: docker:dind
        options: --privileged
        ports:
          - 2375:2375
    container:
      image: ubuntu:latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Install Docker
        run: |
          apt-get update
          apt-get install -y docker.io          

      - name: Test connection
        run: |
          apt-get update
          apt-get install -y iputils-ping
          ping -c 3 docker          

      - name: Test Docker
        run: |
          docker version
          docker info          

The step that tests the network connection using ping is not necessary. Nor is the step that tests the connection to the Docker service. Once you have got this running you can safely remove those steps.