Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python Library API สำหรับ Docker (docker-py)

สามารถเข้าถึง จัดการ และควบคุม Docker objects เช่น containers, images, clusters, swarms ผ่าน Python library API ได้เกือบทุกอย่างที่ CLI ทำได้ เหมาะสำหรับแอป Python (Django, Flask) ที่ต้องจัดการ container จากสคริปต์เดียวกัน

การติดตั้ง

pip3 install docker-py

เชื่อมต่อ Docker Daemon

from docker import client

myClient = client.Client(base_url='unix://var/run/docker.sock')

จัดการ Containers

รายการ Containers ทั้งหมด

myClient.containers()

สร้าง Container ใหม่

myContainer = myClient.create_container(image='ubuntu:latest', command='/bin/bash')
print(myContainer['Id'])

ตรวจสอบ Container (Inspect)

myClient.inspect_container('container_id')
myClient.inspect_container('container_id')['Name']
myClient.inspect_container('container_id')['Created']
myClient.inspect_container('container_id')['Path']

Commit Container (สร้าง Image ใหม่)

myClient.commit('container_id', tag='container1')

Restart Container (พร้อม Try-Except)

try:
    myClient.restart('container_id')
except Exception as e:
    print(e)

จัดการ Images

images = myClient.images()
print(images[0])

myClient.inspect_image('image_id')

จัดการ Volumes

volumes = myClient.volumes()
print(volumes['Volumes'][0])

# สร้าง Volume
volume = myClient.create_volume(name='myVolume1', driver='local', driver_opts={})
print(volume)

# Inspect Volume
myClient.inspect_volume('myVolume1')

# สร้าง Container พร้อม Mount Volume
mounted_container = myClient.create_container(
    'ubuntu', 'ls',
    volumes=['/var/lib/docker/volumes/myVolume1'],
    host_config=myClient.create_host_config(binds=[
        '/var/lib/docker/volumes/myVolume1:/usr/src/app/myVolume1'
    ])
)

สรุป

docker-py ช่วยให้จัดการ Docker ทั้งหมดจาก Python script ได้ เหมาะสำหรับ CI/CD, automation, หรือ web app ที่ต้องควบคุม container