Skip to content

Docker API 参考

Docker 提供了功能强大的 REST API,允许您以编程方式管理容器、镜像、网络和卷。本文将详细介绍 Docker API 的使用方法和常见端点。

目录

  1. API 概述
  2. 认证与安全
  3. 容器 API
  4. 镜像 API
  5. 网络 API
  6. 卷 API
  7. 系统 API
  8. SDK 使用

API 概述

1.1 API 版本

Docker 版本API 版本说明
24.0.x1.43BuildKit 默认启用
23.0.x1.42新构建系统
20.10.x1.41多平台构建支持
19.03.x1.40BuildKit 支持
18.09.x1.39上下文支持

1.2 API 端点格式

Base URL: http://localhost/v{version}/

示例:
- http://localhost/v1.43/containers/json
- http://localhost/v1.43/images/json

1.3 启用 API 访问

bash
# 方法 1: 修改守护进程配置
# /etc/docker/daemon.json
{
  "hosts": ["unix:///var/run/docker.sock", "tcp://0.0.0.0:2375"]
}

# 方法 2: 使用 systemd drop-in
sudo mkdir -p /etc/systemd/system/docker.service.d
sudo tee /etc/systemd/system/docker.service.d/override.conf <<EOF
[Service]
ExecStart=
ExecStart=/usr/bin/dockerd -H fd:// -H tcp://0.0.0.0:2375
EOF
sudo systemctl daemon-reload
sudo systemctl restart docker

认证与安全

2.1 TLS 认证配置

bash
# 生成 CA 私钥
openssl genrsa -aes256 -out ca-key.pem 4096

# 生成 CA 证书
openssl req -new -x509 -days 365 -key ca-key.pem -sha256 -out ca.pem

# 生成服务器私钥
openssl genrsa -out server-key.pem 4096

# 生成服务器证书签名请求
openssl req -subj "/CN=server" -sha256 -new -key server-key.pem -out server.csr

# 添加扩展属性
echo subjectAltName = DNS:localhost,IP:192.168.1.100,IP:127.0.0.1 > extfile.cnf

# 签名服务器证书
openssl x509 -req -days 365 -sha256 -in server.csr -CA ca.pem -CAkey ca-key.pem \
  -CAcreateserial -out server-cert.pem -extfile extfile.cnf

# 生成客户端证书
openssl genrsa -out key.pem 4096
openssl req -subj '/CN=client' -new -key key.pem -out client.csr
echo extendedKeyUsage = clientAuth > extfile.cnf
openssl x509 -req -days 365 -sha256 -in client.csr -CA ca.pem -CAkey ca-key.pem \
  -CAcreateserial -out cert.pem -extfile extfile.cnf

# 清理
rm -v client.csr server.csr extfile.cnf ca.srl

2.2 配置 Docker 使用 TLS

json
{
  "tls": true,
  "tlscacert": "/etc/docker/ca.pem",
  "tlscert": "/etc/docker/server-cert.pem",
  "tlskey": "/etc/docker/server-key.pem",
  "tlsverify": true,
  "hosts": ["tcp://0.0.0.0:2376", "unix:///var/run/docker.sock"]
}

2.3 API 调用示例(带 TLS)

bash
# 使用 curl 调用 API
curl --cacert ca.pem --cert cert.pem --key key.pem \
  https://192.168.1.100:2376/v1.43/containers/json

# 使用 Docker 客户端
docker --tlsverify --tlscacert=ca.pem --tlscert=cert.pem --tlskey=key.pem \
  -H=tcp://192.168.1.100:2376 version

容器 API

3.1 列出容器

bash
# 列出运行中的容器
curl --unix-socket /var/run/docker.sock \
  "http://localhost/v1.43/containers/json"

# 列出所有容器
curl --unix-socket /var/run/docker.sock \
  "http://localhost/v1.43/containers/json?all=true"

# 带过滤条件
curl --unix-socket /var/run/docker.sock \
  "http://localhost/v1.43/containers/json?filters={\"status\":[\"running\"]}"

响应示例:

