1 简介
Docker 是一个流行的容器化平台,用于打包和运行应用程序。而 Docker SDK for Python 是 Python 提供的一个工具包,它让开发者能够通过 Python 脚本与 Docker 引擎进行交互。本教程将介绍如何安装 Docker SDK,并展示如何使用它来管理 Docker 容器和镜像。
2 安装 Docker SDK for Python
首先,我们需要安装 Docker SDK for Python。你可以通过以下命令轻松安装:
!pip install docker
Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple
Requirement already satisfied: docker in d:\soft\anaconda\envs\auto_four\lib\site-packages (7.1.0)
Requirement already satisfied: pywin32>=304 in d:\soft\anaconda\envs\auto_four\lib\site-packages (from docker) (308)
Requirement already satisfied: requests>=2.26.0 in d:\soft\anaconda\envs\auto_four\lib\site-packages (from docker) (2.32.3)
Requirement already satisfied: urllib3>=1.26.0 in d:\soft\anaconda\envs\auto_four\lib\site-packages (from docker) (2.2.3)
Requirement already satisfied: charset-normalizer<4,>=2 in d:\soft\anaconda\envs\auto_four\lib\site-packages (from requests>=2.26.0->docker) (3.4.0)
Requirement already satisfied: idna<4,>=2.5 in d:\soft\anaconda\envs\auto_four\lib\site-packages (from requests>=2.26.0->docker) (3.10)
Requirement already satisfied: certifi>=2017.4.17 in d:\soft\anaconda\envs\auto_four\lib\site-packages (from requests>=2.26.0->docker) (2024.8.30)
如果你已经安装了 Docker 并且能够在命令行中使用 docker 命令,安装这个 SDK 后你就可以通过 Python 控制 Docker 了。
3 使用 Docker SDK 连接到 Docker 守护进程
Docker SDK 默认通过 Unix socket 或 TCP 连接到本地 Docker 守护进程。如果你的 Docker 守护进程是本地的,那么你可以直接通过默认设置来连接。
import docker# 创建 Docker 客户端
client = docker.from_env()# 查看 Docker 客户端的版本
print(client.version())
{'Platform': {'Name': 'Docker Desktop 4.35.1 (173168)'}, 'Components': [{'Name': 'Engine', 'Version': '27.3.1', 'Details': {'ApiVersion': '1.47', 'Arch': 'amd64', 'BuildTime': '2024-09-20T11:41:11.000000000+00:00', 'Experimental': 'false', 'GitCommit': '41ca978', 'GoVersion': 'go1.22.7', 'KernelVersion': '5.15.167.4-microsoft-standard-WSL2', 'MinAPIVersion': '1.24', 'Os': 'linux'}}, {'Name': 'containerd', 'Version': '1.7.21', 'Details': {'GitCommit': '472731909fa34bd7bc9c087e4c27943f9835f111'}}, {'Name': 'runc', 'Version': '1.1.13', 'Details': {'GitCommit': 'v1.1.13-0-g58aa920'}}, {'Name': 'docker-init', 'Version': '0.19.0', 'Details': {'GitCommit': 'de40ad0'}}], 'Version': '27.3.1', 'ApiVersion': '1.47', 'MinAPIVersion': '1.24', 'GitCommit': '41ca978', 'GoVersion': 'go1.22.7', 'Os': 'linux', 'Arch': 'amd64', 'KernelVersion': '5.15.167.4-microsoft-standard-WSL2', 'BuildTime': '2024-09-20T11:41:11.000000000+00:00'}
4 列出所有容器
要列出当前系统上所有的容器,可以使用 containers.list()
方法:
# 列出所有容器,包括运行和停止的容器
containers = client.containers.list(all=True)# 打印容器的名称和状态
for container in containers:print(f"容器名称: {container.name}, 状态: {container.status}")
容器名称: cool_davinci, 状态: exited
容器名称: awesome_cohen, 状态: exited
容器名称: angry_spence3, 状态: exited
容器名称: naughty_maxwell, 状态: exited
容器名称: nostalgic_jennings, 状态: exited
容器名称: angry_satoshi, 状态: exited
容器名称: dazzling_raman, 状态: exited
容器名称: charming_cohen, 状态: exited
容器名称: mystifying_brattain, 状态: exited
5 创建和运行一个容器
创建并启动一个新的 Docker 容器(例如,运行一个简单的 hello-world 容器):
# 运行一个容器
container = client.containers.run("hello-world", detach=True)# 获取容器的状态
print(f"容器 {container.name} 状态: {container.status}")
容器 distracted_swirles 状态: created
如果需要以交互模式运行容器,可以这样做:
container = client.containers.run("ubuntu", "echo hello", detach=True, tty=True)
6 管理 Docker 镜像
列出系统中所有的 Docker 镜像:
# 列出所有镜像
images = client.images.list()# 打印镜像的名称
for image in images:print(f"镜像: {image.tags}")
镜像: ['my_python_app:latest']
镜像: ['ubuntu:latest']
镜像: ['python:3-slim']
镜像: ['python:3.12-slim']
镜像: ['hello-world:latest']
拉取一个 Docker 镜像:
# 拉取镜像
image = client.images.pull("alpine")
print(f"镜像 {image.tags[0]} 已经被拉取")
镜像 alpine:latest 已经被拉取
7 停止和删除容器
停止运行中的容器并删除它:
# 停止容器
container = client.containers.get("4e6d4c25f094")
container.stop()# 删除容器
container.remove()
8 处理容器日志
获取容器的日志,可以帮助你调试应用程序:
# 获取容器的日志
container = client.containers.get('76fb52b969e5')
logs = container.logs()
print(logs.decode('utf-8'))
hello
9 错误处理
使用 Docker SDK 时,可能会遇到一些常见的错误。可以使用 try-except 来处理:
try:container = client.containers.get('76fb52b969eq')
except docker.errors.NotFound:print("容器未找到!")
容器未找到!
10 注意事项
1. container = client.containers.run(“ubuntu”, “echo hello”, detach=True, tty=True)为什么在jupyter环境中没有打印出来
解决方法:
2. docker run hello-world 为什么没有hello-world在运行
具体问题:
C:\Users\32564>docker run hello-worldHello from Docker!
This message shows that your installation appears to be working correctly.To generate this message, Docker took the following steps:1. The Docker client contacted the Docker daemon.2. The Docker daemon pulled the "hello-world" image from the Docker Hub.(amd64)3. The Docker daemon created a new container from that image which runs theexecutable that produces the output you are currently reading.4. The Docker daemon streamed that output to the Docker client, which sent itto your terminal.To try something more ambitious, you can run an Ubuntu container with:$ docker run -it ubuntu bashShare images, automate workflows, and more with a free Docker ID:https://hub.docker.com/For more examples and ideas, visit:https://docs.docker.com/get-started/C:\Users\32564>docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
为什么没有hello-world在运行
解决方法:
3. “No such container: ubuntu”
具体问题:
我在后台启动后,怎么出现NotFound Traceback (most recent call last)
Cell In[14], line 21 # 停止容器
----> 2 container = client.containers.get("ubuntu")File d:\soft\anaconda\envs\auto_four\Lib\site-packages\docker\models\containers.py:954, in ContainerCollection.get(self, container_id)938 def get(self, container_id):939 """940 Get a container by name or ID.941
...37 else:38 cls = NotFound
---> 39 raise cls(e, response=response, explanation=explanation) from eNotFound: 404 Client Error for http+docker://localnpipe/v1.47/containers/ubuntu/json: Not Found ("No such container: ubuntu")
解决方法: