最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用Golang玩轉(zhuǎn)Docker API的實(shí)踐

 更新時(shí)間:2021年04月06日 11:26:14   作者:K8sCat  
這篇文章主要介紹了使用Golang玩轉(zhuǎn)Docker API的實(shí)踐,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

Docker 提供了一個(gè)與 Docker 守護(hù)進(jìn)程交互的 API (稱為Docker Engine API),我們可以使用官方提供的 Go 語言的 SDK 進(jìn)行構(gòu)建和擴(kuò)展 Docker 應(yīng)用程序和解決方案。

安裝 SDK

通過下面的命令就可以安裝 SDK 了:

go get github.com/docker/docker/client

管理本地的 Docker

該部分會(huì)介紹如何使用 Golang + Docker API 進(jìn)行管理本地的 Docker。

運(yùn)行容器

第一個(gè)例子將展示如何運(yùn)行容器,相當(dāng)于 docker run docker.io/library/alpine echo "hello world":

package main

import (
 "context"
 "io"
 "os"

 "github.com/docker/docker/api/types"
 "github.com/docker/docker/api/types/container"
 "github.com/docker/docker/client"
 "github.com/docker/docker/pkg/stdcopy"
)

func main() {
 ctx := context.Background()
 cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
 if err != nil {
 panic(err)
 }

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

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

 statusCh, errCh := cli.ContainerWait(ctx, resp.ID, container.WaitConditionNotRunning)
 select {
 case err := <-errCh:
 if err != nil {
  panic(err)
 }
 case <-statusCh:
 }

 out, err := cli.ContainerLogs(ctx, resp.ID, types.ContainerLogsOptions{ShowStdout: true})
 if err != nil {
 panic(err)
 }

 stdcopy.StdCopy(os.Stdout, os.Stderr, out)
}

后臺(tái)運(yùn)行容器

還可以在后臺(tái)運(yùn)行容器,相當(dāng)于 docker run -d bfirsh/reticulate-splines:

package main

import (
 "context"
 "fmt"
 "io"
 "os"

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

func main() {
 ctx := context.Background()
 cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
 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)
}

查看容器列表

列出正在運(yùn)行的容器,就像使用 docker ps 一樣:

package main

import (
 "context"
 "fmt"

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

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.Println(container.ID)
 }
}

如果是 docker ps -a,我們可以通過修改 types.ContainerListOptions 中的 All 屬性達(dá)到這個(gè)目的:

// type ContainerListOptions struct {
// Quiet bool
// Size bool
// All  bool
// Latest bool
// Since string
// Before string
// Limit int
// Filters filters.Args
// }

options := types.ContainerListOptions{
 All: true,
}
containers, err := cli.ContainerList(ctx, options)
if err != nil {
 panic(err)
}

停止所有運(yùn)行中的容器

通過上面的例子,我們可以獲取容器的列表,所以在這個(gè)案例中,我們可以去停止所有正在運(yùn)行的容器。

注意:不要在生產(chǎn)服務(wù)器上運(yùn)行下面的代碼。

package main

import (
 "context"
 "fmt"

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

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.Print("Stopping container ", container.ID[:10], "... ")
  if err := cli.ContainerStop(ctx, container.ID, nil); err != nil {
   panic(err)
  }
  fmt.Println("Success")
 }
}

獲取指定容器的日志

通過指定容器的 ID,我們可以獲取對(duì)應(yīng) ID 的容器的日志:

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.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
 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)
}

查看鏡像列表

獲取本地所有的鏡像,相當(dāng)于 docker image ls 或 docker images:

package main

import (
 "context"
 "fmt"

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

func main() {
 ctx := context.Background()
 cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
 if err != nil {
  panic(err)
 }

 images, err := cli.ImageList(ctx, types.ImageListOptions{})
 if err != nil {
  panic(err)
 }

 for _, image := range images {
  fmt.Println(image.ID)
 }
}

拉取鏡像

拉取指定鏡像,相當(dāng)于 docker pull alpine:

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.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
 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)
}

拉取私有鏡像

除了公開的鏡像,我們平時(shí)還會(huì)用到一些私有鏡像,可以是 DockerHub 上私有鏡像,也可以是自托管的鏡像倉庫,比如 harbor。這個(gè)時(shí)候,我們需要提供對(duì)應(yīng)的憑證才可以拉取鏡像。

值得注意的是:在使用 Docker API 的 Go SDK 時(shí),憑證是以明文的方式進(jìn)行傳輸?shù)模匀绻亲越ǖ溺R像倉庫,請(qǐng)務(wù)必使用 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.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
 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)
}

保存容器成鏡像

我們可以將一個(gè)已有的容器通過 commit 保存成一個(gè)鏡像:

package main

import (
 "context"
 "fmt"

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

func main() {
 ctx := context.Background()
 cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
 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)
 }

 statusCh, errCh := cli.ContainerWait(ctx, createResp.ID, container.WaitConditionNotRunning)
 select {
 case err := <-errCh:
  if err != nil {
   panic(err)
  }
 case <-statusCh:
 }

 commitResp, err := cli.ContainerCommit(ctx, createResp.ID, types.ContainerCommitOptions{Reference: "helloworld"})
 if err != nil {
  panic(err)
 }

 fmt.Println(commitResp.ID)
}

管理遠(yuǎn)程的 Docker

當(dāng)然,除了可以管理本地的 Docker, 我們同樣也可以通過使用 Golang + Docker API 管理遠(yuǎn)程的 Docker。

遠(yuǎn)程連接

