Copying files from Docker container to host

后端 未结 18 2390
小蘑菇
小蘑菇 2020-11-22 13:39

I\'m thinking of using Docker to build my dependencies on a Continuous Integration (CI) server, so that I don\'t have to install all the runtimes and libraries on the agents

18条回答
  •  萌比男神i
    2020-11-22 14:13

    This can also be done in the SDK for example python. If you already have a container built you can lookup the name via console ( docker ps -a ) name seems to be some concatenation of a scientist and an adjective (i.e. "relaxed_pasteur").

    Check out help(container.get_archive) :

    Help on method get_archive in module docker.models.containers:
    
    get_archive(path, chunk_size=2097152) method of docker.models.containers.Container instance
        Retrieve a file or folder from the container in the form of a tar
        archive.
    
        Args:
            path (str): Path to the file or folder to retrieve
            chunk_size (int): The number of bytes returned by each iteration
                of the generator. If ``None``, data will be streamed as it is
                received. Default: 2 MB
    
        Returns:
            (tuple): First element is a raw tar data stream. Second element is
            a dict containing ``stat`` information on the specified ``path``.
    
        Raises:
            :py:class:`docker.errors.APIError`
                If the server returns an error.
    
        Example:
    
            >>> f = open('./sh_bin.tar', 'wb')
            >>> bits, stat = container.get_archive('/bin/sh')
            >>> print(stat)
            {'name': 'sh', 'size': 1075464, 'mode': 493,
             'mtime': '2018-10-01T15:37:48-07:00', 'linkTarget': ''}
            >>> for chunk in bits:
            ...    f.write(chunk)
            >>> f.close()
    

    So then something like this will pull out from the specified path ( /output) in the container to your host machine and unpack the tar.

    import docker
    import os
    import tarfile
    
    # Docker client
    client = docker.from_env()
    #container object
    container = client.containers.get("relaxed_pasteur")
    #setup tar to write bits to
    f = open(os.path.join(os.getcwd(),"output.tar"),"wb")
    #get the bits
    bits, stat = container.get_archive('/output')
    #write the bits
    for chunk in bits:
        f.write(chunk)
    f.close()
    #unpack
    tar = tarfile.open("output.tar")
    tar.extractall()
    tar.close()
    

提交回复
热议问题