import ( "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/mount" "github.com/docker/docker/api/types/network" "github.com/docker/docker/client" "context" ) func createContainer(ctx context.Context) error { cli, err := client.NewClientWithOpts(client.FromEnv) if err != nil { return err } // Here we define the container configuration resp, err := cli.ContainerCreate(ctx, &container.Config{ Image: "nginx", ExposedPorts: nat.PortSet{ "80/tcp": struct{}{}, }, Env: []string{ "FOO=bar", }, }, &container.HostConfig{ PortBindings: nat.PortMap{ "80/tcp": []nat.PortBinding{ {HostIP: "0.0.0.0", HostPort: "80"}, }, }, Mounts: []mount.Mount{ { Type: mount.TypeBind, Source: "/path/on/host", Target: "/path/on/container", }, }, }, &network.NetworkingConfig{}, "my-nginx-container") if err != nil { return err } if err := cli.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{}); err != nil { return err } return nil }
import ( "github.com/docker/docker/client" "context" ) func stopContainer(ctx context.Context, containerID string) error { cli, err := client.NewClientWithOpts(client.FromEnv) if err != nil { return err } if err := cli.ContainerStop(ctx, containerID, nil); err != nil { return err } if err := cli.ContainerRemove(ctx, containerID, types.ContainerRemoveOptions{}); err != nil { return err } return nil }This example stops a running container with the given containerID and removes it.