使用k8s部署Nginx并提供https证书访问

1、在服务器内部创建证书

运行下列命令,将生成两个文件tls.key(秘钥)和tls.crt(证书内容)

openssl req -newkey rsa:2048 -nodes -keyout tls.key -x509 -days 365 -out tls.crt
Generating a 2048 bit RSA private key
...............+++
.............................+++
writing new private key to 'tls.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:Beijing
Locality Name (eg, city) [Default City]:Beijing
Organization Name (eg, company) [Default Company Ltd]:Kingsoft
Organizational Unit Name (eg, section) []:Ksyun
Common Name (eg, your name or your server's hostname) []:foo.bar.com
Email Address []:ksyun@kingsoft.com

2、将上述两个文件加入到configMap中

kubectl create configmap ssl-key --from-file=tls.key -n kce-test
kubectl create configmap ssl-crt --from-file=tls.crt -n kce-test

(configMap的名字需要和deployment.yaml的相对应)

3、编写default.conf文件

default.conf文件内容如下:

server {  
    listen 443;  

    ssl on;  
    ssl_certificate /etc/ssl/tls.crt;  
    ssl_certificate_key /etc/ssl/tls.key;  

    server_name foo.bar.com;  
    location / {  
    }  
}

将default.conf加入到configmap中:

kubectl create configmap nginx-volume --from-file=default.conf -n kce-test

4、启动部署deployment.yaml文件

deployment.yaml的内容如下:

# app/app.yaml
apiVersion: v1
kind: Service
metadata:
  name: llx-nginx-app
  namespace: kce-test
spec:
  selector:
    app: llx-nginx-app
  ports:
  - protocol: "TCP"
    port: 443
    targetPort: 443
  type: LoadBalancer

---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: llx-nginx-app
  namespace: kce-test
spec:
  selector:
    matchLabels:
      app: llx-nginx-app
  replicas: 1
  template:
    metadata:
      labels:
        app: llx-nginx-app
    spec:
      containers:
      - name: llx-nginx
        image: hub-galaxy.yunyan.com/kce-test/nginx:alpine
        volumeMounts:
        - mountPath: /etc/nginx/conf.d/default.conf  # nginx 配置文件在 pod 中的路径
          name: nginx-volume
          subPath: default.conf
        - mountPath: /etc/ssl/tls.crt  # crt 文件在 pod 中的路径
          name: ssl-crt
          subPath: tls.crt
        - mountPath: /etc/ssl/tls.key  # 域名的 key 文件在 pod 中的路径
          name: ssl-key
          subPath: tls.key
        ports:
        - containerPort: 443
      volumes:
      - name: nginx-volume
        configMap:
          name: default.conf
      - name: ssl-crt
        configMap:
          name: tls.crt
      - name: ssl-key
        configMap:
          name: tls.key

启动命令:

kubectl apply -f deployment.yaml

5、测试

在这里插入图片描述

Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