當前位置: 首頁>>代碼示例>>Golang>>正文


Golang go-dockerclient.Port函數代碼示例

本文整理匯總了Golang中github.com/fsouza/go-dockerclient.Port函數的典型用法代碼示例。如果您正苦於以下問題:Golang Port函數的具體用法?Golang Port怎麽用?Golang Port使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了Port函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: ports

func ports(c *project.ServiceConfig) (map[dockerclient.Port]struct{}, map[dockerclient.Port][]dockerclient.PortBinding, error) {
	ports, binding, err := nat.ParsePortSpecs(c.Ports)
	if err != nil {
		return nil, nil, err
	}

	exPorts, _, err := nat.ParsePortSpecs(c.Expose)
	if err != nil {
		return nil, nil, err
	}

	for k, v := range exPorts {
		ports[k] = v
	}

	exposedPorts := map[dockerclient.Port]struct{}{}
	for k, v := range ports {
		exposedPorts[dockerclient.Port(k)] = v
	}

	portBindings := map[dockerclient.Port][]dockerclient.PortBinding{}
	for k, bv := range binding {
		dcbs := make([]dockerclient.PortBinding, len(bv))
		for k, v := range bv {
			dcbs[k] = dockerclient.PortBinding{HostIP: v.HostIP, HostPort: v.HostPort}
		}
		portBindings[dockerclient.Port(k)] = dcbs
	}
	return exposedPorts, portBindings, nil
}
開發者ID:pirater,項目名稱:os,代碼行數:30,代碼來源:convert.go

示例2: parsePort

func parsePort(port string) docker.Port {
	if port == "" {
		return docker.Port(port)
	}
	if strings.Contains(port, "/") {
		return docker.Port(port)
	} else {
		return docker.Port(port + "/tcp")
	}
}
開發者ID:durl,項目名稱:registrator,代碼行數:10,代碼來源:services.go

示例3: CreateContainer

func CreateContainer(containerName, image, domain string, portsToMap []Port, environmentVars map[string]string) (*docker.Container, error) {
	cfg := &docker.Config{}
	cfg.Image = image
	cfg.Hostname = containerName
	cfg.Domainname = domain

	var e struct{}
	exposedPorts := make(map[docker.Port]struct{})
	for _, p := range portsToMap {
		prt := strconv.FormatUint(p.Private, 10) + "/" + p.Type
		exposedPorts[docker.Port(prt)] = e
		fmt.Printf("Exposing %s\n", prt)
	}
	cfg.ExposedPorts = exposedPorts

	envStrs := make([]string, 0, 10)
	for k, v := range environmentVars {
		envStrs = append(envStrs, k+"="+v)
	}
	cfg.Env = envStrs

	hostCfg := &docker.HostConfig{}
	hostCfg.PublishAllPorts = false
	hostCfg.Privileged = false

	hostPorts := make(map[docker.Port][]docker.PortBinding)
	for _, p := range portsToMap {
		prt := strconv.FormatUint(p.Private, 10) + "/" + p.Type
		bindings := make([]docker.PortBinding, 0, 4)
		bindings = append(bindings, docker.PortBinding{HostIP: "", HostPort: strconv.FormatUint(p.Public, 10)})
		fmt.Printf("Binding %s to %s\n", prt, bindings[0])
		hostPorts[docker.Port(prt)] = bindings
	}
	hostCfg.PortBindings = hostPorts

	opts := docker.CreateContainerOptions{}
	opts.Config = cfg
	opts.Name = containerName
	opts.HostConfig = hostCfg

	json, _ := data.PrettyPrint(opts)
	fmt.Printf("create options: %s\n", string(json))

	container, err := client.CreateContainer(opts)

	if err != nil {
		fmt.Fprintf(os.Stderr, "Error creating container: %s\n", err.Error())
	} else {
		fmt.Printf("Container created: %s\n", container.ID)
	}

	return container, err
}
開發者ID:travissimon,項目名稱:goobernet,代碼行數:53,代碼來源:docker.go

