Connect to docker container as user other than root

后端 未结 9 1035
没有蜡笔的小新
没有蜡笔的小新 2020-12-13 01:38

BY default when you run

docker run -it [myimage]

OR

docker attach [mycontainer]

you connect to the terminal as r

9条回答
  •  粉色の甜心
    2020-12-13 01:52

    My solution:

    #!/bin/bash
    user_cmds="$@"
    
    GID=$(id -g $USER)
    UID=$(id -u $USER)
    RUN_SCRIPT=$(mktemp -p $(pwd))
    (
    cat << EOF
    addgroup --gid $GID $USER
    useradd --no-create-home --home /cmd --gid $GID --uid $UID  $USER
    cd /cmd
    runuser -l $USER -c "${user_cmds}"
    EOF
    ) > $RUN_SCRIPT
    
    trap "rm -rf $RUN_SCRIPT" EXIT
    
    docker run -v $(pwd):/cmd --rm my-docker-image "bash /cmd/$(basename ${RUN_SCRIPT})"
    

    This allows the user to run arbitrary commands using the tools provides by my-docker-image. Note how the user's current working directory is volume mounted to /cmd inside the container.

    I am using this workflow to allow my dev-team to cross-compile C/C++ code for the arm64 target, whose bsp I maintain (the my-docker-image contains the cross-compiler, sysroot, make, cmake, etc). With this a user can simply do something like:

    cd /path/to/target_software
    cross_compile.sh "mkdir build; cd build; cmake ../; make"
    

    Where cross_compile.sh is the script shown above. The addgroup/useradd machinery allows user-ownership of any files/directories created by the build.

    While this works for us. It seems sort of hacky. I'm open to alternative implementations ...

提交回复
热议问题