docker volumes 文件映射

背景

在做区块链日志模块时,如果容器运行,需要把日志文件映射到宿主机上以方便查看。下面介绍一下我的实现方式。

实现

通过docker-compose配置文件volumes参数

配置文件示例:

  volumes:
            - /var/run/:/host/var/run/
            - ./channel-artifacts:/var/hyperledger/configs
            - ./fabric_logs:/tmp/fabric_logs/

把容器中/tmp/fabric_logs目录映射到宿主机当前目录下的./fabric_logs目录下。这两个目录会共享数据。

创建容器时,代码中配置相关参数

代码中创建容器时添加:

func (vm *DockerVM) createContainer(ctxt context.Context, client dockerClient,
    imageID string, containerID string, args []string,
    env []string, attachStdout bool) error {

    volumes := make(map[string]struct{})

    var mounts []docker.Mount
    var source string
    var destination string

    var fabricCfgPath = os.Getenv("FABRIC_CFG_PATH")
    var configName string

    _, err := os.Stat(fabricCfgPath)
    if err == nil {
        configName = strings.ToLower(Peer_Prefix)
        config := viper.New()
        config.SetConfigName(configName)
        config.AddConfigPath(fabricCfgPath)
        config.ReadInConfig()
        config.SetEnvPrefix("CORE")
        config.AutomaticEnv()
        replacer := strings.NewReplacer(".", "_")
        config.SetEnvKeyReplacer(replacer)
        config.SetConfigType("yaml")

        destination = config.GetString("logging.logpath")
        //fmt.Println(destination)
    }

    if destination == "" {
        destination = "/tmp/fabric_logs/"
    }

    source = "/tmp/chaincode_logs/" + containerID

    volumes[destination] = struct{}{}

    mount := docker.Mount{
        Name:        "bind",
        Source:      source,
        Destination: destination,
        Mode:        "rw",
        RW:          true,
        Driver:      "rprivate",
    }
    mounts = append(mounts, mount)

    config := docker.Config{Cmd: args, Image: imageID, Env: env, Volumes: volumes, Mounts: mounts, AttachStdout: attachStdout, AttachStderr: attachStdout}

    hostConfig := getDockerHostConfig()
    hostConfig.Binds = []string{
        source + ":" + destination + ":rw",
    }

    copts := docker.CreateContainerOptions{Name: containerID, Config: &config, HostConfig: hostConfig}
    dockerLogger.Debugf("Create container: %s", containerID)
    _, err = client.CreateContainer(copts)
    if err != nil {
        return err
    }
    dockerLogger.Debugf("Created container: %s", imageID)
    return nil
}

其中volumes,Mounts, Hostconfig.Binds参数需要按照自己的映射关系去填写。

这样和通过:
1、docker-compose 配置文件启动
2、或者docker -v 参数命令行启动
达到一样效果。

你可能感兴趣的:(区块链)