CircleCI 内で Docker のコマンドを使いたい場合

結論

steps の中で setup_remote_docker を実行(記述)した後、docker コマンドを実行します。

具体例

NG な例(setup_remote_docker を実行しない場合)

setup_remote_docker を実行しないと次のようにエラーになります。

.circleci/config.yml は次のとおりとします。

version: 2.1

executors:
  ubuntu:
    docker:
      - image: cimg/base:stable-20.04

jobs:
  foobar:
    executor: ubuntu
    steps:
      - checkout
      - run:
          command: |
            docker run --rm ubuntu:20.10 /bin/echo 'Hello, World!'

workflows:
  version: 2
  hogehoge:
    jobs:
      - foobar

上記のジョブが実行されると以下のようにエラーになります。

#!/bin/bash -eo pipefail
docker run --rm ubuntu:20.10 /bin/echo 'Hello, World!'

docker: Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?.
See 'docker run --help'.

Exited with code exit status 125
CircleCI received exit code 125

OK な例(setup_remote_docker を実行する場合)

setup_remote_docker を実行ておくと期待通りの動作になります。

.circleci/config.yml は次のとおりとします。

version: 2.1

executors:
  ubuntu:
    docker:
      - image: cimg/base:stable-20.04

jobs:
  foobar:
    executor: ubuntu
    steps:
      - checkout
      - setup_remote_docker
      - run:
          command: |
            docker run --rm ubuntu:20.10 /bin/echo 'Hello, World!'

workflows:
  version: 2
  hogehoge:
    jobs:
      - foobar

上記のジョブが実行されると以下のように期待通りの動作になります。

#!/bin/bash -eo pipefail
docker run --rm ubuntu:20.10 /bin/echo 'Hello, World!'

Unable to find image 'ubuntu:20.10' locally
20.10: Pulling from library/ubuntu

Digest: sha256:a7b08558af07bcccca994b01e1c84f1d14a2156e0099fcf7fcf73f52d082791e
Status: Downloaded newer image for ubuntu:20.10
Hello, World!
CircleCI received exit code 0

補足

  • CircleCI の CLI で実行した場合は setup_remote_docker を記述していたとしても実行に失敗します
  • GitHub Actions の場合は特別な準備は不要です
Powered by はてなブログ