Home > Net >  How to run docker mounting volumes using Docker engine SDK and Golang
How to run docker mounting volumes using Docker engine SDK and Golang

Time:12-02

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?

CodePudding user response:

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:

  • Related