示例4: asPortBindings

func asPortBindings(ports []string) (map[docker.Port][]docker.PortBinding, map[docker.Port]struct{}) {
	binds := make(map[docker.Port][]docker.PortBinding)
	exposed := make(map[docker.Port]struct{})
	for _, port := range ports {
		parts := strings.SplitN(port, ":", 2)
		proto, cport := nat.SplitProtoPort(parts[1])
		cport = cport + "/" + proto
		binds[docker.Port(cport)] = []docker.PortBinding{{HostPort: parts[0]}}
		exposed[docker.Port(cport)] = struct{}{}
	}
	return binds, exposed
}
開發者ID:dnephin,項目名稱:dobi,代碼行數:12,代碼來源:run.go

示例5: portSetToDockerPorts

func portSetToDockerPorts(ports *schema.Set) (map[dc.Port]struct{}, map[dc.Port][]dc.PortBinding) {
	retExposedPorts := map[dc.Port]struct{}{}
	retPortBindings := map[dc.Port][]dc.PortBinding{}

	for _, portInt := range ports.List() {
		port := portInt.(map[string]interface{})
		internal := port["internal"].(int)
		protocol := port["protocol"].(string)

		exposedPort := dc.Port(strconv.Itoa(internal) + "/" + protocol)
		retExposedPorts[exposedPort] = struct{}{}

		external, extOk := port["external"].(int)
		ip, ipOk := port["ip"].(string)

		if extOk {
			portBinding := dc.PortBinding{
				HostPort: strconv.Itoa(external),
			}
			if ipOk {
				portBinding.HostIP = ip
			}
			retPortBindings[exposedPort] = append(retPortBindings[exposedPort], portBinding)
		}
	}

	return retExposedPorts, retPortBindings
}
開發者ID:jorjao81,項目名稱:terraform,代碼行數:28,代碼來源:resource_docker_container_funcs.go

示例6: CreateCassandraAndStart

func CreateCassandraAndStart(name, port string) (*docker.Container, error) {
	endpoint := "unix:///var/run/docker.sock"
	client, err := docker.NewClient(endpoint)
	if err != nil {
		return nil, err
	}

	hostConf := &docker.HostConfig{
		PortBindings: map[docker.Port][]docker.PortBinding{
			docker.Port("9042/tcp"): []docker.PortBinding{{
				HostIP:   "0.0.0.0",
				HostPort: port,
			}},
		},
	}
	/*hostConf := &docker.HostConfig{
		PublishAllPorts: true,
	}*/

	opts := docker.CreateContainerOptions{
		Name: name,
		Config: &docker.Config{
			Image: "spotify/cassandra:latest",
		},
		HostConfig: hostConf,
	}

	container, err := client.CreateContainer(opts)
	if err != nil {
		return nil, err
	}

	return container, client.StartContainer(container.ID, hostConf)
}
開發者ID:jerome-laforge,項目名稱:mytweeter,代碼行數:34,代碼來源:tweet_test.go

示例7: TestDockerDriver_PortsMapping

func TestDockerDriver_PortsMapping(t *testing.T) {
	task, res, dyn := dockerTask()
	task.Config["port_map"] = []map[string]string{
		map[string]string{
			"main":  "8080",
			"REDIS": "6379",
		},
	}

	client, handle, cleanup := dockerSetup(t, task)
	defer cleanup()

	waitForExist(t, client, handle.(*DockerHandle))

	container, err := client.InspectContainer(handle.(*DockerHandle).ContainerID())
	if err != nil {
		t.Fatalf("err: %v", err)
	}

	// Verify that the correct ports are EXPOSED
	expectedExposedPorts := map[docker.Port]struct{}{
		docker.Port("8080/tcp"): struct{}{},
		docker.Port("8080/udp"): struct{}{},
		docker.Port("6379/tcp"): struct{}{},
		docker.Port("6379/udp"): struct{}{},
	}

	if !reflect.DeepEqual(container.Config.ExposedPorts, expectedExposedPorts) {
		t.Errorf("Exposed ports don't match.\nExpected:\n%s\nGot:\n%s\n", expectedExposedPorts, container.Config.ExposedPorts)
	}

	// Verify that the correct ports are FORWARDED
	expectedPortBindings := map[docker.Port][]docker.PortBinding{
		docker.Port("8080/tcp"): []docker.PortBinding{docker.PortBinding{HostIP: "127.0.0.1", HostPort: fmt.Sprintf("%d", res)}},
		docker.Port("8080/udp"): []docker.PortBinding{docker.PortBinding{HostIP: "127.0.0.1", HostPort: fmt.Sprintf("%d", res)}},
		docker.Port("6379/tcp"): []docker.PortBinding{docker.PortBinding{HostIP: "127.0.0.1", HostPort: fmt.Sprintf("%d", dyn)}},
		docker.Port("6379/udp"): []docker.PortBinding{docker.PortBinding{HostIP: "127.0.0.1", HostPort: fmt.Sprintf("%d", dyn)}},
	}

	if !reflect.DeepEqual(container.HostConfig.PortBindings, expectedPortBindings) {
		t.Errorf("Forwarded ports don't match.\nExpected:\n%s\nGot:\n%s\n", expectedPortBindings, container.HostConfig.PortBindings)
	}

	expectedEnvironment := map[string]string{
		"NOMAD_ADDR_main":      "127.0.0.1:8080",
		"NOMAD_ADDR_REDIS":     "127.0.0.1:6379",
		"NOMAD_HOST_PORT_main": strconv.Itoa(docker_reserved),
	}

	for key, val := range expectedEnvironment {
		search := fmt.Sprintf("%s=%s", key, val)
		if !inSlice(search, container.Config.Env) {
			t.Errorf("Expected to find %s in container environment: %+v", search, container.Config.Env)
		}
	}
}
開發者ID:nak3,項目名稱:nomad,代碼行數:56,代碼來源:docker_test.go

示例8: TestDockerPortsNoMap

func TestDockerPortsNoMap(t *testing.T) {
	t.Parallel()
	task, res, dyn := dockerTask()

	client, handle, cleanup := dockerSetup(t, task)
	defer cleanup()

	container, err := client.InspectContainer(handle.(*DockerHandle).ContainerID())
	if err != nil {
		t.Fatalf("err: %v", err)
	}

	// Verify that the correct ports are EXPOSED
	expectedExposedPorts := map[docker.Port]struct{}{
		docker.Port(fmt.Sprintf("%d/tcp", res)): struct{}{},
		docker.Port(fmt.Sprintf("%d/udp", res)): struct{}{},
		docker.Port(fmt.Sprintf("%d/tcp", dyn)): struct{}{},
		docker.Port(fmt.Sprintf("%d/udp", dyn)): struct{}{},
		// This one comes from the redis container
		docker.Port("6379/tcp"): struct{}{},
	}

	if !reflect.DeepEqual(container.Config.ExposedPorts, expectedExposedPorts) {
		t.Errorf("Exposed ports don't match.\nExpected:\n%s\nGot:\n%s\n", expectedExposedPorts, container.Config.ExposedPorts)
	}

	// Verify that the correct ports are FORWARDED
	expectedPortBindings := map[docker.Port][]docker.PortBinding{
		docker.Port(fmt.Sprintf("%d/tcp", res)): []docker.PortBinding{docker.PortBinding{HostIP: "127.0.0.1", HostPort: fmt.Sprintf("%d", res)}},
		docker.Port(fmt.Sprintf("%d/udp", res)): []docker.PortBinding{docker.PortBinding{HostIP: "127.0.0.1", HostPort: fmt.Sprintf("%d", res)}},
		docker.Port(fmt.Sprintf("%d/tcp", dyn)): []docker.PortBinding{docker.PortBinding{HostIP: "127.0.0.1", HostPort: fmt.Sprintf("%d", dyn)}},
		docker.Port(fmt.Sprintf("%d/udp", dyn)): []docker.PortBinding{docker.PortBinding{HostIP: "127.0.0.1", HostPort: fmt.Sprintf("%d", dyn)}},
	}

	if !reflect.DeepEqual(container.HostConfig.PortBindings, expectedPortBindings) {
		t.Errorf("Forwarded ports don't match.\nExpected:\n%s\nGot:\n%s\n", expectedPortBindings, container.HostConfig.PortBindings)
	}

	expectedEnvironment := map[string]string{
		"NOMAD_ADDR_main":  fmt.Sprintf("127.0.0.1:%d", res),
		"NOMAD_ADDR_REDIS": fmt.Sprintf("127.0.0.1:%d", dyn),
	}

	for key, val := range expectedEnvironment {
		search := fmt.Sprintf("%s=%s", key, val)
		if !inSlice(search, container.Config.Env) {
			t.Errorf("Expected to find %s in container environment: %+v", search, container.Config.Env)
		}
	}
}
開發者ID:hooklift,項目名稱:nomad,代碼行數:50,代碼來源:docker_test.go

