繁体   English   中英

如何从 jenkins 脚本在 docker 容器内运行命令

[英]How to run a command inside a docker container from a jenkins script

我有一个看起来像这样的詹金斯脚本:

    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
                '''
            }
        }
    }
}

它执行成功,但它显示的主机名不是 docker 容器,而是它运行的机器。

如果我在 docker run 命令中尝试使用“-t”,那么我会得到“输入设备不是 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
                '''
            }
        }
    }
}

输入设备不是 TTY 错误:脚本返回退出代码 1

有什么建议可以运行一组命令(除了来自 docker 容器内的“主机名”吗?

谢谢!

Jenkins 具有可用于声明式管道的本机Docker支持。 因此,您可以使用Docker映像作为代理,也可以使用 Docker 步骤。

使用图像作为代理。

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'
            }
        }
    }
}

使用泊坞窗步骤

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'
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM