How to perform docker run -p xxxx:xxxx using containerd/client and go-cni
yldoge opened this issue · comments
yldoge commented
Could anyone give an example of code snippets of how to use CNI plugin to set up the network and attach to a container with port forwarding capability programmatically?
My code skeleton now looks like this:
l, err := gocni.New(
gocni.WithPluginConfDir("c:\\Program Files\\containerd\\cni\\conf"),
gocni.WithPluginDir([]string{"c:\\Program Files\\containerd\\cni\\bin"}),
)
err := l.Load(gocni.WithDefaultConf)
netNs, err := netns.NewNetNS("")
result, err := l.Setup(ctx, id, netNs.GetPath(),
gocni.WithLabels(map[string]string{
"IgnoreUnknown": "1",
}),
gocni.WithCapabilityPortMap([]gocni.PortMapping{
{
ContainerPort: 8888,
HostPort: 8886,
HostIP: "0.0.0.0",
Protocol: "TCP",
},
}),
)
// ============================ create container ============================
c, err := h.conn.NewContainer(ctx, id,
containerd.WithImage(img),
containerd.WithNewSpec(
oci.WithDefaultSpec(),
oci.WithImageConfig(img),
WithWindowsNetNS(netNs.GetPath()),
),
containerd.WithNewSnapshot("test-container", img),
)
func WithWindowsNetNS(path string) oci.SpecOpts {
return func(_ context.Context, _ oci.Client, _ *containers.Container, s *specs.Spec) error {
if s.Windows == nil {
s.Windows = &specs.Windows{}
}
if s.Windows.Network == nil {
s.Windows.Network = &specs.WindowsNetwork{}
}
s.Windows.Network.NetworkNamespace = path
return nil
}
}