目录

安装 Docker SDK for Python

pip install docker

例子

将本地文件或目录添加到容器,生成新的镜像。

  • put_archive
  • commit
import docker
import tarfile
import tempfile
import os

def simple_tar(path):
    f = tempfile.NamedTemporaryFile()
    t = tarfile.open(mode='w', fileobj=f)
    abs_path = os.path.abspath(path)
    t.add(abs_path, arcname=os.path.basename(path))
    t.close()
    f.seek(0)
    return f

client = docker.from_env()
container = client.containers.create('alpine')
with simple_tar('test') as test_tar:
    container.put_archive('/', test_tar)

container.commit('test-alpine')

container.remove()
client.close()

参考资料