Configuring Docker‑in‑Docker for Jenkins Pipelines and Multi‑Stage Builds
This tutorial explains how to set up Docker‑in‑Docker for Jenkins, mount the Docker socket, run containers as root, and create multi‑stage pipelines that use different Docker images for Maven and Node builds, including troubleshooting tips.
This guide demonstrates how to configure Docker‑in‑Docker for Jenkins, mount the Docker socket inside the Jenkins master container, and run commands as the root user to avoid permission problems.
docker run --name jenkins -itd \ -p 8081:8080 \ -p 50000:50000 \ -v ~/jenkins:/var/jenkins_home \ -v /var/run/docker.sock:/var/run/docker.sock \ -v /usr/local/bin/docker:/usr/bin/docker \ jenkins/jenkins:lts
To solve permission issues, run the container as root and add the Jenkins user to the root group:
docker exec -it -u root jenkins bash usermod -aG root jenkins id jenkins
A basic Jenkins pipeline using a Docker agent with a Maven image can be written as:
pipeline { agent { docker { image 'maven:3.6.3-jdk-8' args '-v $HOME/.m2:/root/.m2' } } stages { stage('Build') { steps { sh 'mvn -v' } } } }
The pipeline execution log shows the container being started, Maven version output, and successful completion:
Started by user admin Running in Durability level: MAX_SURVIVABILITY [Pipeline] Start of Pipeline ... (log details) ... Apache Maven 3.6.3 ... Finished: SUCCESS
To run different stages in different Docker containers, define each stage with its own agent. For example, a Maven stage and a Node.js stage:
pipeline { agent none stages { stage('ServiceBuild') { agent { docker { image 'maven:3.6.3-jdk-8' args '-v $HOME/.m2:/root/.m2' } } steps { sh 'mvn -v && sleep 15' } } stage('WebBuild') { agent { docker { image 'node:7-alpine' args '-v $HOME/.m2:/root/.m2' } } steps { sh 'node -v && sleep 15' } } } }
A frontend‑focused pipeline using a Node image and npm configuration can be written as:
pipeline { agent none stages { stage('WebBuild') { agent { docker { image 'node:10.19.0-alpine' args '-u 0:0 -v /var/jenkins_home/.npm:/root/.npm' } } steps { sh ''' id ls /root/.npm npm config set unsafe-perm=true npm config set cache /root/.npm # npm config set registry https://registry.npm.taobao.org npm install --unsafe-perm=true && npm run build && ls -l dist/ && sleep 15 ''' } } } }
FAQ notes: use the root user for npm builds to avoid permission errors, mount a cache volume (e.g., -v /var/jenkins_home/.npm:/root/.npm ) to speed up builds, and optionally set the npm registry to the Taobao mirror ( npm config set registry https://registry.npm.taobao.org ).
DevOps Cloud Academy
Exploring industry DevOps practices and technical expertise.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.