Jenkins Docker映像-仅将`jobs`文件夹放入命名卷时的权限问题

时间:2019-03-07 13:33:58

标签: docker jenkins docker-volume

我通过在自己的Dockerfile中扩展the official image在Docker容器中运行Jenkins。

该页面的顶部建议将整个$JENKINS_HOME文件夹放入一个命名卷中,以使通过UI进行的更改在容器重新启动和重新创建时得以保留。

但是,我不希望整个$JENKINS_HOME文件夹成为该卷的一部分,而只是$JENKINS_HOME/jobs文件夹。原因如下:

  • install_plugins.sh脚本在图像构建过程as documented here期间从基础图像设置插件。
  • 所有其他配置都将由configuration-as-code plugin在每个图像构建中从头开始创建。
  • 只有在每次构建映像时都不会从头开始重新创建作业,因此,这些作业应保留在命名卷中。

结果,我像这样启动了Jenkins容器:

docker run \
    -p 8080:8080 \
    -p 50000:50000 \
    -v jenkins-jobs:/var/jenkins_home/jobs \
    my-custom-jenkins-image

容器现在无法正确以日志中的permission denied错误开头。通过$JENKINS_HOME检查docker exec container_name_or_id ls -ahl /var/jenkins_home内部的权限表明,$JENKINS_HOME/jobs现在由root拥有,而不是{那里拥有所有其他文件和子目录的jenkins用户{1}}本身。

有趣的是,当将整个$JENKINS_HOME文件夹放入一个命名卷中时,$JENKINS_HOME用户将正确拥有其中的所有文件和子文件夹。

如何仅将jenkins文件夹放入命名卷中,并确保它属于容器内部的jobs用户?

修改: 我的jenkins精简到最低限度就是这样。但是,我不怀疑这是根本原因,因为在运行Dockerfile库存图像时会发生相同的情况,如下所示:

jenkins/jenkins:lts

可以找到on GitHub的基础图像的docker run \ -p 8080:8080 \ -p 50000:50000 \ -v jenkins-jobs:/var/jenkins_home/jobs \ jenkins/jenkins:lts

Dockerfile

1 个答案:

答案 0 :(得分:0)

可怕的解决方法,可以解决问题,直到找到更好的解决方案为止:

  1. 将以下几行添加到Dockerfile
FROM jenkins/jenkins:lts

USER root

# Install additional tools and plugins, set up configuration etc.

# We need the gosu tool to step down from the root user to an unprivileged
# user as part of the entrypoint script.
# See further: https://github.com/tianon/gosu
RUN apt-get -y update && apt-get -y install gosu

# Note that we stay the root user and do not step down to the jenkins user yet.
COPY fix_volume_ownership.sh /usr/local/bin/fix_volume_ownership.sh
ENTRYPOINT ["/sbin/tini", "--", "/usr/local/bin/fix_volume_ownership.sh"]

创建fix_volume_ownership.sh

#!/bin/bash

# This script is run by the root user in order to have the privileges to change
# ownership of the jobs directory. The jobs directory is mounted as a named
# volume and otherwise is owned by the root user so that the jenkins user
# cannot write into it.
#
# "gosu" finally steps down from the root user to the jenkins user since we
# do not want to run the Jenkins process with root privileges.
#
# /usr/local/bin/jenkins.sh is the original entrypoint script from the base image.

chown -R jenkins:jenkins /var/jenkins_home/jobs
gosu jenkins /usr/local/bin/jenkins.sh

现在,docker exec container_name_or_id ls -ahl /var/jenkins_home将显示jobs用户正确拥有jenkins子文件夹。此外,docker exec container_name_or_id ps aux将显示jenkins用户正在运行Jenkins进程。