Hello,
I’m trying to create and run a container with the Docker SDK for GoLang, but I am getting always the same error when I try to set the port bindings. I looked these threads in StackOverflow, but I’m getting the same error:
This is my code:
import (
"fmt"
"strings"
"strconv"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
"github.com/docker/docker/api/types/container"
"github.com/docker/go-connections/nat"
"golang.org/x/net/context"
)
func CreateAndRun(image string, bindings map[string]int) {
portBinding := nat.PortMap {}
for port, binding := range bindings {
portBinding[nat.Port(port)] = []nat.PortBinding{
nat.PortBinding{
HostIP: "0.0.0.0",
HostPort: strconv.Itoa(binding),
},
}
}
resp, err := client.ContainerCreate(ctx, &container.Config {
Image: image,
Labels: map[string]string {DOCKER_CONTAINER_LABEL: ""},
}, &container.HostConfig{
PortBindings: portBinding,
AutoRemove: DOCKER_REMOVE_ON_EXIT,
}, nil, "")
if err != nil {
panic(err)
}
if err := client.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{}); err != nil {
panic(err)
}
fmt.Println(resp.ID)
}
And this is the error I’m getting while compiling:
error: incompatible type for field 5 in struct construction (cannot use type nat.PortMap as type nat.PortMap)
PortBindings: portBinding,
If I cast the variable “portBinding” to “net.PortMap” I am still getting this error.
For installing the libraries I ran:
go get github.com/docker/docker/api/types
go get github.com/docker/docker/client
go get github.com/docker/go-connections/nat
go get golang.org/x/net/context
Does anyone know what is happening?
Thanks,
Xoán
UPDATE: If somehow it matters, I’m using Ubuntu 18.04 LTS, Docker 19.03.4 and Go 1.10.3 (gccgo).