在Docker容器中运行命令而无需挂载项目目录

时间:2019-03-18 07:53:46

标签: docker jenkins-pipeline

我的Jenkins管道使用docker-workflow插件。它构建一个Docker映像并将其标记为app。构建步骤获取一些依赖项,并将其与我的应用程序一起烘焙到图像中。

我想基于该图像在容器内运行两个命令。该命令应在构建环境中执行,并且可以访问依赖项。我尝试使用Image.inside,但是它似乎失败了,因为inside将项目目录安装在工作目录(?)上,因此依赖项不可用。

docker.image("app").inside {
    sh './run prepare-tests'
    sh './run tests'
}

我也尝试使用docker.script.withDockerContainer,但是命令似乎没有在容器内运行。 Image.withRun似乎也是如此。至少我可以指定一个命令,但是似乎我必须在一条语句中运行两个命令。似乎还withRun doesn't fail the build if the command doesn't exit cleanly

docker
  .image("app")
  .withRun('', 'bash -c "./app prepare-tests && ./app tests"') { container ->
    sh "exit \$(docker wait ${container.id})"
  }

有没有一种方法可以使用Image.inside而不挂载项目目录?还是有更优雅的方式做到这一点?

1 个答案:

答案 0 :(得分:1)

docker DSL,例如docker.image().inside() {}等,会将jenkins作业工作区目录挂载到容器,并将其作为WORKDIR,它将覆盖Dockerfile中的WORKDIR

您可以从jenkins控制台输出中进行验证。

1)CD顽固的工作目录

docker.image("app").inside {
    sh '''
        cd <WORKDIR of image specifyed in Dockerfile>
        ./run prepare-tests
        ./run tests
    '''
}

2)在sh中运行容器,而不是通过docker DSL

sh '''
    docker run -i app bash -c "./run prepare-tests && ./run tests"
'''