Golang Docker SDK: 创建共享目录并设置只读权限
使用 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目录存在,并且对于运行此代码的用户有读取权限。
常见错误:'bind source path does not exist'
此错误表示您在主机上的绑定源路径不存在。请确保该路径正确且存在。
原文地址: https://www.cveoy.top/t/topic/fMDN 著作权归作者所有。请勿转载和采集!