json
[
  {
    "Id": "a1b2c3d4e5f6...",
    "Names": ["/web"],
    "Image": "nginx:alpine",
    "ImageID": "sha256:1234...",
    "Command": "nginx -g 'daemon off;'",
    "Created": 1699999999,
    "Ports": [
      {
        "PrivatePort": 80,
        "PublicPort": 8080,
        "Type": "tcp"
      }
    ],
    "Labels": {
      "app": "web"
    },
    "State": "running",
    "Status": "Up 2 hours",
    "HostConfig": {
      "NetworkMode": "default"
    },
    "NetworkSettings": {
      "Networks": {
        "bridge": {
          "IPAddress": "172.17.0.2"
        }
      }
    }
  }
]

3.2 创建容器

bash
# 创建容器
curl -X POST \
  --unix-socket /var/run/docker.sock \
  -H "Content-Type: application/json" \
  -d '{
    "Hostname": "web",
    "Image": "nginx:alpine",
    "ExposedPorts": {
      "80/tcp": {}
    },
    "HostConfig": {
      "PortBindings": {
        "80/tcp": [{"HostPort": "8080"}]
      },
      "Memory": 536870912,
      "CpuShares": 512,
      "RestartPolicy": {
        "Name": "always"
      }
    },
    "Env": [
      "NGINX_HOST=localhost",
      "NGINX_PORT=80"
    ],
    "Labels": {
      "app": "web",
      "environment": "production"
    }
  }' \
  "http://localhost/v1.43/containers/create?name=my-nginx"

响应示例:

json
{
  "Id": "a1b2c3d4e5f6...",
  "Warnings": []
}

3.3 启动/停止容器

bash
# 启动容器
curl -X POST \
  --unix-socket /var/run/docker.sock \
  "http://localhost/v1.43/containers/my-nginx/start"

# 停止容器
curl -X POST \
  --unix-socket /var/run/docker.sock \
  "http://localhost/v1.43/containers/my-nginx/stop?t=30"

# 重启容器
curl -X POST \
  --unix-socket /var/run/docker.sock \
  "http://localhost/v1.43/containers/my-nginx/restart"

# 暂停容器
curl -X POST \
  --unix-socket /var/run/docker.sock \
  "http://localhost/v1.43/containers/my-nginx/pause"

# 恢复容器
curl -X POST \
  --unix-socket /var/run/docker.sock \
  "http://localhost/v1.43/containers/my-nginx/unpause"

3.4 删除容器

bash
# 删除容器
curl -X DELETE \
  --unix-socket /var/run/docker.sock \
  "http://localhost/v1.43/containers/my-nginx"

# 强制删除运行中的容器
curl -X DELETE \
  --unix-socket /var/run/docker.sock \
  "http://localhost/v1.43/containers/my-nginx?force=true"

# 删除容器并删除关联卷
curl -X DELETE \
  --unix-socket /var/run/docker.sock \
  "http://localhost/v1.43/containers/my-nginx?v=true"

3.5 查看容器详情

bash
# 查看容器详情
curl --unix-socket /var/run/docker.sock \
  "http://localhost/v1.43/containers/my-nginx/json"

# 查看容器日志
curl --unix-socket /var/run/docker.sock \
  "http://localhost/v1.43/containers/my-nginx/logs?stdout=true&stderr=true&tail=100"

# 查看容器进程
curl --unix-socket /var/run/docker.sock \
  "http://localhost/v1.43/containers/my-nginx/top"

# 查看容器变更
curl --unix-socket /var/run/docker.sock \
  "http://localhost/v1.43/containers/my-nginx/changes"

3.6 在容器中执行命令

bash
# 创建 exec 实例
curl -X POST \
  --unix-socket /var/run/docker.sock \
  -H "Content-Type: application/json" \
  -d '{
    "AttachStdin": false,
    "AttachStdout": true,
    "AttachStderr": true,
    "Cmd": ["ls", "-la"]
  }' \
  "http://localhost/v1.43/containers/my-nginx/exec"

# 启动 exec 实例(响应中包含 exec ID)
curl -X POST \
  --unix-socket /var/run/docker.sock \
  -H "Content-Type: application/json" \
  -d '{
    "Detach": false,
    "Tty": false
  }' \
  "http://localhost/v1.43/exec/<exec-id>/start"

