This guide explains how to set up Docker inside Docker (DinD). This approach is useful for CI/CD pipelines, enabling Docker commands to be executed within a Docker container.
- Docker installed on the host machine
- Basic knowledge of Docker commands
- Docker Compose (optional, for easier orchestration)
If Docker is not already installed on your host machine, follow these steps:
-
Update the package database:
sudo apt-get update
-
Install prerequisites:
sudo apt-get install apt-transport-https ca-certificates curl software-properties-common
-
Add Docker’s official GPG key:
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add - -
Add Docker’s repository:
sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" -
Install Docker CE:
sudo apt-get update sudo apt-get install docker-ce
-
Verify Docker installation:
docker --version
Create a Dockerfile that uses the official Docker-in-Docker image:
# Dockerfile
FROM docker:20.10.7-dind
# Optional: Install any additional packages
RUN apk add --no-cache git
# Optional: Create a working directory
WORKDIR /app
# Optional: Copy application files
COPY . /app
# Entry point for the Docker container
CMD ["sh"]Build the Docker image from the Dockerfile:
docker build -t my-dind-image .Run a container using the DinD image with necessary Docker daemon options:
docker run --privileged --name my-dind-container -d docker:20.10.7-dind--privileged grants the container extended privileges. --name assigns a name to the container. -d runs the container in detached mode.
- Access the running DinD container:
docker exec -it my-dind-container sh - Verify Docker daemon is running inside the container:
docker info
- Run Docker commands inside the container:
docker run hello-world
To stop and remove the DinD container:
docker stop my-dind-container
docker rm my-dind-containerTo remove the Docker image:
docker rmi my-dind-imageYou have successfully set up Docker inside Docker (DinD). This configuration is ideal for CI/CD pipelines and allows you to run Docker commands within a Docker container.
