sanjay patel
sanjay patel

Reputation: 449

Running commands inside docker container created using Dockerfile in Jenkinsfile

I have created a Jenkins pipeline file and created a Jenkinsfile. Inside Jenkinsfile I have used Dockerfile agent and then running some steps. The steps are supposed to run inside docker but they are running on the host. Hers the code.

#!/usr/bin/env groovy
@Library(['abc-jenkins','xyz-jenkins-library']) _
pipeline {
agent {
    dockerfile{
        dir 'TEST'
        filename 'dockerfile'
        label 'docker'
    }
}
stages {
    stage('Build Stage') {
        steps {
            echo 'testing stage running'
            sh "ls"
        }
    }
}   
}

Upvotes: 4

Views: 12418

Answers (3)

Michael
Michael

Reputation: 51

You may using -> docker.image('image').inside{..}

stage('BuildInside') {
         docker.image('ubuntu1804').withRun('-d=true -p 8888:8080') {c ->
            docker.image('ubuntu1804').inside{
               /*  Do something here inside container  */
               sh "ls"
            }
        }
  }

Upvotes: 2

yong
yong

Reputation: 13712

You misunderstand it according to the output of ls.

For Jenkins pipeline docker DSL, it will mount the jenkins job workspace to docker container and change the docker WORKDIR to the jenkins job workspace.

Therefor when you execute ls inside container, it will print the files & fodler under your jenkins job workspace.

You can try other cmd or ls other folder that not exists in host to approve it's really be executed inside container rather than host.

Upvotes: 6

EduMoga
EduMoga

Reputation: 83

You have to write the agent creation stage inside the stages brackets:

stages {
    stage('Build Stage') {
        agent {
           dockerfile{
           dir 'TEST'
           filename 'dockerfile'
           label 'docker'
        }
        steps {
           echo 'testing stage running'
           sh "ls"
       }
}

Upvotes: 0

Related Questions