示例9: StartContainer

// StartContainer starts a test container and returns its ID.
func StartContainer(daemon *dockertest.Docker, bindings []*beacon.Binding, labels map[string]string) (string, error) {
	client, err := daemon.Client()
	if err != nil {
		return "", errors.Wrap(err, "unable to create docker client")
	}

	exposedPorts := map[dockerclient.Port]struct{}{}
	for _, binding := range bindings {
		port := dockerclient.Port(fmt.Sprintf("%d/%s", binding.ContainerPort, binding.Protocol))
		exposedPorts[port] = struct{}{}
	}

	container, err := client.CreateContainer(dockerclient.CreateContainerOptions{
		Config: &dockerclient.Config{
			Image:        fmt.Sprintf("%s:%s", DOCKER_IMAGE_REPO, DOCKER_IMAGE_TAG),
			Cmd:          []string{"/bin/sh", "-c", "trap exit SIGTERM SIGINT; while true; do sleep 0.1; done"},
			ExposedPorts: exposedPorts,
			Labels:       labels,
		},
	})
	if err != nil {
		return "", errors.Wrap(err, "unable to create docker container")
	}

	portBindings := map[dockerclient.Port][]dockerclient.PortBinding{}
	for _, binding := range bindings {
		port := dockerclient.Port(fmt.Sprintf("%d/%s", binding.ContainerPort, binding.Protocol))
		portBindings[port] = []dockerclient.PortBinding{{
			HostIP:   binding.HostIP,
			HostPort: fmt.Sprintf("%d", binding.HostPort),
		}}
	}

	err = client.StartContainer(container.ID, &dockerclient.HostConfig{
		PortBindings: portBindings,
	})
	if err != nil {
		StopContainer(daemon, container.ID)
		return "", errors.Wrap(err, "unable to start docker container")
	}
	return container.ID, nil
}
開發者ID:BlueDragonX,項目名稱:beacon,代碼行數:43,代碼來源:docker_test.go

示例10: createContainer