3.7 获取容器统计信息

bash
# 获取容器统计(流式)
curl --unix-socket /var/run/docker.sock \
  "http://localhost/v1.43/containers/my-nginx/stats"

# 获取单个统计快照
curl --unix-socket /var/run/docker.sock \
  "http://localhost/v1.43/containers/my-nginx/stats?stream=false"

响应示例:

json
{
  "read": "2024-01-01T00:00:00Z",
  "pids_stats": {
    "current": 5
  },
  "memory_stats": {
    "usage": 6537216,
    "limit": 104857600
  },
  "cpu_stats": {
    "cpu_usage": {
      "total_usage": 1234567890
    },
    "system_cpu_usage": 9876543210
  },
  "networks": {
    "eth0": {
      "rx_bytes": 1234,
      "tx_bytes": 5678
    }
  }
}

镜像 API

4.1 列出镜像

bash
# 列出所有镜像
curl --unix-socket /var/run/docker.sock \
  "http://localhost/v1.43/images/json"

# 带过滤条件
curl --unix-socket /var/run/docker.sock \
  "http://localhost/v1.43/images/json?filters={\"dangling\":[\"true\"]}"

响应示例:

json
[
  {
    "Id": "sha256:a1b2c3d4e5f6...",
    "RepoTags": ["nginx:alpine", "nginx:latest"],
    "RepoDigests": ["nginx@sha256:1234..."],
    "Created": 1699999999,
    "Size": 23456789,
    "VirtualSize": 23456789,
    "Labels": {
      "maintainer": "NGINX Team"
    }
  }
]

4.2 拉取镜像

bash
# 拉取镜像
curl -X POST \
  --unix-socket /var/run/docker.sock \
  -H "Content-Type: application/json" \
  -d '{
    "fromImage": "nginx",
    "tag": "alpine"
  }' \
  "http://localhost/v1.43/images/create"

# 从私有仓库拉取
curl -X POST \
  --unix-socket /var/run/docker.sock \
  -H "X-Registry-Auth: <base64-encoded-auth>" \
  -d '{
    "fromImage": "myregistry.com/myapp",
    "tag": "v1.0"
  }' \
  "http://localhost/v1.43/images/create"

4.3 构建镜像

bash
# 构建镜像(使用 BuildKit)
curl -X POST \
  --unix-socket /var/run/docker.sock \
  -H "Content-Type: application/x-tar" \
  --data-binary @build-context.tar \
  "http://localhost/v1.43/build?t=myapp:v1.0&dockerfile=Dockerfile"

# 带构建参数
curl -X POST \
  --unix-socket /var/run/docker.sock \
  -H "Content-Type: application/x-tar" \
  --data-binary @build-context.tar \
  "http://localhost/v1.43/build?t=myapp:v1.0&buildargs={\"VERSION\":\"1.0\"}"

4.4 删除镜像

bash
# 删除镜像
curl -X DELETE \
  --unix-socket /var/run/docker.sock \
  "http://localhost/v1.43/images/nginx:alpine"

# 强制删除
curl -X DELETE \
  --unix-socket /var/run/docker.sock \
  "http://localhost/v1.43/images/nginx:alpine?force=true"

# 删除不删除未标记的父镜像
curl -X DELETE \
  --unix-socket /var/run/docker.sock \
  "http://localhost/v1.43/images/nginx:alpine?noprune=true"

4.5 查看镜像详情

bash
# 查看镜像详情
curl --unix-socket /var/run/docker.sock \
  "http://localhost/v1.43/images/nginx:alpine/json"

# 查看镜像历史
curl --unix-socket /var/run/docker.sock \
  "http://localhost/v1.43/images/nginx:alpine/history"

网络 API

5.1 列出网络

bash
# 列出所有网络
curl --unix-socket /var/run/docker.sock \
  "http://localhost/v1.43/networks"

# 查看特定网络
curl --unix-socket /var/run/docker.sock \
  "http://localhost/v1.43/networks/bridge"

5.2 创建网络

