Jenkinsfile Throws docker: not found in Jenkins Running on Docker for CICD of Spring Boot Project - Stack Overflow

I'm encountering an issue in my Jenkins CICD pipeline where Jenkins running in a Docker container

I'm encountering an issue in my Jenkins CI/CD pipeline where Jenkins running in a Docker container is unable to find the docker command during the build process. Below is the setup:

  • Groovy Script for creating a Jenkins pipeline job programmatically.
  • Jenkins Dockerfile that installs Docker CLI. Docker Compose to define
  • services, including Jenkins and its dependencies. Jenkinsfile which
  • uses Docker to build a Docker image for the project.

Note : As I work with Windows , I change /var/run/docker.sock:/var/run/docker.sock to /var/run/docker.sock.raw:/var/run/docker.sock to detect testcontainer in the pipeline. Otherwise I cannot run integration.

Here is the groovy file shown below

import hudson.plugins.git.UserRemoteConfig
import hudson.plugins.git.BranchSpec
import hudson.plugins.git.GitSCM
import jenkins.model.*
import .jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition

def instance = Jenkins.getInstance()

def jobName = "flightsearchapi"
def job = instance.getItem(jobName)

if (job != null) {
    job.delete()
}

def pipelineJob = instance.createProject(.jenkinsci.plugins.workflow.job.WorkflowJob, jobName)
def definition = new CpsScmFlowDefinition(
        new GitSCM(
                [
                        new UserRemoteConfig(".git", null, null, null)
                ],
                [new BranchSpec("*/development/issue-2/implement-jenkins-for-ci-cd")],
                false, Collections.emptyList(),
                null, null, Collections.emptyList()
        ),
        "Jenkinsfile"
)
definition.setLightweight(true)
pipelineJob.setDefinition(definition)
pipelineJob.save()

println("Pipeline job '${jobName}' has been successfully created!")

Here is the plugin.txt

workflow-aggregator
git
job-dsl
ws-cleanup
docker-plugin
docker-workflow
docker-commons

Here is the Dockerfile shown below

FROM jenkins/jenkins:lts

# Plugin list
COPY plugins.txt /usr/share/jenkins/ref/plugins.txt
RUN jenkins-plugin-cli --plugin-file /usr/share/jenkins/ref/plugins.txt

# For Groovy scripts, init.d directory
COPY init.groovy.d/ /var/jenkins_home/init.groovy.d/

# Install Docker CLI
USER root
RUN apt-get update && apt-get install -y docker.io

Here is the docker-compose.yml

version: '3.9'

services:
  jenkins:
    build:
      context: .
      dockerfile: Dockerfile
    container_name: jenkins-server
    ports:
      - "8080:8080"    # Expose Jenkins UI on port 8080
      - "50000:50000"  # Expose port for Jenkins agents
    volumes:
      - jenkins_home:/var/jenkins_home   # Persistent Jenkins data
      - /var/run/docker.sock.raw:/var/run/docker.sock # Mount Docker socket for Docker builds
      - ../k8s:/var/jenkins_home/k8s # Mount Kubernetes configuration files (optional)
      - ./init.groovy.d:/var/jenkins_home/init.groovy.d # Mount Jenkins init scripts (optional)
    environment:
      JAVA_OPTS: "-Djenkins.install.runSetupWizard=false" # Skip setup wizard (optional)
    user: root # Run as root to allow installing dependencies

volumes:
  jenkins_home:

Here is the Jenkinsfile shown below

pipeline {
    agent {
        docker {
            image 'maven:3.9.9-amazoncorretto-21-alpine'
            args '-v /root/.m2:/root/.m2'
        }
    }

    environment {
        GIT_REPO_URL = '.git'
        BRANCH_NAME = 'development/issue-2/implement-jenkins-for-ci-cd'
        DOCKERHUB_USERNAME = 'noyandocker'
        DOCKER_IMAGE_NAME = 'flightsearchapi-jenkins'
    }

    stages {
        stage('Checkout') {
            steps {
                script {
                    checkout([
                        $class: 'GitSCM',
                        branches: [[name: "*/${env.BRANCH_NAME}"]],
                        userRemoteConfigs: [[url: "${env.GIT_REPO_URL}"]]
                    ])
                }
            }
        }

        stage('Build') {
            steps {
                sh 'mvn clean install'
            }
        }

        stage('Build Docker Image') {
            steps {
                sh "docker build -t ${env.DOCKERHUB_USERNAME}/${env.DOCKER_IMAGE_NAME}:latest ."
            }
        }

        stage('Push Docker Image') {
            steps {
                withDockerRegistry([credentialsId: 'docker-hub-credentials', url: '']) {
                    sh "docker push ${env.DOCKERHUB_USERNAME}/${env.DOCKER_IMAGE_NAME}:latest"
                }
            }
        }

    }

    post {
            always {
                cleanWs(cleanWhenNotBuilt: false,
                        deleteDirs: true,
                        disableDeferredWipeout: true,
                        notFailBuild: true,
                        patterns: [[pattern: '.gitignore', type: 'INCLUDE'],
                                   [pattern: '.propsfile', type: 'EXCLUDE']])
            }
        }
}

In the pipeline, I am attempting to build and push a Docker image as part of the CI/CD process, but the error message shows

+ docker build -t noyandocker/flightsearchapi-jenkins:latest .
/var/jenkins_home/workspace/flightsearchapi@tmp/durable-7294ca4e/script.sh.copy: line 1: docker: not found

Can you fix the issue ?

I'm encountering an issue in my Jenkins CI/CD pipeline where Jenkins running in a Docker container is unable to find the docker command during the build process. Below is the setup:

  • Groovy Script for creating a Jenkins pipeline job programmatically.
  • Jenkins Dockerfile that installs Docker CLI. Docker Compose to define
  • services, including Jenkins and its dependencies. Jenkinsfile which
  • uses Docker to build a Docker image for the project.

Note : As I work with Windows , I change /var/run/docker.sock:/var/run/docker.sock to /var/run/docker.sock.raw:/var/run/docker.sock to detect testcontainer in the pipeline. Otherwise I cannot run integration.

Here is the groovy file shown below

import hudson.plugins.git.UserRemoteConfig
import hudson.plugins.git.BranchSpec
import hudson.plugins.git.GitSCM
import jenkins.model.*
import .jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition

def instance = Jenkins.getInstance()

def jobName = "flightsearchapi"
def job = instance.getItem(jobName)

if (job != null) {
    job.delete()
}

def pipelineJob = instance.createProject(.jenkinsci.plugins.workflow.job.WorkflowJob, jobName)
def definition = new CpsScmFlowDefinition(
        new GitSCM(
                [
                        new UserRemoteConfig("https://github/Rapter1990/flightsearchapi.git", null, null, null)
                ],
                [new BranchSpec("*/development/issue-2/implement-jenkins-for-ci-cd")],
                false, Collections.emptyList(),
                null, null, Collections.emptyList()
        ),
        "Jenkinsfile"
)
definition.setLightweight(true)
pipelineJob.setDefinition(definition)
pipelineJob.save()

println("Pipeline job '${jobName}' has been successfully created!")

Here is the plugin.txt

workflow-aggregator
git
job-dsl
ws-cleanup
docker-plugin
docker-workflow
docker-commons

Here is the Dockerfile shown below

FROM jenkins/jenkins:lts

# Plugin list
COPY plugins.txt /usr/share/jenkins/ref/plugins.txt
RUN jenkins-plugin-cli --plugin-file /usr/share/jenkins/ref/plugins.txt

# For Groovy scripts, init.d directory
COPY init.groovy.d/ /var/jenkins_home/init.groovy.d/

# Install Docker CLI
USER root
RUN apt-get update && apt-get install -y docker.io

Here is the docker-compose.yml

version: '3.9'

services:
  jenkins:
    build:
      context: .
      dockerfile: Dockerfile
    container_name: jenkins-server
    ports:
      - "8080:8080"    # Expose Jenkins UI on port 8080
      - "50000:50000"  # Expose port for Jenkins agents
    volumes:
      - jenkins_home:/var/jenkins_home   # Persistent Jenkins data
      - /var/run/docker.sock.raw:/var/run/docker.sock # Mount Docker socket for Docker builds
      - ../k8s:/var/jenkins_home/k8s # Mount Kubernetes configuration files (optional)
      - ./init.groovy.d:/var/jenkins_home/init.groovy.d # Mount Jenkins init scripts (optional)
    environment:
      JAVA_OPTS: "-Djenkins.install.runSetupWizard=false" # Skip setup wizard (optional)
    user: root # Run as root to allow installing dependencies

