Share files between host system and docker container using specific UID

前端 未结 4 1108
耶瑟儿~
耶瑟儿~ 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:33

    I slightly modified @ISanych answer:

    #!/usr/bin/env bash
    
    user_exists() {
      id -u $1 > /dev/null 2>&1
    }
    
    group_exists() {
      id -g $1 > /dev/null 2>&1
    }
    
    setuser() {
      if [[ "$#" != 3 ]]; then
        echo "Usage: $0   "
        return
      fi
      local dest_uid=$(stat -c "%u" $1)
      local dest_gid=$(stat -c "%g" $1)
      if user_exists $dest_uid; then
        id -nu $dest_uid
        return
      fi
      local dest_user=$2
      local dest_group=$3
    
      if user_exists $dest_user; then
        userdel $dest_user
      fi
    
      if group_exists $dest_group; then
        groupdel $dest_user
      fi
    
      groupadd -g $dest_gid $dest_group
      useradd -u $dest_uid -g $dest_gid -s $DEFAULT_SHELL -d $DEFAULT_HOME -G root $dest_user
      chown -R $dest_uid:$dest_gid $DEFAULT_HOME
      id -nu $dest_user
    }
    
    REAL_USER=$(setuser $SRC_DIR $DEFAULT_USER $DEFAULT_GROUP)
    

    setuser function accepts user and group names that you want to assign to uid and gid of provided directory. Then if user with such uid exists then it simply returns login corresponding to this uid, otherwise it creates user and group and returns login originally passed to function.

    So you get the login of user that owns destination directory.

提交回复
热议问题