Docker API用于自动化拉取和运行。

huangapple go评论74阅读模式
英文:

Docker API to automate pull and run

问题

我建议你使用Go语言的Docker客户端库来实现在Go程序流程中运行Docker命令。你可以使用官方提供的Docker客户端库,它提供了与Docker API进行交互的功能。你可以使用该库来拉取镜像、创建容器、执行命令等操作。

以下是一个简单的示例代码,演示了如何使用Docker客户端库在Go程序中运行Docker命令:

package main

import (
	"context"
	"fmt"
	"github.com/docker/docker/api/types"
	"github.com/docker/docker/client"
)

func main() {
	// 创建Docker客户端
	cli, err := client.NewClientWithOpts(client.FromEnv)
	if err != nil {
		panic(err)
	}

	// 拉取镜像
	imageName := "namespace/myimage"
	pullOptions := types.ImagePullOptions{}
	responseBody, err := cli.ImagePull(context.Background(), imageName, pullOptions)
	if err != nil {
		panic(err)
	}
	defer responseBody.Close()

	// 运行容器
	containerConfig := &types.ContainerCreateConfig{
		Image: imageName,
	}
	resp, err := cli.ContainerCreate(context.Background(), containerConfig, nil, nil, "")
	if err != nil {
		panic(err)
	}

	// 启动容器
	err = cli.ContainerStart(context.Background(), resp.ID, types.ContainerStartOptions{})
	if err != nil {
		panic(err)
	}

	fmt.Println("Docker命令已成功执行!")
}

在上面的示例中,我们使用了github.com/docker/docker/client包来创建Docker客户端,并使用ImagePull方法拉取了指定的镜像。然后,我们使用ContainerCreate方法创建了一个容器,并使用ContainerStart方法启动了该容器。

你可以根据自己的需求修改上述代码,并根据需要添加更多的Docker操作。希望对你有帮助!

英文:

I want to integrate my Go code with Docker which is also in Go. I want to do something like:

myapp.Run()
IMG := dockerapi.Pull("namespace/my image")
IMG.Run()

What do you recommend if I want to run docker commands in the middle of my Go program program flow.

Thanks!

答案1

得分: 0

Docker提供了一个基于REST的API,用于以编程方式与其进行交互:

示例请求:

POST /images/create?fromImage=base HTTP/1.1

示例响应:

HTTP/1.1 200 OK
Content-Type: application/json

{"status":"Pulling..."}
{"status":"Pulling", "progress":"1 B/ 100 B", "progressDetail":{"current":1, "total":100}}
{"error":"Invalid..."}
...

这里有一个用Go语言编写的包装器,但我自己没有使用过。

英文:

Docker offers a rest based API for interacting with it programatically:

Example request:

POST /images/create?fromImage=base HTTP/1.1

Example response:

HTTP/1.1 200 OK
Content-Type: application/json

{"status":"Pulling..."}
{"status":"Pulling", "progress":"1 B/ 100 B", "progressDetail":{"current":1, "total":100}}
{"error":"Invalid..."}
...

there is a wrapper written in go here, though I have not used it myself.

huangapple
  • 本文由 发表于 2014年10月16日 05:44:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/26392645.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定