bash
# 创建网络
curl -X POST \
  --unix-socket /var/run/docker.sock \
  -H "Content-Type: application/json" \
  -d '{
    "Name": "my-network",
    "Driver": "bridge",
    "IPAM": {
      "Config": [{
        "Subnet": "172.20.0.0/16",
        "Gateway": "172.20.0.1"
      }]
    },
    "Labels": {
      "environment": "production"
    }
  }' \
  "http://localhost/v1.43/networks/create"

5.3 连接/断开容器

bash
# 连接容器到网络
curl -X POST \
  --unix-socket /var/run/docker.sock \
  -H "Content-Type: application/json" \
  -d '{
    "Container": "my-nginx",
    "EndpointConfig": {
      "IPAMConfig": {
        "IPv4Address": "172.20.0.10"
      }
    }
  }' \
  "http://localhost/v1.43/networks/my-network/connect"

# 断开容器
curl -X POST \
  --unix-socket /var/run/docker.sock \
  -H "Content-Type: application/json" \
  -d '{
    "Container": "my-nginx",
    "Force": false
  }' \
  "http://localhost/v1.43/networks/my-network/disconnect"

5.4 删除网络

bash
# 删除网络
curl -X DELETE \
  --unix-socket /var/run/docker.sock \
  "http://localhost/v1.43/networks/my-network"

卷 API

6.1 列出卷

bash
# 列出所有卷
curl --unix-socket /var/run/docker.sock \
  "http://localhost/v1.43/volumes"

# 带过滤条件
curl --unix-socket /var/run/docker.sock \
  "http://localhost/v1.43/volumes?filters={\"dangling\":[\"true\"]}"

6.2 创建卷

bash
# 创建卷
curl -X POST \
  --unix-socket /var/run/docker.sock \
  -H "Content-Type: application/json" \
  -d '{
    "Name": "my-volume",
    "Driver": "local",
    "DriverOpts": {
      "type": "nfs",
      "o": "addr=192.168.1.100,rw",
      "device": ":/path/to/export"
    },
    "Labels": {
      "environment": "production"
    }
  }' \
  "http://localhost/v1.43/volumes/create"

6.3 查看和删除卷

bash
# 查看卷详情
curl --unix-socket /var/run/docker.sock \
  "http://localhost/v1.43/volumes/my-volume"

# 删除卷
curl -X DELETE \
  --unix-socket /var/run/docker.sock \
  "http://localhost/v1.43/volumes/my-volume"

# 清理未使用卷
curl -X POST \
  --unix-socket /var/run/docker.sock \
  "http://localhost/v1.43/volumes/prune"

系统 API

7.1 系统信息

bash
# 获取系统信息
curl --unix-socket /var/run/docker.sock \
  "http://localhost/v1.43/info"

# 获取版本信息
curl --unix-socket /var/run/docker.sock \
  "http://localhost/v1.43/version"

# 获取磁盘使用
curl --unix-socket /var/run/docker.sock \
  "http://localhost/v1.43/system/df"

7.2 事件监听

bash
# 监听事件(流式)
curl --unix-socket /var/run/docker.sock \
  "http://localhost/v1.43/events"

# 带过滤条件
curl --unix-socket /var/run/docker.sock \
  "http://localhost/v1.43/events?filters={\"type\":[\"container\"],\"event\":[\"start\",\"stop\"]}"

# 时间范围
curl --unix-socket /var/run/docker.sock \
  "http://localhost/v1.43/events?since=1699999999&until=1700000000"

7.3 数据清理

bash
# 清理容器
curl -X POST \
  --unix-socket /var/run/docker.sock \
  "http://localhost/v1.43/containers/prune"

# 清理镜像
curl -X POST \
  --unix-socket /var/run/docker.sock \
  "http://localhost/v1.43/images/prune"

# 清理网络
curl -X POST \
  --unix-socket /var/run/docker.sock \
  "http://localhost/v1.43/networks/prune"

# 清理卷
curl -X POST \
  --unix-socket /var/run/docker.sock \
  "http://localhost/v1.43/volumes/prune"

# 系统清理
curl -X POST \
  --unix-socket /var/run/docker.sock \
  -H "Content-Type: application/json" \
  -d '{
    "Containers": true,
    "Images": true,
    "Networks": true,
    "Volumes": true
  }' \
  "http://localhost/v1.43/system/prune"

