如何使用Docker引擎SDK和Golang运行Docker挂载卷

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

How to run docker mounting volumes using Docker engine SDK and Golang

问题

我一直在查看与使用Golang运行Docker相关的Docker引擎SDK文档(https://docs.docker.com/engine/api/sdk/)。
我想要运行一个容器(已经有很好的文档),但是我找不到如何在运行容器时挂载卷的方法。

我的想法是使用Docker SDK来运行等效的命令:
docker run -v $PWD:/tmp myimage
但是不使用Golang的os exec库来执行。

这种方式可行吗?

英文:

I have being reviewing the docker engine SDK documentation related with running Docker with Golang (https://docs.docker.com/engine/api/sdk/)
I would like to run a container(which is well documented) but I cannot find how can I mount a volume when running the container.

My idea is to use Docker SDK to run the equivalent command:
docker run -v $PWD:/tmp myimage
But without executing the Golang os exec library.

Is that possible?

答案1

得分: 2

示例部分包含了大部分你所需要的内容:

https://docs.docker.com/engine/api/sdk/examples/#run-a-container

重要的是要记住,docker run ... 同时完成了以下两个操作:

  1. 创建一个容器
  2. 启动一个容器

docker run -vdocker run --mount type=bind,source="$(pwd)"/target,target=/app 的简写形式。

如果你只想要一个单独的文件,可以使用以下代码:

  1. resp, err := cli.ContainerCreate(ctx, &container.Config{
  2. Image: "alpine",
  3. Cmd: []string{"echo", "hello world"},
  4. },
  5. &container.HostConfig{
  6. Binds: []string{
  7. "/local/dir/file.txt:/app/file.txt",
  8. },
  9. },
  10. nil,
  11. "",
  12. )

相关链接:

英文:

The examples section has most of what you need:

https://docs.docker.com/engine/api/sdk/examples/#run-a-container

Important to remember that docker run ... does both

  1. create a container
  2. start a container

and that docker run -v is short hand for docker run --mount type=bind,source="$(pwd)"/target,target=/app

  1. resp, err := cli.ContainerCreate(ctx, &container.Config{
  2. Image: "alpine",
  3. Cmd: []string{"echo", "hello world",},
  4. },
  5. &container.HostConfig{
  6. Mounts: []mount.Mount{
  7. {
  8. Type: mount.TypeBind,
  9. Source: "/local/dir",
  10. Target: "/app",
  11. },
  12. },
  13. },
  14. nil,
  15. "",
  16. )

If you want just a single file

  1. resp, err := cli.ContainerCreate(ctx, &container.Config{
  2. Image: "alpine",
  3. Cmd: []string{"echo", "hello world",},
  4. },
  5. &container.HostConfig{
  6. Binds: []string{
  7. "/local/dir/file.txt:/app/file.txt",
  8. },
  9. },
  10. nil,
  11. "",
  12. )

related:

huangapple
  • 本文由 发表于 2022年12月2日 05:51:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/74648570.html
匿名

发表评论

匿名网友

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

确定