| | |
| | | var ( |
| | | replicas int32 = 3 |
| | | port int32 = 9081 |
| | | rpcPort int32 = 9082 |
| | | namespaces = []string{"guangsheng", "geruimi", "tongsheng"} |
| | | usedNodePorts = make(map[int32]bool) |
| | | ) |
| | |
| | | return err |
| | | } |
| | | |
| | | log.Printf("Waiting for Deployment %s to be ready...\n", deploymentName) |
| | | // 创建 Service |
| | | err = createService(clientset, namespace, serviceName) |
| | | if err != nil { |
| | |
| | | Containers: []apiv1.Container{ |
| | | { |
| | | Name: namespace, |
| | | Image: "192.168.20.119/apsserver/apsserver:v0.2", |
| | | Image: "192.168.20.119/apsserver/apsserver:v0.5", |
| | | Env: []apiv1.EnvVar{ |
| | | { |
| | | Name: "NODE_ID", |
| | |
| | | func createService(clientset *kubernetes.Clientset, namespace, serviceName string) error { |
| | | fmt.Println("\033[1;37;40mCreating Service:", serviceName, "\033[0m") |
| | | |
| | | nodePort, err := getRandomNodePort(clientset) |
| | | if err != nil { |
| | | return err |
| | | } |
| | | //nodePort, err := getRandomNodePort(clientset) |
| | | //if err != nil { |
| | | // return err |
| | | //} |
| | | |
| | | service := &apiv1.Service{ |
| | | ObjectMeta: metav1.ObjectMeta{ |
| | |
| | | { |
| | | Name: "http", |
| | | Protocol: apiv1.ProtocolTCP, |
| | | Port: port, |
| | | TargetPort: intstr.FromInt(int(port)), |
| | | NodePort: nodePort, |
| | | Port: port, // 集群内部访问端口 |
| | | TargetPort: intstr.FromInt(int(port)), // 容器对外端口 |
| | | NodePort: 0, // 外部访问端口 |
| | | }, |
| | | { |
| | | Name: "tcp", |
| | | Protocol: apiv1.ProtocolTCP, |
| | | Port: rpcPort, |
| | | TargetPort: intstr.FromInt(int(rpcPort)), |
| | | NodePort: 0, |
| | | }, |
| | | }, |
| | | }, |
| | | } |
| | | |
| | | _, err = clientset.CoreV1().Services(namespace).Create(context.TODO(), service, metav1.CreateOptions{}) |
| | | _, err := clientset.CoreV1().Services(namespace).Create(context.TODO(), service, metav1.CreateOptions{}) |
| | | |
| | | if err != nil { |
| | | if !errors.IsAlreadyExists(err) { |
| | | return fmt.Errorf("failed to create Service: %v", err) |
| | | } |
| | | fmt.Printf("Service %s already exists in Namespace %s\n", serviceName, namespace) |
| | | log.Printf("Service %s already exists in Namespace %s\n", serviceName, namespace) |
| | | } else { |
| | | fmt.Printf("Service %s created in Namespace %s\n", serviceName, namespace) |
| | | log.Printf("Service %s created in Namespace %s\n", serviceName, namespace) |
| | | } |
| | | |
| | | return nil |
| | |
| | | |
| | | // 获取第一个端口的 NodePort |
| | | if len(svc.Spec.Ports) > 0 { |
| | | return svc.Spec.Ports[0].NodePort, nil |
| | | for _, p := range svc.Spec.Ports { |
| | | // return tcp port |
| | | if p.Name == "tcp" { |
| | | return p.NodePort, nil |
| | | } |
| | | } |
| | | } |
| | | |
| | | return 0, fmt.Errorf("no ports defined for Service %s", serviceName) |