Skip to content

DockerAPI ​

Before You Start

  • Applies to: Go 1.21+ (examples verified with Go 1.22) · Prerequisites: Std: net · Read time: about 15 min

文档:Develop with Docker Engine SDKs | Docker Documentation

DockerAPI是Docker的SDK,以编程的方式与Docker进行交互,例如拉取镜像,运行容器,这个文档只是简单的讲解如何去使用DockerAPI,在官方文档中对每一个API有着更详细的解释。官方API只有Go和Python版本,并且Docker本身也支持HTTP进行交互,如果是其他语言的话可以使用第三方社区开源的SDK,本教程将采用Go语言进行讲解。

安装 ​

使用Go Get 安装Docker Client。

go get github.com/docker/docker/client

Complete Example ​

The program below runs as-is: copy it into a file and execute go run main.go, or paste it into the Go Playground.

go
package main

import (
	"fmt"
	"net/url"
)

func main() {
	// Docker Engine API requests are versioned paths plus query filters
	filters := url.Values{}
	filters.Set("status", "running")

	path := "/v1.43/containers/json"
	escaped := url.QueryEscape(`{"status":["running"]}`)
	fmt.Println("request:", path+"?filters="+escaped)
	fmt.Println("simple filters:", filters.Encode())
}

Expected output:

text
request: /v1.43/containers/json?filters=%7B%22status%22%3A%5B%22running%22%5D%7D
simple filters: status=running

Common Pitfalls ​

  • Negotiate the API version. Call client.NegotiateAPIVersion (or pass a version) instead of hard-coding one that the daemon may not support.
  • Honour the environment. DOCKER_HOST, TLS settings and contexts should come from client.FromEnv.
  • Always pass a context with a timeout. Container operations can hang when the daemon is busy.
  • Handle typed errors. Use the client's helpers (errdefs/IsErrNotFound) instead of matching error strings.
  • Do not build URLs by hand in production. The official client methods handle versioning, encoding and streaming.

Change Log ​

  • 2026-10-14: Added "Before You Start" notes, a complete runnable example with expected output, common pitfalls, and this change log.

Golang by www.golangdev.cn · Adapted in part from Golang 中文学习文档 (MIT, © 寒江蓑笠翁)