16

Been trying to set-up Gitlab CI which can build a docker image, and came across that DinD was enabled initially only for separate runners and Blog Post suggest it would be enabled soon for shared runners,

Running DinD requires enabling privileged mode in runners, which is set as a flag while registering runner, but couldn't find an equivalent mechanism for Shared Runners

Somasundaram Sekar
  • 5,244
  • 6
  • 43
  • 85

1 Answers1

41

The shared runners are now capable of building Docker images. Here is the job that you can use:

stages:
  - build
  - test
  - deploy

# ...
# other jobs here
# ...

docker:image:
  stage: deploy
  image: docker:1.11
  services:
    - docker:dind
  script:
    - docker version
    - docker build -t $CI_REGISTRY_IMAGE:latest .
    # push only for tags
    - "[[ -z $CI_BUILD_TAG ]] && exit 0"
    - docker tag $CI_REGISTRY_IMAGE:latest $CI_REGISTRY_IMAGE:$CI_BUILD_TAG
    - docker login -u gitlab-ci-token -p $CI_BUILD_TOKEN $CI_REGISTRY
    - docker push $CI_REGISTRY_IMAGE:$CI_BUILD_TAG

This job assumes that you are using the Container Registry provided by Gitlab. It pushes the images only when the build commit is tagged with a version number.

  • Documentation for Predefined variables.

  • Note that you will need to cache or generate as temporary artifacts of any dependencies for your service which are not committed in the repository. This is supposed to be done in other jobs. e.g. node_modules are not generally contained in the repository and must be cached from the build/test stage.

psiyumm
  • 6,437
  • 3
  • 29
  • 50
  • "shared runners are now capable of building Docker images" - I assume you mean the ones on GitLab.com? How do you setup secure shared GitLab Runner setup for Docker Build? See also https://gitlab.com/gitlab-org/gitlab-ce/issues/31379 – bbodenmiller Apr 25 '17 at 09:28
  • I also had to set `DOCKER_HOST` job variable to `tcp://docker:2375` with a config like this. Other things work perfect! – madhead Jul 02 '18 at 23:43
  • Correction: if you are using image other then `docker` for the job itself (`job.image` and not the `job.services..image`) and that image uses Docker service (my case was Java Docker API trying to talk to Docker) then you have to set `DOCKER_HOST` job variable to `tcp://docker:2375` with a config like this, because this value is actually set in non-dind `docker` images for you. – madhead Jul 02 '18 at 23:50
  • 1
    `services: - docker:dind` part helped me to solve `Cannot connect to the Docker daemon` – vladkras Jan 20 '19 at 11:23
  • Do we need to use TLS here? The docs https://docs.gitlab.com/ee/ci/docker/using_docker_build.html#docker-in-docker-with-tls-enabled indicate that TLS may be disabled when we don't control the runner configuration. Therefore does it make sense to use the TLS-enabled version or non-TLS enabled version? – CMCDragonkai Nov 21 '21 at 04:58