Skip to content

Instantly share code, notes, and snippets.

@crosbymichael
Last active November 15, 2017 21:39
Show Gist options
  • Save crosbymichael/672385bc29f605704223e30a12bce212 to your computer and use it in GitHub Desktop.
Save crosbymichael/672385bc29f605704223e30a12bce212 to your computer and use it in GitHub Desktop.
package main
import (
"context"
"syscall"
"time"
"github.com/Sirupsen/logrus"
"github.com/containerd/containerd"
"github.com/containerd/containerd/namespaces"
)
const (
address = "/run/containerd/containerd.sock"
redis = "docker.io/library/redis:alpine"
)
func main() {
ctx := context.Background()
// name your own namespace
ctx = namespaces.WithNamespace(ctx, "mystuff")
if err := runRedis(ctx, "redis"); err != nil {
logrus.Error(err)
}
}
func runRedis(ctx context.Context, id string) error {
client, err := containerd.New(address)
if err != nil {
return err
}
defer client.Close()
image, err := client.Pull(ctx, redis, containerd.WithPullUnpack)
if err != nil {
return err
}
container, err := client.NewContainer(
ctx,
id,
containerd.WithNewSpec(containerd.WithImageConfig(image)),
containerd.WithNewSnapshot(id, image),
)
if err != nil {
return err
}
// delete the snapshot with the container
defer container.Delete(ctx, containerd.WithSnapshotCleanup)
// use our stdio for the container's stdio
task, err := container.NewTask(ctx, containerd.Stdio)
if err != nil {
return err
}
// get the exit channel
exit, err := task.Wait(ctx)
if err != nil {
return err
}
defer task.Delete(ctx)
// start the task
if err := task.Start(ctx); err != nil {
return err
}
// for the example run for 3 sec then kill the redis container
time.Sleep(3 * time.Second)
if err := task.Kill(ctx, syscall.SIGTERM); err != nil {
return err
}
// wait for the task to exit
<-exit
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment