?
This document uses PHP Chinese website manual Release
在安裝 Docker 之后,您可以嘗試 Docker API。
或者,為您正在使用的語言安裝 SDK。官方 SDK 可用于 Python 和 Go,以及一些社區(qū)維護(hù)的其他語言庫。
了解有關(guān)安裝和使用 Docker SDK的更多信息。
這些例子展示了如何使用 Python,Go或curl
直接使用來執(zhí)行相同的操作。
這里使用的 Python 和 Go 示例沒有指定要使用的 API 版本,因為它們使用長期以來一直是 Docker 一部分的功能。Docker API完全向后兼容。
要查看 Docker 守護(hù)進(jìn)程和客戶端支持的API的最高版本,請使用docker version
:
$ docker version Client: Version: 17.04.0-ce API version: 1.28 Go version: go1.7.5 Git commit: 4845c56 Built: Wed Apr 5 06:06:36 2017 OS/Arch: darwin/amd64 Server: Version: 17.04.0-ce API version: 1.28 (minimum version 1.12) Go version: go1.7.5 Git commit: 4845c56 Built: Tue Apr 4 00:37:25 2017 OS/Arch: linux/amd64 Experimental: true
您可以通過以下方式之一指定要使用的 API 版本:
curl
直接使用時,請將版本指定為 URL 的第一部分。例如,如果端點是/containers/
,您可以使用/v1.27/containers/
。
對于 SDK,或強制 Docker CLI 使用特定版本的 API,請將環(huán)境變量DOCKER_API_VERSION
設(shè)置為正確的版本。這適用于 Linux,Windows 或 MacOS 客戶端。
DOCKER_API_VERSION = '1.27'
雖然環(huán)境變量已設(shè)置,但即使 Docker 守護(hù)程序支持較新版本,也會使用該版本的API。
對于 SDK,您還可以通過編程方式指定 API 版本作為client
對象的參數(shù)。請參閱Go的構(gòu)造函數(shù)或Python SDK文檔client
。API 示例運行容器第一個示例演示如何使用 Docker API 運行容器。在命令行上,您可以使用該docker run
命令,但這同樣適用于您自己的應(yīng)用程序。這與docker run alpine echo hello world
在命令提示符下鍵入相同:
Python
Go
Curl
import docker client = docker.from_env()print client.containers.run("alpine", ["echo", "hello", "world"])
package mainimport ( "io" "os" "github.com/docker/docker/client" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/container" "golang.org/x/net/context")func main() { ctx := context.Background() cli, err := client.NewEnvClient() if err != nil { panic(err) } _, err = cli.ImagePull(ctx, "docker.io/library/alpine", types.ImagePullOptions{}) if err != nil { panic(err) } resp, err := cli.ContainerCreate(ctx, &container.Config{ Image: "alpine", Cmd: []string{"echo", "hello world"}, }, nil, nil, "") if err != nil { panic(err) } if err := cli.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{}); err != nil { panic(err) } if _, err = cli.ContainerWait(ctx, resp.ID); err != nil { panic(err) } out, err := cli.ContainerLogs(ctx, resp.ID, types.ContainerLogsOptions{ShowStdout: true}) if err != nil { panic(err) } io.Copy(os.Stdout, out)}
$ curl --unix-socket /var/run/docker.sock -H "Content-Type: application/json" \ -d '{"Image": "alpine", "Cmd": ["echo", "hello world"]}' \ -X POST http:/v1.24/containers/create{"Id":"1c6594faf5","Warnings":null}$ curl --unix-socket /var/run/docker.sock -X POST http:/v1.24/containers/1c6594faf5/start $ curl --unix-socket /var/run/docker.sock -X POST http:/v1.24/containers/1c6594faf5/wait{"StatusCode":0}$ curl --unix-socket /var/run/docker.sock "http:/v1.24/containers/1c6594faf5/logs?stdout=1"hello world
你也可以在后臺運行容器,相當(dāng)于輸入docker run -d bfirsh/reticulate-splines
:
Python
Go
Curl
import docker client = docker.from_env()container = client.containers.run("bfirsh/reticulate-splines", detach=True)print container.id
package mainimport ( "fmt" "io" "os" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/container" "github.com/docker/docker/client" "golang.org/x/net/context")func main() { ctx := context.Background() cli, err := client.NewEnvClient() if err != nil { panic(err) } imageName := "bfirsh/reticulate-splines" out, err := cli.ImagePull(ctx, imageName, types.ImagePullOptions{}) if err != nil { panic(err) } io.Copy(os.Stdout, out) resp, err := cli.ContainerCreate(ctx, &container.Config{ Image: imageName, }, nil, nil, "") if err != nil { panic(err) } if err := cli.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{}); err != nil { panic(err) } fmt.Println(resp.ID)}
$ curl --unix-socket /var/run/docker.sock -H "Content-Type: application/json" \ -d '{"Image": "bfirsh/reticulate-splines"}' \ -X POST http:/v1.24/containers/create{"Id":"1c6594faf5","Warnings":null}$ curl --unix-socket /var/run/docker.sock -X POST http:/v1.24/containers/1c6594faf5/start
您可以使用 API 列出正在運行的容器,就像使用一樣docker ps
:
Python
Go
Curl
import docker client = docker.from_env()for container in client.containers.list(): print container.id
package mainimport ( "context" "fmt" "github.com/docker/docker/api/types" "github.com/docker/docker/client")func main() { cli, err := client.NewEnvClient() if err != nil { panic(err) } containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{}) if err != nil { panic(err) } for _, container := range containers { fmt.Println(container.ID) }}
$ curl --unix-socket /var/run/docker.sock http:/v1.24/containers/json[{ "Id":"ae63e8b89a26f01f6b4b2c9a7817c31a1b6196acf560f66586fbc8809ffcd772", "Names":["/tender_wing"], "Image":"bfirsh/reticulate-splines", ...}]
現(xiàn)在您知道存在哪些容器,您可以對它們執(zhí)行操作。例如,要停止所有正在運行的容器:
Python
Go
Curl
import docker client = docker.from_env()for container in client.containers.list(): container.stop()
package mainimport ( "context" "github.com/docker/docker/api/types" "github.com/docker/docker/client")func main() { ctx := context.Background() cli, err := client.NewEnvClient() if err != nil { panic(err) } containers, err := cli.ContainerList(ctx, types.ContainerListOptions{}) if err != nil { panic(err) } for _, container := range containers { if err := cli.ContainerStop(ctx, container.ID, nil); err != nil { panic(err) } }}
$ curl --unix-socket /var/run/docker.sock http:/v1.24/containers/json[{ "Id":"ae63e8b89a26f01f6b4b2c9a7817c31a1b6196acf560f66586fbc8809ffcd772", "Names":["/tender_wing"], "Image":"bfirsh/reticulate-splines", ...}]$ curl --unix-socket /var/run/docker.sock \ -X POST http:/v1.24/containers/ae63e8b89a26/stop
您也可以對單個容器執(zhí)行操作。這個例子打印給定 ID 的容器的日志:
Python
Go
Curl
import docker client = docker.from_env()container = client.containers.get('f1064a8a4c82')print container.logs()
package mainimport ( "context" "io" "os" "github.com/docker/docker/api/types" "github.com/docker/docker/client")func main() { ctx := context.Background() cli, err := client.NewEnvClient() if err != nil { panic(err) } options := types.ContainerLogsOptions{ShowStdout: true} out, err := cli.ContainerLogs(ctx, "f1064a8a4c82", options) if err != nil { panic(err) } io.Copy(os.Stdout, out)}
$ curl --unix-socket /var/run/docker.sock "http:/v1.24/containers/ca5f55cdb/logs?stdout=1"Reticulating spline 1...Reticulating spline 2...Reticulating spline 3...Reticulating spline 4...Reticulating spline 5...
列出引擎上的圖像,類似于docker images
:
Python
Go
Curl
import docker client = docker.from_env()for image in client.images.list(): print image.id
package mainimport ( "context" "fmt" "github.com/docker/docker/api/types" "github.com/docker/docker/client")func main() { cli, err := client.NewEnvClient() if err != nil { panic(err) } images, err := cli.ImageList(context.Background(), types.ImageListOptions{}) if err != nil { panic(err) } for _, image := range images { fmt.Println(image.ID) }}
$ curl --unix-socket /var/run/docker.sock http:/v1.24/images/json[{ "Id":"sha256:31d9a31e1dd803470c5a151b8919ef1988ac3efd44281ac59d43ad623f275dcd", "ParentId":"sha256:ee4603260daafe1a8c2f3b78fd760922918ab2441cbb2853ed5c439e59c52f96", ...}]
Pull images,像docker pull
:
Python
Go
Curl
import docker client = docker.from_env()image = client.images.pull("alpine")print image.id
package mainimport ( "io" "os" "github.com/docker/docker/api/types" "github.com/docker/docker/client" "golang.org/x/net/context")func main() { ctx := context.Background() cli, err := client.NewEnvClient() if err != nil { panic(err) } out, err := cli.ImagePull(ctx, "alpine", types.ImagePullOptions{}) if err != nil { panic(err) } defer out.Close() io.Copy(os.Stdout, out)}
$ curl --unix-socket /var/run/docker.sock \ -X POST "http:/v1.24/images/create?fromImage=alpine"{"status":"Pulling from library/alpine","id":"3.1"}{"status":"Pulling fs layer","progressDetail":{},"id":"8f13703509f7"}{"status":"Downloading","progressDetail":{"current":32768,"total":2244027},"progress":"[\u003e ] 32.77 kB/2.244 MB","id":"8f13703509f7"}...
docker pull
通過身份驗證提取圖片,例如:
注意:憑證以明文形式發(fā)送。Docker 官方注冊管理機構(gòu)使用 HTTPS。私人注冊管理機構(gòu)也應(yīng)配置為使用 HTTPS。
Python
Go
Curl
Python SDK 從憑證存儲文件中檢索認(rèn)證信息并與憑證助手集成。可以覆蓋這些憑據(jù),但這不在本入門指南的范圍之內(nèi)。使用后docker login
,Python SDK會自動使用這些憑據(jù)。
import docker client = docker.from_env()image = client.images.pull("alpine")print image.id
package mainimport ( "io" "os" "encoding/json" "encoding/base64" "github.com/docker/docker/api/types" "github.com/docker/docker/client" "golang.org/x/net/context")func main() { ctx := context.Background() cli, err := client.NewEnvClient() if err != nil { panic(err) } authConfig := types.AuthConfig{ Username: "username", Password: "password", } encodedJSON, err := json.Marshal(authConfig) if err != nil { panic(err) } authStr := base64.URLEncoding.EncodeToString(encodedJSON) out, err := cli.ImagePull(ctx, "alpine", types.ImagePullOptions{RegistryAuth: authStr}) if err != nil { panic(err) } defer out.Close() io.Copy(os.Stdout, out)}
這個例子會將證書留在你 shell 的歷史記錄中,所以認(rèn)為這是一個天真的實現(xiàn)。憑證以 Base-64 編碼的 JSON結(jié)構(gòu)形式傳遞。
$ JSON=$(echo '{"username": "string", "password": "string", "serveraddress": "string"}' | base64)$ curl --unix-socket /var/run/docker.sock \ -H "Content-Type: application/tar" -X POST "http:/v1.24/images/create?fromImage=alpine" -H "X-Registry-Auth" -d "$JSON"{"status":"Pulling from library/alpine","id":"3.1"}{"status":"Pulling fs layer","progressDetail":{},"id":"8f13703509f7"}{"status":"Downloading","progressDetail":{"current":32768,"total":2244027},"progress":"[\u003e ] 32.77 kB/2.244 MB","id":"8f13703509f7"}...
提交容器以從其內(nèi)容創(chuàng)建圖像:
Python
Go
Curl
import docker client = docker.from_env()container = client.containers.run("alpine", ["touch", "/helloworld"], detach=True)container.wait()image = container.commit("helloworld")print image.id
package mainimport ( "fmt" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/container" "github.com/docker/docker/client" "golang.org/x/net/context")func main() { ctx := context.Background() cli, err := client.NewEnvClient() if err != nil { panic(err) } createResp, err := cli.ContainerCreate(ctx, &container.Config{ Image: "alpine", Cmd: []string{"touch", "/helloworld"}, }, nil, nil, "") if err != nil { panic(err) } if err := cli.ContainerStart(ctx, createResp.ID, types.ContainerStartOptions{}); err != nil { panic(err) } if _, err = cli.ContainerWait(ctx, createResp.ID); err != nil { panic(err) } commitResp, err := cli.ContainerCommit(ctx, createResp.ID, types.ContainerCommitOptions{Reference: "helloworld"}) if err != nil { panic(err) } fmt.Println(commitResp.ID)}
$ docker run -d alpine touch /helloworld 0888269a9d584f0fa8fc96b3c0d8d57969ceea3a64acf47cd34eebb4744dbc52 $ curl --unix-socket /var/run/docker.sock\ -X POST "http:/v1.24/commit?container=0888269a9d&repo=helloworld"{"Id":"sha256:6c86a5cd4b87f2771648ce619e319f3e508394b5bfc2cdbd2d60f59d52acda6c"}
Python SDK的完整文檔
Go SDK的完整文檔
HTTPAPI的完整文檔