Share files between host system and docker container using specific UID

前端 未结 4 1103
耶瑟儿~
耶瑟儿~ 2020-12-14 10:08

I\'m trying to share files within a Docker guest using the volume sharing. In order to get the same UID, and therefore interoperability with those files, I would like to cr

4条回答
  •  北海茫月
    2020-12-14 10:43

    The environment is not shared, you could use -e, --env options to set env variables in container.

    I usually use this approach when I want to have the same owner of the mapped volume: I check uid & gid of directory in container and then create a corresponding user. Here my script (setuser.sh) which creates a user for a directory:

    #!/bin/bash
    
    setuser() {
      if [ -z "$1" ]; then
        echo "Usage: $0 "
        return
      fi
      CURRENT_UID=`id -u`
      DEST_UID=`stat -c "%u" $1`
      if [ $CURRENT_UID = $DEST_UID ]; then
        return
      fi
      DEST_GID=`stat -c "%g" $1`
      if [ -e /home/$DEST_UID ]; then
        return
      fi
      groupadd -g $DEST_GID $DEST_GID
      useradd -u $DEST_UID -g $DEST_GID $DEST_UID
      mkdir -p /home/$DEST_UID
      chown $DEST_UID:$DEST_GID /home/$DEST_UID
    }
    setuser $1
    

    And this is the wrapper script which runs commands as the user, where the directory with permissions is specified either as $USER_DIR or in /etc/user_dir

    #!/bin/bash
    if [ -z "$USER_DIR" ]; then
      if [ -e /etc/user_dir ]; then
        export USER_DIR=`head -n 1 /etc/user_dir`
      fi
    fi
    if [ -n "$USER_DIR" ]; then
      if [ ! -d "$USER_DIR" ]; then
        echo "Please mount $USER_DIR before running this script"
        exit 1
      fi
      . `dirname $BASH_SOURCE`/setuser.sh $USER_DIR
    fi
    if [ -n "$USER_DIR" ]; then
      cd $USER_DIR
    fi
    if [ -e /etc/user_script ]; then
      . /etc/user_script
    fi
    if [ $CURRENT_UID = $DEST_UID ]; then
      "$@"
    else
      su $DEST_UID -p -c "$@"
    fi
    

    P.S. Alleo suggested different approach: to map users and groups files into container and to specify uid and gid. So your container does not depend on built-in users/groups you could use it without additional scripts.

提交回复
热议问题