1.6.3. 使用 Service 连接到应用

1.6.3.1. 访问 Service

k8s支持2中查找服务的模式, 环境变量和dns

1.6.3.2. 保护 Service

我们只在集群内部访问了 Nginx 服务器。在将 Service 暴露到因特网之前,我们希望确保通信信道是安全的。 为实现这一目的,可能需要:

  • 用于 HTTPS 的自签名证书(除非已经有了一个识别身份的证书)

  • 使用证书配置的 Nginx 服务器

  • 使证书可以访问 Pod 的 Secret

准备公钥和私钥

1KEY=nginx.key
2CERT=nginx.crt
3openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout $KEY -out $CERT -subj "/CN=nginxsvc/O=nginxsvc"

执行上面的脚本,生成证书,然后执行下面脚本完成secret的创建

# 直接跟进文件创建
kubectl create secret  tls nginxsvc.tls --key=nginx.key --cert=nginx.crt
# 通过命令方式,进行归档成为文件
kubectl get secret  nginxsvc.tls  -o yaml >nginxsvc.tls

准备个nginx配置下

curl 'https://raw.githubusercontent.com/kubernetes/examples/master/staging/https-nginx/default.conf'  >default.conf
kubectl get cm nginxconfigmap -o yaml >nginxconfigmap.yaml

准备nginx service和deployment

 1apiVersion: v1
 2kind: Service
 3metadata:
 4  name: my-nginx
 5  labels:
 6    run: my-nginx
 7spec:
 8  type: NodePort
 9  ports:
10  - port: 8080
11    targetPort: 80
12    protocol: TCP
13    name: http
14  - port: 443
15    protocol: TCP
16    name: https
17  selector:
18    run: my-nginx
19---
20apiVersion: apps/v1
21kind: Deployment
22metadata:
23  name: my-nginx
24spec:
25  selector:
26    matchLabels:
27      run: my-nginx
28  replicas: 1
29  template:
30    metadata:
31      labels:
32        run: my-nginx
33    spec:
34      volumes:
35      - name: secret-volume
36        secret:
37          secretName: nginxsvc.tls
38      - name: configmap-volume
39        configMap:
40          name: nginxconfigmap
41      containers:
42      - name: nginxhttps
43        image: bprashanth/nginxhttps:1.0
44        ports:
45        - containerPort: 443
46        - containerPort: 80
47        volumeMounts:
48        - mountPath: /etc/nginx/ssl
49          name: secret-volume
50        - mountPath: /etc/nginx/conf.d
51          name: configmap-volume

访问测试

# 确认ip
kubectl get pod my-nginx-77fd8b978f-rcvh2 -o yaml |grep podip -i
podIP: 10.244.2.219
podIPs:

# 测试访问
$ curl -k https://10.244.2.219/ |grep Welcome
% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                Dload  Upload   Total   Spent    Left  Speed
100   612  100   612    0     0   6274      0 --:--:-- --:--:-- --:--:--  6309
<title>Welcome to nginx!</title>
<h1>Welcome to nginx!</h1>