go docker sdk 使用 第二章
本文以zookeeper镜像做示范
容器端口映射
package main
import (
"context"
"log"
"os"
"os/signal"
"syscall"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/network"
"github.com/docker/docker/client"
"github.com/docker/go-connections/nat"
)
func main() {
cli, err := client.NewClientWithOpts(client.WithVersion("1.41"))
if err != nil {
log.Fatalln(err)
}
portinfo, _ := nat.NewPort("tcp", "2181")//指明协议端口,也可以不用他给的函数,直接写 "2181/tcp" 端口号/协议
resp, err := cli.ContainerCreate(context.Background(), &container.Config{
Image: "zookeeper",
}, &container.HostConfig{
PortBindings: nat.PortMap{portinfo: []nat.PortBinding{nat.PortBinding{HostPort: "2182"}}},//映射到宿主机0.0.0.0:2182 区别于2181,这里方便演示时区别容器端口和映射端口
}, &network.NetworkingConfig{}, nil, "zookeeper2")
if err != nil {
log.Fatalln(err)
}
err = cli.ContainerStart(context.Background(), resp.ID, container.StartOptions{})
if err != nil {
log.Fatalln(err)
}
ch := make(chan os.Signal, 1)
signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
<-ch
err2 := cli.ContainerStop(context.Background(), resp.ID, container.StopOptions{})
if err2 != nil {
log.Fatalln("stop error", err2)
}
cli.Close()
}
演示效果
本文含有隐藏内容,请 开通VIP 后查看