Module 7 Lesson 1: Docker-in-Docker (DinD)
·DevOps

Module 7 Lesson 1: Docker-in-Docker (DinD)

The chicken and the egg. Learn how to run Docker commands inside a Docker container to build your application images within a GitLab pipeline.

Module 7 Lesson 1: Docker-in-Docker (DinD)

Most GitLab Runners run inside a Docker container. To build a new Docker image for your app, you need to run the docker build command inside that container. This is called Docker-in-Docker (DinD).

1. The Challenge

Imagine a set of Russian Nesting Dolls:

  1. The Host Server (Runs the GitLab Runner).
  2. The Runner Container (Runs your job).
  3. The Build Command (Needs to start another container to build your image).

2. Enabling DinD in YAML

To use Docker commands, you must add the docker:dind service to your job.

build-image:
  image: docker:24.0.5 # The CLI tool
  services:
    - docker:24.0.5-dind # The background engine
  variables:
    DOCKER_TLS_CERTDIR: "/certs" # Required for security
  script:
    - docker build -t my-app .
    - docker images

3. Why Use DinD?

  • Isolation: Every job gets its own separate Docker engine. They cannot interfere with each other.
  • Security: You don't have to share the Host's "Docker Socket" (which is a security risk).
  • Cloud Ready: It works perfectly on "GitLab.com" shared runners.

4. The Performance Penalty

DinD is slightly slow because it has to start a whole Docker engine from scratch for every job.

  • The Fix: In Lesson 5, we will look at Kaniko, which is a faster alternative for building images without needing a full Docker engine.

Exercise: The Image Builder

  1. Create a project with a simple Dockerfile.
  2. Add the build-image job from Section 2 to your .gitlab-ci.yml.
  3. Run the pipeline. Watch the logs. Did the dind service start correctly?
  4. Why is the DOCKER_TLS_CERTDIR variable necessary? (Research: "Docker TLS verification").
  5. If you change a file in your project, how long does the docker build step take on the second run? (What happened to the cache?)

Summary

DinD is the standard way to build containers in the cloud. By understanding the "Nesting" nature of Docker-in-Docker, you can automate the creation of your application images securely and reliably.

Next Lesson: Ship it: Building and pushing images to registries.

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn