A’ riaghladh shoithichean Docker ann an Go

Sgrìobhainnean!

Nuair a cho-dhùnas tu do bhaidhc fhèin a sgrìobhadh airson dubhan a ghlacadh bhon ionad docker no bhon chlàr gus soithichean ùrachadh / ruith air an fhrithealaiche gu fèin-ghluasadach, is dòcha gum bi an Docker Cli feumail dhut, a chuidicheas le bhith a’ riaghladh deamhan an Docker air an t-siostam agad.
A’ riaghladh shoithichean Docker ann an Go

Gus obrachadh feumaidh tu tionndadh Go nach eil nas ìsle na 1.9.4

Mura h-eil thu fhathast air atharrachadh gu modalan, stàlaich Cli leis an àithne a leanas:

go get github.com/docker/docker/client

A 'ruith container

Tha an eisimpleir a leanas a’ sealltainn mar a ruitheas tu soitheach a’ cleachdadh an Docker API. Air an loidhne-àithne cleachdaidh tu an àithne docker run, ach is urrainn dhuinn gu furasta dèiligeadh ris an obair seo nar seirbheis.
Tha an eisimpleir seo co-ionann ri ruith an àithne docker run alpine echo hello world

package main {
    ctx := context.Background()
    cli, err := client.NewEnvClient()
    if err != nil {
        panic(err)
    }

    // Делаем docker pull
    reader, err := cli.ImagePull(ctx, "docker.io/library/alpine", types.ImagePullOptions{})
    if err != nil {
        panic(err)
    }
    io.Copy(os.Stdout, reader)

    hostBinding := nat.PortBinding{
        HostIP:   "0.0.0.0",
        HostPort: "8000",
    }
    containerPort, err := nat.NewPort("tcp", "80")
    if err != nil {
        panic("Unable to get the port")
    }
    portBinding := nat.PortMap{containerPort: []nat.PortBinding{hostBinding}}

    // Создаем контейнер с заданной конфигурацией
    resp, err := cli.ContainerCreate(ctx, &container.Config{
        Image: "alpine",
        Cmd:   []string{"echo", "hello world"},
        Tty:   true,
    }, &container.HostConfig{
        PortBindings: portBinding,
    }, nil, "")
    if err != nil {
        panic(err)
    }

    // Запускаем контейнер
    if err := cli.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{}); 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)
}

Faigh liosta de shoithichean ruith

Tha an eisimpleir seo co-ionann ri ruith an àithne docker ps

package main

import (
    "context"
    "fmt"

    "github.com/docker/docker/api/types"
    "github.com/docker/docker/client"
)

func main() {
    cli, err := client.NewEnvClient()
    if err != nil {
        panic(err)
    }

    // Получение списка запуцщенных контейнеров(docker ps)
    containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{})
    if err != nil {
        panic(err)
    }

    // Вывод всех идентификаторов контейнеров
    for _, container := range containers {
        fmt.Println(container.ID)
    }
}

Cuir stad air a h-uile soitheach ruith

Aon uair ‘s gu bheil thu air ionnsachadh mar a chruthaicheas agus a ruitheas tu soithichean, tha an t-àm ann ionnsachadh mar a stiùireas tu iad. Cuiridh an eisimpleir a leanas stad air a h-uile soitheach ruith.

Na ruith an còd seo air frithealaiche riochdachaidh!

package main

import (
    "context"
    "fmt"

    "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)
    }

    // Получение списка запуцщенных контейнеров(docker ps)
    containers, err := cli.ContainerList(ctx, types.ContainerListOptions{})
    if err != nil {
        panic(err)
    }

    for _, c := range containers {
        fmt.Print("Stopping container ", c.ID[:10], "... ")
        if err := cli.ContainerStop(ctx, c.ID, nil); err != nil {
            panic(err)
        }
        fmt.Println("Success")
    }
}

Taisbeanadh logaichean airson aon container

Faodaidh tu obrachadh le soithichean fa leth. Tha an eisimpleir a leanas a’ taisbeanadh logaichean container leis an aithnichear ainmichte. Mus tòisich thu, feumaidh tu ID an t-soithich aig a bheil na logaichean a tha thu airson fhaighinn atharrachadh.

package main

import (
    "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}
    // Измените id контейнера здесь
    out, err := cli.ContainerLogs(ctx, "f1064a8a4c82", options)
    if err != nil {
        panic(err)
    }
    io.Copy(os.Stdout, out)
}

A 'faighinn liosta de dhealbhan

Tha an eisimpleir seo co-ionann ri ruith an àithne docker image ls

package main

import (
    "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)
    }
}

Pull

Tha an eisimpleir seo co-ionann ri ruith an àithne docker pull

package main

import (
    "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)
    }

    // docker pull alpine
    out, err := cli.ImagePull(ctx, "docker.io/library/alpine", types.ImagePullOptions{})
    if err != nil {
        panic(err)
    }
    defer out.Close()
    io.Copy(os.Stdout, out)
}

Luchdaich a-nuas an dealbh leis an neach-cleachdaidh dearbhadh

Tha an eisimpleir seo co-ionann ri ruith an àithne docker pull, le dearbhadh.

Thèid dàta dearbhaidh a chuir ann an teacsa soilleir. Bidh an clàr oifigeil docker a’ cleachdadh HTTPS,
feumaidh clàran prìobhaideach a bhith air an rèiteachadh cuideachd gus dàta a ghluasad a’ cleachdadh HTTPS.

package main

import (
    "context"
    "encoding/base64"
    "encoding/json"
    "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)
    }

    // Создание конфига с данными для аутентификации
    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, "docker.io/library/alpine", types.ImagePullOptions{RegistryAuth: authStr})
    if err != nil {
        panic(err)
    }

    defer out.Close()
    io.Copy(os.Stdout, out)
}

Source: www.habr.com

Cuir beachd ann