Home > OS >  How to run a command inside a docker container from a jenkins script
How to run a command inside a docker container from a jenkins script

Time:07-08

I have a jenkins script that looks like this:

    pipeline {
    agent {
        label 'machine'
    }
    
    stages {
        stage('GC Open Build') {
            steps {
                sh '''
                    docker run -i --rm \
                       -u $(id -u):$(id -g) \
                       -e USER_NAME=$(id -un) \
                       -e GROUP_NAME=$(id -gn) \
                       -e HOME \
                       -v $HOME:$HOME \
                       -v /PROJ:/PROJ:shared \
                       -v /srv:/srv \
                       -w $PWD \
                       i-st-pd-docker-vxxxxxx
                       bash | hostname
                '''
            }
        }
    }
}

It executes successfully, but the hostname it displays is not the docker container, but the machine on which it runs.

If I try with '-t' in the docker run command, then I get "the input device is not a tty":

pipeline {
    agent {
        label 'machine'
    }
    
    stages {
        stage('GC Open Build') {
            steps {
                sh '''
                    docker run -it --rm \
                       -u $(id -u):$(id -g) \
                       -e USER_NAME=$(id -un) \
                       -e GROUP_NAME=$(id -gn) \
                       -e HOME \
                       -v $HOME:$HOME \
                       -v /PROJ:/PROJ:shared \
                       -v /srv:/srv \
                       -w $PWD \
                       i-st-pd-docker-v.xxxx
                       bash | hostname
                '''
            }
        }
    }
}

the input device is not a TTY ERROR: script returned exit code 1

Any suggestions to be able to run a set of commands (other than "hostname" from inside the docker container?

Thank you!

CodePudding user response:

Jenkins has native Docker support available for declarative pipelines. So you can either use your Docker image as an agent or you can use the Docker step.

Using the image as an agent.

pipeline {
    agent any
    stages {
        stage('Build') {
            agent {
                docker {
                    image 'gradle:6.7-jdk11'
                    // Run the container on the node specified at the
                    // top-level of the Pipeline, in the same workspace,
                    // rather than on a new node entirely:
                    reuseNode true
                }
            }
            steps {
                sh 'gradle --version'
            }
        }
    }
}

Using docker step

docker.image('mysql:5').inside("--link ${c.id}:db") {
            /* Wait until mysql service is up */
            sh 'while ! mysqladmin ping -hdb --silent; do sleep 1; done'
        }
  • Related