// createContainer initializes a struct needed to call docker.client.CreateContainer()
func createContainer(ctx *ExecContext, task *structs.Task, logger *log.Logger) docker.CreateContainerOptions {
	if task.Resources == nil {
		panic("task.Resources is nil and we can't constrain resource usage. We shouldn't have been able to schedule this in the first place.")
	}

	hostConfig := createHostConfig(task)
	logger.Printf("[DEBUG] driver.docker: using %d bytes memory for %s", hostConfig.Memory, task.Config["image"])
	logger.Printf("[DEBUG] driver.docker: using %d cpu shares for %s", hostConfig.CPUShares, task.Config["image"])

	// Setup port mapping (equivalent to -p on docker CLI). Ports must already be
	// exposed in the container.
	if len(task.Resources.Networks) == 0 {
		logger.Print("[WARN] driver.docker: No networks are available for port mapping")
	} else {
		network := task.Resources.Networks[0]
		dockerPorts := map[docker.Port][]docker.PortBinding{}

		for _, port := range network.ListStaticPorts() {
			dockerPorts[docker.Port(strconv.Itoa(port)+"/tcp")] = []docker.PortBinding{docker.PortBinding{HostIP: network.IP, HostPort: strconv.Itoa(port)}}
			dockerPorts[docker.Port(strconv.Itoa(port)+"/udp")] = []docker.PortBinding{docker.PortBinding{HostIP: network.IP, HostPort: strconv.Itoa(port)}}
			logger.Printf("[DEBUG] driver.docker: allocated port %s:%d -> %d (static) %s\n", network.IP, port, port)
		}

		for label, port := range network.MapDynamicPorts() {
			// If the label is numeric we expect that there is a service
			// listening on that port inside the container. In this case we'll
			// setup a mapping from our random host port to the label port.
			//
			// Otherwise we'll setup a direct 1:1 mapping from the host port to
			// the container, and assume that the process inside will read the
			// environment variable and bind to the correct port.
			if _, err := strconv.Atoi(label); err == nil {
				dockerPorts[docker.Port(label+"/tcp")] = []docker.PortBinding{docker.PortBinding{HostIP: network.IP, HostPort: strconv.Itoa(port)}}
				dockerPorts[docker.Port(label+"/udp")] = []docker.PortBinding{docker.PortBinding{HostIP: network.IP, HostPort: strconv.Itoa(port)}}
				logger.Printf("[DEBUG] driver.docker: allocated port %s:%d -> %s (mapped)", network.IP, port, label)
			} else {
				dockerPorts[docker.Port(strconv.Itoa(port)+"/tcp")] = []docker.PortBinding{docker.PortBinding{HostIP: network.IP, HostPort: strconv.Itoa(port)}}
				dockerPorts[docker.Port(strconv.Itoa(port)+"/udp")] = []docker.PortBinding{docker.PortBinding{HostIP: network.IP, HostPort: strconv.Itoa(port)}}
				logger.Printf("[DEBUG] driver.docker: allocated port %s:%d -> %d for label %s\n", network.IP, port, port, label)
			}
		}
		hostConfig.PortBindings = dockerPorts
	}

	config := &docker.Config{
		Env:   TaskEnvironmentVariables(ctx, task).List(),
		Image: task.Config["image"],
	}

	// If the user specified a custom command to run, we'll inject it here.
	if command, ok := task.Config["command"]; ok {
		config.Cmd = strings.Split(command, " ")
	}

	return docker.CreateContainerOptions{
		Config:     config,
		HostConfig: hostConfig,
	}
}
開發者ID:rbramwell,項目名稱:nomad,代碼行數:60,代碼來源:docker.go

示例11: expose

// EXPOSE 6667/tcp 7000/tcp
//
// Expose ports for links and port mappings. This all ends up in
// b.RunConfig.ExposedPorts for runconfig.
//
func expose(b *Builder, args []string, attributes map[string]bool, original string) error {
	if len(args) == 0 {
		return errAtLeastOneArgument("EXPOSE")
	}

	if b.RunConfig.ExposedPorts == nil {
		b.RunConfig.ExposedPorts = make(map[docker.Port]struct{})
	}

	existing := map[string]struct{}{}
	for k := range b.RunConfig.ExposedPorts {
		existing[k.Port()] = struct{}{}
	}

	for _, port := range args {
		dp := docker.Port(port)
		if _, exists := existing[dp.Port()]; !exists {
			b.RunConfig.ExposedPorts[docker.Port(fmt.Sprintf("%s/%s", dp.Port(), dp.Proto()))] = struct{}{}
		}
	}
	return nil
}
開發者ID:juanluisvaladas,項目名稱:origin,代碼行數:27,代碼來源:dispatchers.go