volumes:
  jenkins_home:

Here is the Jenkinsfile shown below

pipeline {
    agent {
        docker {
            image 'maven:3.9.9-amazoncorretto-21-alpine'
            args '-v /root/.m2:/root/.m2'
        }
    }

    environment {
        GIT_REPO_URL = 'https://github/Rapter1990/flightsearchapi.git'
        BRANCH_NAME = 'development/issue-2/implement-jenkins-for-ci-cd'
        DOCKERHUB_USERNAME = 'noyandocker'
        DOCKER_IMAGE_NAME = 'flightsearchapi-jenkins'
    }

    stages {
        stage('Checkout') {
            steps {
                script {
                    checkout([
                        $class: 'GitSCM',
                        branches: [[name: "*/${env.BRANCH_NAME}"]],
                        userRemoteConfigs: [[url: "${env.GIT_REPO_URL}"]]
                    ])
                }
            }
        }

        stage('Build') {
            steps {
                sh 'mvn clean install'
            }
        }

        stage('Build Docker Image') {
            steps {
                sh "docker build -t ${env.DOCKERHUB_USERNAME}/${env.DOCKER_IMAGE_NAME}:latest ."
            }
        }

        stage('Push Docker Image') {
            steps {
                withDockerRegistry([credentialsId: 'docker-hub-credentials', url: '']) {
                    sh "docker push ${env.DOCKERHUB_USERNAME}/${env.DOCKER_IMAGE_NAME}:latest"
                }
            }
        }

    }

    post {
            always {
                cleanWs(cleanWhenNotBuilt: false,
                        deleteDirs: true,
                        disableDeferredWipeout: true,
                        notFailBuild: true,
                        patterns: [[pattern: '.gitignore', type: 'INCLUDE'],
                                   [pattern: '.propsfile', type: 'EXCLUDE']])
            }
        }
}

In the pipeline, I am attempting to build and push a Docker image as part of the CI/CD process, but the error message shows

+ docker build -t noyandocker/flightsearchapi-jenkins:latest .
/var/jenkins_home/workspace/flightsearchapi@tmp/durable-7294ca4e/script.sh.copy: line 1: docker: not found

Can you fix the issue ?

Share Improve this question asked Jan 29 at 13:21 Sercan Noyan GermiyanoğluSercan Noyan Germiyanoğlu 2,7864 gold badges53 silver badges124 bronze badges 2
  • 1 Your sh "docker ..." commands are running inside the Maven image from the agent { ... } block; if that image doesn't have the Docker CLI installed and access to the host's Docker socket then you might get that error. Can you move the agent declaration to only the specific build step that needs it? Does using the Jenkins Docker plugin everywhere instead of sh "docker ..." work any better? – David Maze Commented Jan 29 at 15:27
  • @DavidMaze I saw Docker Plugin is added as plugin when I open the Jenkins through docker-compose up -d . Can you provide the solution for me? – Sercan Noyan Germiyanoğlu Commented Jan 29 at 15:48
Add a comment  | 

1 Answer 1

Reset to default 0

The issue disappeared after I followed these steps shown below

1 ) Change agent as any from docker image

2 ) Define mvn for build step and docker for its relevant step

Here is the code shown below.

pipeline {
    agent any
    ...

    stage('Build') {
                agent {
                        docker {
                            image 'maven:3.9.9-amazoncorretto-21-alpine'
                        }
                    }
                steps {
                    sh 'mvn clean install'
                }
            }
    
            stage('Build Docker Image') {
                agent {
                    docker {
                        image 'docker:27.5.1'
                    }
                }
                steps {
                    sh "docker build -t ${env.DOCKERHUB_USERNAME}/${env.DOCKER_IMAGE_NAME}:latest ."
                }
            }
    
            stage('Push Docker Image') {
                agent {
                    docker {
                        image 'docker:27.5.1'
                    }
                }
                steps {
                    withDockerRegistry([credentialsId: 'docker-hub-credentials', url: '']) {
                        sh "docker push ${env.DOCKERHUB_USERNAME}/${env.DOCKER_IMAGE_NAME}:latest"
                    }
                }
            }
    ...
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745295659a4621124.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信