golang docker sdk中ContainerCreate方法创建共享目录并设置共享目录只读如何实现设置共享目录后报错 Error response from daemon invalid mount config for type bind bind source path does not exist homewufantestKvm
在使用golang docker sdk的ContainerCreate方法创建共享目录时,可以通过设置Mount类型为bind,并设置ReadOnly属性为true来实现只读共享目录。
以下是一个示例代码:
package main
import (
"context"
"fmt"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
)
func main() {
cli, err := client.NewClientWithOpts(client.FromEnv)
if err != nil {
panic(err)
}
ctx := context.Background()
hostPath := "/home/wufan/testKvm" // 主机目录
containerPath := "/shared" // 容器内目录
// 创建共享目录的mount配置
bindMount := types.Mount{
Type: types.Bind,
Source: hostPath,
Target: containerPath,
ReadOnly: true,
Consistency: types.DefaultConsistency,
}
// 创建容器的配置
config := &container.Config{
Image: "your_image_name",
Cmd: []string{"your_command"},
}
// 创建容器的HostConfig配置
hostConfig := &container.HostConfig{
Mounts: []types.Mount{bindMount},
}
// 创建容器
resp, err := cli.ContainerCreate(ctx, config, hostConfig, nil, nil, "your_container_name")
if err != nil {
panic(err)
}
// 启动容器
err = cli.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{})
if err != nil {
panic(err)
}
fmt.Println("Container created and started:", resp.ID)
}
请确保/home/wufan/testKvm目录存在,并且对于运行此代码的用户有读取权限。
原文地址: https://www.cveoy.top/t/topic/h402 著作权归作者所有。请勿转载和采集!