SDK 使用

8.1 Python SDK

python
import docker

# 连接到 Docker
client = docker.from_env()
# 或
client = docker.DockerClient(base_url='unix://var/run/docker.sock')

# 列出容器
containers = client.containers.list()
for container in containers:
    print(f"{container.name}: {container.status}")

# 运行容器
container = client.containers.run(
    "nginx:alpine",
    detach=True,
    name="web",
    ports={'80/tcp': 8080},
    environment={'NGINX_HOST': 'localhost'},
    labels={'app': 'web'}
)

# 获取容器
container = client.containers.get('web')

# 停止和删除
container.stop()
container.remove()

# 镜像操作
images = client.images.list()
client.images.pull('nginx:alpine')
client.images.remove('nginx:alpine')

# 构建镜像
image, build_logs = client.images.build(
    path='.',
    dockerfile='Dockerfile',
    tag='myapp:v1.0',
    buildargs={'VERSION': '1.0'}
)

# 网络操作
network = client.networks.create(
    'my-network',
    driver='bridge',
    ipam=docker.types.IPAMConfig(
        pool_configs=[docker.types.IPAMPool(
            subnet='172.20.0.0/16',
            gateway='172.20.0.1'
        )]
    )
)

# 卷操作
volume = client.volumes.create(
    'my-volume',
    driver='local',
    labels={'environment': 'production'}
)

8.2 Go SDK

go
package main

import (
    "context"
    "fmt"
    "github.com/docker/docker/api/types"
    "github.com/docker/docker/api/types/container"
    "github.com/docker/docker/client"
    "github.com/docker/go-connections/nat"
)

func main() {
    ctx := context.Background()
    
    // 创建客户端
    cli, err := client.NewClientWithOpts(
        client.FromEnv,
        client.WithAPIVersionNegotiation(),
    )
    if err != nil {
        panic(err)
    }
    
    // 列出容器
    containers, err := cli.ContainerList(ctx, types.ContainerListOptions{})
    if err != nil {
        panic(err)
    }
    
    for _, container := range containers {
        fmt.Printf("%s %s\n", container.ID[:12], container.Image)
    }
    
    // 创建容器
    resp, err := cli.ContainerCreate(ctx,
        &container.Config{
            Image: "nginx:alpine",
            Env:   []string{"NGINX_HOST=localhost"},
            Labels: map[string]string{
                "app": "web",
            },
        },
        &container.HostConfig{
            PortBindings: nat.PortMap{
                "80/tcp": []nat.PortBinding{
                    {HostIP: "0.0.0.0", HostPort: "8080"},
                },
            },
        },
        nil,
        nil,
        "my-nginx",
    )
    if err != nil {
        panic(err)
    }
    
    // 启动容器
    if err := cli.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{}); err != nil {
        panic(err)
    }
    
    fmt.Printf("Container %s started\n", resp.ID)
}

8.3 Node.js SDK

javascript
const Docker = require('dockerode');
const docker = new Docker();

// 列出容器
async function listContainers() {
    const containers = await docker.listContainers();
    containers.forEach(container => {
        console.log(`${container.Names[0]}: ${container.State}`);
    });
}

// 运行容器
async function runContainer() {
    const container = await docker.createContainer({
        Image: 'nginx:alpine',
        name: 'web',
        Env: ['NGINX_HOST=localhost'],
        Labels: { app: 'web' },
        HostConfig: {
            PortBindings: {
                '80/tcp': [{ HostPort: '8080' }]
            }
        }
    });
    
    await container.start();
    console.log(`Container ${container.id} started`);
}

// 构建镜像
async function buildImage() {
    const stream = await docker.buildImage({
        context: __dirname,
        src: ['Dockerfile', 'package.json', 'app.js']
    }, { t: 'myapp:v1.0' });
    
    return new Promise((resolve, reject) => {
        docker.modem.followProgress(stream, (err, res) => 
            err ? reject(err) : resolve(res)
        );
    });
}

listContainers();

下一步

基于 MIT 许可发布