英文:
docker stack deploy using the client api
问题
我正在使用Docker的客户端API进行开发。我已经学会了如何运行容器、推送、拉取等操作。现在我想使用Compose文件部署一个堆栈,但我不认为在客户端API中有一个单一的函数调用可以实现这一点。我查看了Docker的代码,并找到了他们是如何实现的。
这是唯一的方法吗?我试图尽量减少依赖,但如果没有其他选择,我想我可以接受这种方式。另外,我对Go语言还不太熟悉,所以如果有人能提供一个通过Go代码实现docker stack deploy --compose-file file.yml
的示例,我将非常感激。
英文:
I'm playing with docker's client api. I've seen how to run containers, pushing, pulling, etc. Now I want to deploy a stack with a compose file, but I don't think there's a one-func-call to do that (not in the client api anyway). I went trough docker's code and saw how they do it.
Is this the only way? I'm trying to keep the dependencies to a minimum, but if there aren't other options I guess I could live with it. Also I'm still pretty new to golang, so if someone could provide an example of how can I achieve docker stack deploy --compose-file file.yml
though go code will be greatly appreciated.
答案1
得分: 4
经过进一步的研究,我认为有三种选择:
-
只使用
os/exec
包和exec.Command("docker", ...)
。这个方法可以实现,但需要安装Docker客户端。 -
使用docker/client包提供的内容,并自己实现调用。这样可以获得最大的控制权,但需要实现复合调用(如docker stack deploy),例如创建镜像、网络、启动容器等。
-
使用docker/cli/command包提供的命令。这样你也可以访问一些可以覆盖的配置,并让Docker团队负责复合调用的问题。
我最终选择了第三种方法,以下是我的代码:
import (
"os"
"github.com/docker/docker/cli/command"
"github.com/docker/docker/cli/command/stack"
"github.com/docker/docker/cli/flags"
)
func main() {
cli := command.NewDockerCli(os.Stdin, os.Stdout, os.Stderr)
cli.Initialize(flags.NewClientOptions())
cmd := stack.NewStackCommand(cli)
// 这些参数会被命令包捕获,但如果需要的话,你可以进行覆盖
// cmd.SetArgs([]string{"deploy", "--compose-file", "compose.yml", "mystack"})
cmd.Execute()
}
英文:
After some more research I think I have 3 options:
-
just use os/exec package and
exec.Command("docker", ...)
. This is ok, but it requires the docker client -
use the stuff provided by the docker/client package and implement the call yourself. This gives you the most control, but you need to implement composite calls (docker stack deploy) e.g. create images, networks, start containers, etc.
-
use the commands provided by the docker/cli/command package. This way you also have access to some configs that could be overriden and you let the docker guys worry about composite calls.
I ended up using #3, here's my code:
import (
"os"
"github.com/docker/docker/cli/command"
"github.com/docker/docker/cli/command/stack"
"github.com/docker/docker/cli/flags"
)
func main() {
cli := command.NewDockerCli(os.Stdin, os.Stdout, os.Stderr)
cli.Initialize(flags.NewClientOptions())
cmd := stack.NewStackCommand(cli)
// the command package will pick up these, but you could override if you need to
// cmd.SetArgs([]string{"deploy", "--compose-file", "compose.yml", "mystack"})
cmd.Execute()
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论