示例12: mappedPortAddress

/*
Extract a "mapped port" address. This mode assumes the balancer is
connecting to containers via a port "mapped" (NATed) by
Docker. Therefore it looks for the port mentioned in the list of
published ports, and finds the host port it has been mapped to. The IP
address is that given as the host's IP address.
*/
func (l *Listener) mappedPortAddress(container *docker.Container, port int) (string, int) {
	p := docker.Port(fmt.Sprintf("%d/tcp", port))
	if bindings, found := container.NetworkSettings.Ports[p]; found {
		for _, binding := range bindings {
			if binding.HostIP == l.hostIP || binding.HostIP == "" || binding.HostIP == "0.0.0.0" {
				mappedToPort, err := strconv.Atoi(binding.HostPort)
				if err != nil {
					return "", 0
				}
				return l.hostIP, mappedToPort
			}
		}
	}
	return "", 0
}
開發者ID:errordeveloper,項目名稱:flux,代碼行數:22,代碼來源:listener.go

示例13: Port

// Port returns the host port the specified port is mapped on.
func (c *Container) Port(port string) (string, error) {
	info, err := c.findInfo()
	if err != nil {
		return "", err
	}

	if bindings, ok := info.NetworkSettings.Ports[dockerclient.Port(port)]; ok {
		result := []string{}
		for _, binding := range bindings {
			result = append(result, binding.HostIP+":"+binding.HostPort)
		}

		return strings.Join(result, "\n"), nil
	}
	return "", nil
}
開發者ID:gondor,項目名稱:libcompose,代碼行數:17,代碼來源:container.go

示例14: PortForward

func (h *Runner) PortForward(local, remote int) *Runner {
	if h.hostConfig.PortBindings == nil {
		h.hostConfig.PortBindings = map[docker.Port][]docker.PortBinding{}
	}
	containerPort := docker.Port(fmt.Sprintf("%d/tcp", remote))
	binding := docker.PortBinding{
		HostPort: fmt.Sprintf("%d", local),
	}
	h.hostConfig.PortBindings[containerPort] = []docker.PortBinding{binding}

	if h.config.ExposedPorts == nil {
		h.config.ExposedPorts = map[docker.Port]struct{}{}
	}
	h.config.ExposedPorts[containerPort] = struct{}{}
	return h
}
開發者ID:Xmagicer,項目名稱:origin,代碼行數:16,代碼來源:run.go

示例15: startContainers

func (m *mockInspector) startContainers(cs ...container) {
	for _, c := range cs {
		env := []string{}
		for k, v := range c.Env {
			env = append(env, strings.Join([]string{k, v}, "="))
		}
		ports := map[docker.Port][]docker.PortBinding{}
		for k, v := range c.Ports {
			ports[docker.Port(k)] = []docker.PortBinding{
				docker.PortBinding{
					HostIP:   "0.0.0.0",
					HostPort: v,
				},
			}
		}

		netmode := c.NetworkMode
		if netmode == "" {
			netmode = "default"
		}
		c1 := &docker.Container{
			ID: c.ID,
			HostConfig: &docker.HostConfig{
				NetworkMode: netmode,
			},
			Config: &docker.Config{
				Image:  c.Image,
				Env:    env,
				Labels: c.Labels,
			},
			NetworkSettings: &docker.NetworkSettings{
				IPAddress: c.IPAddress,
				Ports:     ports,
			},
		}
		m.containers[c.ID] = c1
		if m.events != nil {
			m.events <- &docker.APIEvents{
				Status: "start",
				ID:     c.ID,
			}
		}
	}
}
開發者ID:errordeveloper,項目名稱:flux,代碼行數:44,代碼來源:listener_test.go


注:本文中的github.com/fsouza/go-dockerclient.Port函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。