【问题标题】:File permissions in Docker ContainerDocker 容器中的文件权限
【发布时间】:2018-05-25 21:33:48
【问题描述】:

我有一个简单的 tomcat docker 文件,如下所示。

FROM tomcat:7
MAINTAINER ***
COPY sample.war /opt/tomcat/webapps
USER tomcat
RUN chown -R tomcat:tomcat /tmp/
CMD ["catalina.sh", "run"]

当我创建 docker 镜像时,它会给我文件权限

tomcat tomcat  Dec 11 08:04 tmp

我的示例应用程序在 tmp 文件夹中创建了几个目录,我希望所有者是 tomcat,但它看起来像 root。由于我以 tomcat 用户身份运行容器,如何使其使用 tomcat 用户来创建这些。

【问题讨论】:

    标签: linux docker dockerfile file-permissions


    【解决方案1】:

    我尝试构建和运行您提供的Dockerfile,但遇到了多个错误。您正在询问您的“应用程序”创建的文件权限。所以这是我的出发点:

    我假设“应用程序”是catalina.sh。在/tmp/ 中创建文件的过程。由于我们以用户tomcat 运行容器,因此它会自动创建具有相应文件权限的文件。查看下面的代码 cmets 以获取有关此处发生的更多信息。

    Dockerfile:

    FROM httpd 
    # I switched the image since you would need to configure tomcat to make it run
    # httpd works out of the box without any application specific config. That's why
    
    COPY ./catalina.sh /
    RUN chmod +x /catalina.sh  # copy your 'app' / entrypoint into the image
    
    RUN groupadd -r tomcat \
        && useradd -r -g tomcat tomcat
    # create a new user and group under which the container runs
    RUN chown -R tomcat:tomcat /tmp/  # change initial file permisisons. 
    # So that our new user tomcat is allowed to access and fill the directory with files
    
    USER tomcat  # switch the user under which the container runs
    
    ENTRYPOINT ["/catalina.sh"]
    

    catalina.sh:

    #!/bin/bash
    
    mkdir /tmp/test  # create a dir
    touch /tmp/yolo.txt  # and some files
    touch /tmp/test/yolo2.txt  # to check the file permissions later on
    
    while true; do echo "sleep"; sleep 2; done
    # endless loop so that the container doesn't exit
    

    检查文件权限exec到正在运行的容器中。

    docker exec -ti <container_name> bash

    【讨论】:

    • catalina.sh 不是应用程序。它是 Tomcat 的启动脚本。 catalina.sh run 在前台启动 tomcat,在您启动它的控制台上显示日志。按 Ctrl-C 将终止 tomcat。
    • 我想这没什么区别。如果您在 Dockerfile 中提供 USER 指令,则您正在此上下文中运行容器。因此,当tomcat 创建新文件时,这些文件将具有关联的文件权限。应该是相同的行为。把镜像切换回tomcat试试看。
    【解决方案2】:

    Docker 通常以 root 权限运行,所以我相信您必须创建一个 docker 组(如果它不存在),并将用户(在您的情况下为 tomcat)添加到 docker 组。

    见下文如何将用户添加到 docker 组:

    创建 docker 组。

    $ sudo groupadd docker
    

    将您的用户添加到 docker 组。

    $ sudo usermod -aG docker tomcat
    

    参考:https://docs.docker.com/engine/installation/linux/linux-postinstall/#manage-docker-as-a-non-root-user

    有了这个,相信你的问题就可以解决了。

    【讨论】:

      猜你喜欢
      • 2019-09-11
      • 1970-01-01
      • 2018-04-28
      • 2019-12-26
      • 2018-09-02
      • 1970-01-01
      • 2020-01-17
      • 2018-02-08
      • 2019-02-11
      相关资源
      最近更新 更多