默認(rèn) Docker 是通過非網(wǎng)絡(luò)的 Unix 套接字運(yùn)行的,只能夠進(jìn)行本地通信(/var/run/docker.sock),是不能夠直接遠(yuǎn)程連接 Docker 的。
我們需要編輯配置文件 /etc/docker/daemon.json,并修改以下內(nèi)容(把 192.168.59.3 改成你自己的 IP 地址),然后重啟 Docker:

# vi /etc/docker/daemon.json
{
 "hosts": [
 "tcp://192.168.59.3:2375",
 "unix:///var/run/docker.sock"
 ]
}

systemctl restart docker

修改 client

創(chuàng)建 client 的時(shí)候需要指定遠(yuǎn)程 Docker 的地址,這樣就可以像管理本地 Docker 一樣管理遠(yuǎn)程的 Docker 了:

cli, err = client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation(),
 client.WithHost("tcp://192.168.59.3:2375"))

總結(jié)

現(xiàn)在已經(jīng)有很多可以管理 Docker 的產(chǎn)品,它們便是這樣進(jìn)行實(shí)現(xiàn)的,比如:portainer。

到此這篇關(guān)于使用Golang玩轉(zhuǎn)Docker API的實(shí)踐的文章就介紹到這了,更多相關(guān)Golang運(yùn)行Docker API內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 解決docker pull鏡像報(bào)錯(cuò)的問題

    解決docker pull鏡像報(bào)錯(cuò)的問題

    這篇文章主要介紹了解決docker pull鏡像報(bào)錯(cuò)的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2021-03-03
  • docker 啟動(dòng)具有多個(gè)網(wǎng)絡(luò)接口的容器的方法示例

    docker 啟動(dòng)具有多個(gè)網(wǎng)絡(luò)接口的容器的方法示例

    這篇文章主要介紹了docker 啟動(dòng)具有多個(gè)網(wǎng)絡(luò)接口的容器的方法示例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2018-10-10
  • Docker宿主機(jī)與容器之間的文件拷貝實(shí)例詳解

    Docker宿主機(jī)與容器之間的文件拷貝實(shí)例詳解

    現(xiàn)在公司用docker,有時(shí)候需要從容器中拷貝文件出來,下面這篇文章主要給大家介紹了關(guān)于Docker宿主機(jī)與容器之間的文件拷貝的相關(guān)資料,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下
    2023-06-06
  • docker搭建Hadoop?CDH高可用集群實(shí)現(xiàn)

    docker搭建Hadoop?CDH高可用集群實(shí)現(xiàn)

    本文主要介紹了docker搭建Hadoop?CDH高可用集群實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-07-07
  • 詳解Docker掛載本地目錄及實(shí)現(xiàn)文件共享的方法

    詳解Docker掛載本地目錄及實(shí)現(xiàn)文件共享的方法

    本篇文章主要介紹了詳解Docker掛載本地目錄及實(shí)現(xiàn)文件共享的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-12-12
  • docker指令收集整理(收藏)

    docker指令收集整理(收藏)

    Docker 是一個(gè)基于Linux容器(LXC-linux container)的高級(jí)容器引擎,基于go語言開發(fā),源代碼托管在 Github 上, 遵從Apache2.0協(xié)議開源。這篇文章主要介紹了docker指令收集整理(收藏),需要的朋友可以參考下
    2017-02-02
  • 使用Docker安裝detectron2的配置方法

    使用Docker安裝detectron2的配置方法

    Detectron2 是一個(gè)用于目標(biāo)檢測(cè)、分割和其他視覺識(shí)別任務(wù)的平臺(tái),下面采用 docker 方式在 windows 上安裝,對(duì)Docker安裝detectron2的配置方法感興趣的朋友一起看看吧
    2024-03-03
  • docker鏡像的拉取登陸上傳及保存等相關(guān)使用命令

    docker鏡像的拉取登陸上傳及保存等相關(guān)使用命令

    這篇文章主要為大家介紹了docker鏡像的拉取登陸上傳及保存等相關(guān)使用命令,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步早日升職加薪
    2022-04-04
  • SQL?Server?簡(jiǎn)介與?Docker?Compose?部署SQL?Server?容器

    SQL?Server?簡(jiǎn)介與?Docker?Compose?部署SQL?Server?容器

    SQL?Server?是一個(gè)功能強(qiáng)大的關(guān)系型數(shù)據(jù)庫管理系統(tǒng),適用于各種規(guī)模的應(yīng)用程序和數(shù)據(jù)存儲(chǔ)需求,在本文中,我將簡(jiǎn)要介紹?SQL?Server?的基本概念,并詳細(xì)闡述如何使用?Docker?Compose?部署?SQL?Server?容器,感興趣的朋友跟隨小編一起看看吧
    2023-10-10
  • 使用Dockerfile構(gòu)建docker鏡像

    使用Dockerfile構(gòu)建docker鏡像

    這篇文章主要介紹了使用Dockerfile構(gòu)建docker鏡像的方法,幫助大家更好的理解和學(xué)習(xí)使用docker,感興趣的朋友可以了解下
    2021-04-04

最新評(píng)論

梁平县| 五常市| 新平| 平邑县| 景东| 东阳市| 湘阴县| 潜山县| 蒲江县| 册亨县| 泸溪县| 南宁市| 新巴尔虎左旗| 荥阳市| 临湘市| 黑水县| 象州县| 大英县| 油尖旺区| 漳浦县| 县级市| 云梦县| 台东市| 安化县| 公主岭市| 克东县| 昭苏县| 旺苍县| 马鞍山市| 灵丘县| 六盘水市| 兖州市| 兰坪| 嘉禾县| 塘沽区| 保山市| 慈溪市| 江孜县| 将乐县| 元阳县| 锡林浩特市|