
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:
- The Host Server (Runs the GitLab Runner).
- The Runner Container (Runs your job).
- 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
- Create a project with a simple
Dockerfile. - Add the
build-imagejob from Section 2 to your.gitlab-ci.yml. - Run the pipeline. Watch the logs. Did the
dindservice start correctly? - Why is the
DOCKER_TLS_CERTDIRvariable necessary? (Research: "Docker TLS verification"). - If you change a file in your project, how long does the
docker buildstep 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.