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

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

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 的简写形式。

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

    resp, err := cli.ContainerCreate(ctx, &container.Config{
        Image: "alpine",
        Cmd:   []string{"echo", "hello world"},
      },
      &container.HostConfig{
        Binds: []string{
          "/local/dir/file.txt:/app/file.txt",
        },
      },
      nil,
      "",
   )

相关链接:

英文:

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

    resp, err := cli.ContainerCreate(ctx, &container.Config{
        Image: "alpine",
        Cmd:   []string{"echo", "hello world",},
      },
      &container.HostConfig{
        Mounts: []mount.Mount{
          {
             Type: mount.TypeBind,
             Source: "/local/dir",
             Target: "/app",
          },
        },
     },
     nil,
     "",
   )

If you want just a single file

    resp, err := cli.ContainerCreate(ctx, &container.Config{
        Image: "alpine",
        Cmd:   []string{"echo", "hello world",},
      },
      &container.HostConfig{
        Binds: []string{
          "/local/dir/file.txt:/app/file.txt",
        },
      },
      nil,
      "",
   )

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:

确定