K8s获取NodePort
K8s获取NodePort(金庆的专栏 2018.9)将服务用NodePort暴露到外网,为避免端口冲突,不指定NodePort,而是让k8s自动选择一个端口。$ cat get_node_port.yamlkind: ServiceapiVersion: v1metadata:name: jq-servicespec:type: NodePorts...
·
K8s获取NodePort
(金庆的专栏 2018.9)
将服务用NodePort暴露到外网,为避免端口冲突,不指定NodePort,
而是让k8s自动选择一个端口。
$ cat get_node_port.yaml
kind: Service
apiVersion: v1
metadata:
name: jq-service
spec:
type: NodePort
selector:
app: MyApp
ports:
- protocol: TCP
port: 80
$ kubectl apply -f get_node_port.yaml
service "jq-service" configured
$ kubectl describe svc/jq-service
Name: jq-service
Namespace: default
Labels: <none>
Annotations: kubectl...
Selector: app=MyApp
Type: NodePort
IP: 10.104.228.187
Port: <unset> 80/TCP
TargetPort: 80/TCP
NodePort: <unset> 32115/TCP
Endpoints: <none>
Session Affinity: None
External Traffic Policy: Cluster
Events: <none>
可以看到k8s分配了NodePort 32115。
然后需要获取这个动态的NodePort,以通知客户端连接该端口。
cat main.go
package main
import (
"context"
"fmt"
"log"
"io/ioutil"
"github.com/ghodss/yaml"
"github.com/ericchiang/k8s"
corev1 "github.com/ericchiang/k8s/apis/core/v1"
)
func main() {
data, err := ioutil.ReadFile("config")
if err != nil {
panic(err)
}
// Unmarshal YAML into a Kubernetes config object.
var config k8s.Config
if err := yaml.Unmarshal(data, &config); err != nil {
panic(err)
}
client, err := k8s.NewClient(&config)
// client, err := k8s.NewInClusterClient()
if err != nil {
log.Fatal(err)
}
var svc corev1.Service
if err := client.Get(context.Background(), "default", "jq-service", &svc); err != nil {
log.Fatal(err)
}
fmt.Printf("%d\n", *svc.Spec.Ports[0].NodePort)
}
运行时需要复制config: cp ~/.kube/config .
更多推荐
已为社区贡献5条内容
所有评论(0)