Search code examples
dockerdocker-composenode-redi2craspberry-pi4

Accessing the i²c bus with Node-Red in Docker on a RaspberryPi 4


I am currently setting up Home Assistant with Docker on a RaspberryPi 4. I used this tutorial : https://www.reddit.com/r/homeassistant/comments/cm4tzp/guide_for_installing_on_a_raspberry_pi4_using/ as a reference - so far so good.

Thing is I would like to use the i²c interface of the Raspberry to communicate with different devices. The relevant part of the docker-compose.yaml file looks like that:

version: '3.8'
services:

[...]
  node-red:
      container_name: node-red
      image: nodered/node-red:latest
      user: "1000:1000"
      privileged: true
      ports:
        - "1880:1880"
      volumes:
        - /opt/node-red:/data
        - /etc/localtime:/etc/localtime:ro
        - /etc/timezone:/etc/timezone:ro
      devices:
        - /dev/mem:/dev/mem
        - /dev/gpiomem:/dev/gpiomem
        - /dev/i2c-1:/dev/i2c-1
      restart: unless-stopped
[...]

I mapped the user to pi (that's what the user: "1000:1000" line does as far as I understood) and set the container as privileged.

For context, this is the result of a few commands (for ls -l I only put in the relevant line):

pi@raspberrypi:/dev $ ls -l
crw-rw----  1 root i2c      89,   1 Jul  3 17:17 i2c-1
pi@raspberrypi:/dev $ groups pi
pi : pi adm dialout cdrom sudo audio video plugdev games users input netdev spi gpio docker i2c
id pi
uid=1000(pi) gid=1000(pi) groups=1000(pi),4(adm),20(dialout),24(cdrom),27(sudo),29(audio),44(video),46(plugdev),60(games),100(users),105(input),109(netdev),999(spi),997(gpio),995(docker),998(i2c)
pi@raspberrypi:~ $ docker --version
Docker version 19.03.12, build 48a6621

When I try to send something via I²C Node-Red outputs Error: EACCES: permission denied, open '/dev/i2c-1' in the debug tab.

When I replace the user: "1000:1000" line with user: "998:998" my Node-Red Flow works (I can send data to an Arduino) but I can't save any new ones (The Node-Red files are owned by pi ).

When I do sudo chmod 666 /dev/i2c-1 it also works but it's not secure and resets when the Raspberry restarts.

I could also change the ownership of /dev/i2c-1 to pi, it worked when I tried it but I would rather keep the i2c group if possible.

Why can't the Node-Red Container access /dev/i2c-1 as is?

What would be the best way to get it to work?


Solution

  • I just changed user: "1000:1000" to user: "1000:998" and everything seems to work. Until I find a better solution I'll only access directories owned by pi or the i2c group.

    Maybe I'll create a group just for this purpose.

    What seems to be the case is that although the UIDs in and outside of the container are the same, the user inside of the container doesn't have access to the directories owned by the groups the outside user is part of.