How to specify user and group owner of a mounted device in Docker container?

Viewed 465

I'm using VSCode Devcontainer and:

  • I need to access /dev/kvm from within the container
  • I don't want the user in my container to be root

So, I start the container with --device=/dev/kvm and I can access it, however I can't use it because it's owned by root and by the kvm group from the host.

vscode@c017a6dc1bc0:/workspaces/project$ ls -l /dev/kvm
crw-rw---- 1 root 108 10, 232 May  1 09:56 /dev/kvm

The 108 id corresponds to the kvm group on host, but it's not mapped to anything in the container. Even if I create the group kvm it won't work. And I don't want to hardcode 108 because this is not reliable if I ever use the Dockerfile on another computer.

A possibility is to run chown myuser /dev/kvm from within the container, but myuser is non-root and I would like the kvm device to be automatically usable once container is started.

I know there exist the postCreateCommand in VScode but it won't execute as root neither and thus won't allow my to change group of /dev/kvm.

FROM ubuntu:20.04

ARG USERNAME=myuser
ARG USER_UID=1000
ARG USER_GID=$USER_UID

RUN groupadd --gid $USER_GID $USERNAME \
    && useradd --uid $USER_UID --gid $USER_GID -m $USERNAME
    # && groupadd -r kvm \
    # && adduser $USERNAME kvm \
    # && gpasswd -a $USERNAME kvm

USER $USERNAME
{
    "name": "Test container",
    "build": {
        "dockerfile": "Dockerfile"
    },
    "settings": {
        "terminal.integrated.shell.linux": "/bin/bash"
    },
    "remoteUser": "myuser",
    "runArgs": [
        "--device=/dev/kvm"
    ]
}

What is best practice in this case? Should I somehow mount /etc/group in container or something else? Is there a way from the Dockerfile to change group owner of a device mounted by the command line?

1 Answers

I found a hacky solution: I installed sudo in the container and allowed the non-root user to execute chgrp without password, then added sudo chgrp myuser /dev/kvm to my entrypoint script.

Here an example for kvm access for jenkins:

FROM jenkins/jenkins:2.339-jdk11
USER root

RUN apt-get update && apt-get install -y sudo && \ 
    rm -rf /var/lib/apt/lists/* && \
    echo "jenkins ALL = (root) NOPASSWD: /bin/chgrp" >> /etc/sudoers

USER jenkins

COPY initscript.sh /initscript.sh

ENTRYPOINT [ "/initscript.sh" ]

And the initscript file

#!/bin/bash
sudo chgrp jenkins /dev/kvm
/sbin/tini -- /usr/local/bin/jenkins.sh

maybe this works for your setup, too.

Related