英文:
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 ...
同时完成了以下两个操作:
- 创建一个容器
- 启动一个容器
而 docker run -v
是 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{
Binds: []string{
"/local/dir/file.txt:/app/file.txt",
},
},
nil,
"",
)
相关链接:
- https://stackoverflow.com/q/42248198/4526019
- https://github.com/fsouza/go-dockerclient/issues/132
- https://stackoverflow.com/q/48470194/4526019
英文:
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
- create a container
- 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:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论