File ownership after docker cp

前端 未结 4 1999

How can I control which user owns the files I copy in and out of a container?

The docker cp command says this about file ownership:

The cp

4条回答
  •  清歌不尽
    2021-02-19 23:50

    In order to get complete control of file ownership, I used the tar stream feature of docker cp:

    If - is specified for either the SRC_PATH or DEST_PATH, you can also stream a tar archive from STDIN or to STDOUT.

    I launch the docker cp process, then stream a tar file to or from the process. As the tar entries go past, I can adjust the ownership and permissions however I like.

    Here's a simple example in Python that copies all the files from /outputs in the sandbox1 container to the current directory, excludes the current directory so its permissions don't get changed, and forces all the files to have read/write permissions for the user.

    from subprocess import Popen, PIPE, CalledProcessError
    import tarfile
    
    def main():
        export_args = ['sudo', 'docker', 'cp', 'sandbox1:/outputs/.', '-']
        exporter = Popen(export_args, stdout=PIPE)
        tar_file = tarfile.open(fileobj=exporter.stdout, mode='r|')
        tar_file.extractall('.', members=exclude_root(tar_file))
        exporter.wait()
        if exporter.returncode:
            raise CalledProcessError(exporter.returncode, export_args)
    
    def exclude_root(tarinfos):
        print('\nOutputs:')
        for tarinfo in tarinfos:
            if tarinfo.name != '.':
                assert tarinfo.name.startswith('./'), tarinfo.name
                print(tarinfo.name[2:])
                tarinfo.mode |= 0o600
                yield tarinfo
    
    main()
    

提交回复
热议问题