go操作docker

weixin_34253539發表於2017-05-26

[TOC]

通過docker sdk api操作docker

以下為使用go語言的sdk,官網及原始碼裡面的測試用例都沒有一個完整的建立容器的例子(帶埠對映等),真TM爛,只好自己整理出來。

其中也遇到些坑,最坑的是在使用埠對映時報的型別問題,見最後

Container

其中除了建立有點複雜,其它操作都比較簡單。

建立Container

其主要複雜在埠的對映上面。如果hostConfig裡面的PortBindings對應的PortMap中相應埠對應的PortBinding,其值有幾個(空值也算)就會對外對映幾個埠。

程式碼如:

func createContainer(cli *client.Client) string {
    exports := make(nat.PortSet, 10)
    port, err := nat.NewPort("tcp", "80")
    log(err)
    exports[port] = struct{}{}
    config := &container.Config{Image: "nginx", ExposedPorts: exports}

    portBind := nat.PortBinding{HostPort: "80"}
    portMap := make(nat.PortMap, 0)
    tmp := make([]nat.PortBinding, 0, 1)
    tmp = append(tmp, portBind)
    portMap[port] = tmp
    hostConfig := &container.HostConfig{PortBindings: portMap}
    // networkingConfig := &network.NetworkingConfig{}
    containerName := "hel"
    body, err := cli.ContainerCreate(context.Background(), config, hostConfig, nil, containerName)
    log(err)
    fmt.Printf("ID: %s\n", body.ID)
    return body.ID
}

其中啟動、停止、刪除都比較簡單,不再一步一步說明。完整程式碼如下:

package main

import (
    "context"
    "fmt"
    "time"

    "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() {
    cli, err := client.NewClient("tcp://192.168.100.33:2376", "v1.12", nil, nil)
    defer cli.Close()
    log(err)
    listImage(cli)
    id := createContainer(cli)
    fmt.Printf("%s\n", id)
    time.Sleep(time.Second * 1)
    startContainer(id, cli)
    time.Sleep(time.Second * 40)
    stopContainer(id, cli)
    time.Sleep(time.Second * 3)
    id, err = removeContainer(id, cli)
    if err == nil {
        fmt.Println("刪除容器", id, "成功")
    }
}
// 列出映象
func listImage(cli *client.Client) {
    images, err := cli.ImageList(context.Background(), types.ImageListOptions{})
    log(err)

    for _, image := range images {
        fmt.Println(image)
    }
}
// 建立容器
func createContainer(cli *client.Client) string {
    exports := make(nat.PortSet, 10)
    port, err := nat.NewPort("tcp", "80")
    log(err)
    exports[port] = struct{}{}
    config := &container.Config{Image: "nginx", ExposedPorts: exports}

    portBind := nat.PortBinding{HostPort: "80"}
    portMap := make(nat.PortMap, 0)
    tmp := make([]nat.PortBinding, 0, 1)
    tmp = append(tmp, portBind)
    portMap[port] = tmp
    hostConfig := &container.HostConfig{PortBindings: portMap}
    
    containerName := "hel"
    body, err := cli.ContainerCreate(context.Background(), config, hostConfig, nil, containerName)
    log(err)
    fmt.Printf("ID: %s\n", body.ID)
    return body.ID
}
// 啟動
func startContainer(containerID string, cli *client.Client) {
    err := cli.ContainerStart(context.Background(), containerID, types.ContainerStartOptions{})
    log(err)
    if err == nil {
        fmt.Println("容器", containerID, "啟動成功")
    }
}
// 停止
func stopContainer(containerID string, cli *client.Client) {
    timeout := time.Second * 10
    err := cli.ContainerStop(context.Background(), containerID, &timeout)
    if err != nil {
        log(err)
    } else {
        fmt.Printf("容器%s已經被停止\n", containerID)
    }
}
// 刪除
func removeContainer(containerID string, cli *client.Client) (string, error) {
    err := cli.ContainerRemove(context.Background(), containerID, types.ContainerRemoveOptions{})
    log(err)
    return containerID, err
}

func log(err error) {
    if err != nil {
        fmt.Printf("%v\n", err)
        panic(err)
    }
}

埠對映問題

在使用docker go sdk的時候,進行容器建立,如果指定了對映的埠,會報以下錯誤:

cannot use ports (type map["bitbucket.org/myorg/myproject/vendor/github.com/docker/go-connect
ions/nat".Port]struct {}) as type "github.com/docker/docker/vendor/github.com/docker/go-connections/nat".PortSet in field
 value

其解決方法:把gopath裡面pkg下面docker的vendor裡面相應的connections包刪除即可。src下的最好也刪除。如果編譯報缺少包,則把其相應的包get下來即可。

相關文章