Created
October 7, 2020 05:14
-
-
Save noateden/75bf69edf5d0b056d20de2935dcd9b9d to your computer and use it in GitHub Desktop.
Run Docker container use Golang SDk
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ( | |
"context" | |
"fmt" | |
"github.com/docker/docker/api/types" | |
"github.com/docker/docker/api/types/container" | |
"github.com/docker/docker/client" | |
"github.com/docker/go-connections/nat" | |
) | |
func CreateNewContainer(image string) (string, error) { | |
cli, err := client.NewEnvClient() | |
if err != nil { | |
fmt.Println("Unable to create docker client") | |
panic(err) | |
} | |
hostBinding := nat.PortBinding{ | |
HostIP: "0.0.0.0", | |
HostPort: "8000", | |
} | |
containerPort, err := nat.NewPort("tcp", "80") | |
if err != nil { | |
panic("Unable to get the port") | |
} | |
portBinding := nat.PortMap{containerPort: []nat.PortBinding{hostBinding}} | |
cont, err := cli.ContainerCreate( | |
context.Background(), | |
&container.Config{ | |
Image: image, | |
}, | |
&container.HostConfig{ | |
PortBindings: portBinding, | |
}, nil, "") | |
if err != nil { | |
panic(err) | |
} | |
cli.ContainerStart(context.Background(), cont.ID, types.ContainerStartOptions{}) | |
fmt.Printf("Container %s is started", cont.ID) | |
return cont.ID, nil | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ( | |
"context" | |
"io" | |
"os" | |
"github.com/docker/distribution/reference" | |
"github.com/docker/docker/api/types" | |
) | |
func PullImage(name string) error { | |
ctx := context.Background() | |
distributionRef, err := reference.ParseNormalizedNamed(name) | |
if err != nil { | |
return err | |
} | |
ref := reference.TagNameOnly(distributionRef) | |
name = ref.String() | |
reader, err := dc.Cmd.ImagePull(ctx, name, request.Options) | |
if err != nil { | |
panic(err) | |
} | |
_, err = io.Copy(os.Stdout, reader) | |
if err != nil { | |
return nil | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment