将主机组导入 Docker 容器 [英] Import host group into Docker container

查看:33
本文介绍了将主机组导入 Docker 容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在树莓派上使用 Docker.我想以用户身份(而不是 root 用户)访问容器中的 GPIO 线.

I am using Docker on a raspberry. I want to access the GPIO lines from the container as a user (not as root).

树莓派运行 raspbian 8.0.

The raspberry run raspbian 8.0.

在主机上查看/sys/class的内容:

pi@raspberrypi:~ $ ls -al /sys/class/
total 0
[...]
drwxrwx---  2 root gpio 0 Sep 27 19:05 gpio
[...]

该文件夹属于 gpio 组.

The folder belongs to the group gpio.

当我以这种方式启动容器时:

When I launch my container this way:

docker run -it --privileged container-name bash

用户无法访问 gpio 文件夹:

The user can't access the gpio folder:

root@f66a9f1cca91:/# su user
user@f66a9f1cca91:/$ ls /sys/class/gpio/
ls: cannot open directory /sys/class/gpio/: Permission denied

即使用户是 gpio 组的一部分,因为我在 Dockerfile 中创建了该组并将其分配给我的用户:

Even though the user is part of the gpio group, because I created the group in the Dockerfile and assigned it to my user:

user@f66a9f1cca91:/$ groups user
user : user gpio fuse

这是因为,由于某种原因,gpio 组丢失了:

This is because, for some reason, the gpio group is lost:

root@f66a9f1cca91:/# ls -al /sys/class/
total 0
[...]
drwxrwx---  2 root  997 0 Sep 27 19:05 gpio
[...]

如何让容器识别分组?

作为一种解决方法,我可以更改 /etc/group 以便 gpio 组匹配正确的 UID.问题是 gpio 组的 UID 可以在我下次在 raspberry 上安装 raspbian 时更改.

As a workaround, I can change /etc/group so the gpio group match the proper UID. The problem is that the UID of the gpio group can change on my next install of raspbian on the raspberry.

有没有办法在 Dockerfile 中动态创建 gpio 组或检索主机 gpio GID?

Any way to dynamically create the gpio group or retrieve the host gpio GID within the Dockerfile ?

推荐答案

我最终在容器启动时添加了一个 startup.sh.Dockerfile:

I ended up adding a startup.sh when the container is started. Dockerfile:

ADD startup.sh /root/
RUN chmod +c /root/startup.sh
CMD bash -c startup.sh ; bash

startup.sh:

startup.sh:

#!/bin/bash

# Change local gpio group GID to the host gpio group GID so use jedi has access to /sys/class/gpio
sed -r "s/gpio:([^:]*):[0-9]*/gpio:\1:$(grep gpio ~/host/etc/group | awk -F ':' '{ print $3 }')/g" /etc/group > /tmp/group
mv /tmp/group /etc/group

并以这种方式挂载 /etc 文件夹:

And mount the /etc folder this way:

然后我以这种方式将主机/etc 文件夹挂载到容器中:

Then I mount the host /etc folder into the container this way:

docker tun -it -v /etc/:/root/host/etc/

这样,容器中的 gpio 组与主机上的 gpio 组具有相同的 GID,并且用户可以通过文件系统 /sys/class/gpio 访问 gpio 线.

With this, the gpio group in the container have the same GID as the gpio group on the host and the user have access to the gpio line via the filesystem /sys/class/gpio.

这篇关于将主机组导入 Docker 容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