示例代码
示例中有忽略部分文件内容,详细配置yaml文件与golang的demo都通过下面的传送查看
注入配置
secret
建议存储如密码,私钥等敏感的数据,
pods
通过环境变量
或者volume
获取 stringData
: 记录为字符串, data
: 记录为base64编码后的值; 通过 kubectl 打印的密钥是被base64编码后的值 密钥配置
apiVersion: v1
kind: Secret
metadata:
name: demo
labels:
app: demo
type: Opaque
stringData:
server_secret: "qvbilam-secret"
configMap
存储应用信息配置非敏感的数据,
pods
通过环境变量
或者volume
获取 apiVersion: "v1"
kind: ConfigMap
metadata:
name: demo
labels:
app: demo
data:
# 服务配置
server_name: "demo-http"
deployment
apiVersion: apps/v1
kind: Deployment
metadata:
name: demo-http
spec:
template:
metadata:
labels:
app: demo-http
version: v1.1
spec:
containers:
- name: demo-http-server
image: qvbilam/http-server:1.1-alpine3.15
imagePullPolicy: Always
env: # 定义系统参数
- name: SERVER_NAME # 系统参数名
valueFrom:
configMapKeyRef: # 值来源 configMap
key: server_name # configMap.data 中定义健
name: demo # 创建 configMap 名称
- name: SERVER_SECRET # 系统参数名
valueFrom:
secretKeyRef: # 值来源 secret
key: server_secret # secret.stringData 中定义健
name: demo # 创建 secret 名称
imagePullSecrets:
# 启动中定义的 secret 名字
- name: self.hubkey
selector:
matchLabels:
app: demo-http
生成密钥
# 申请密钥
$ kubectl apply -f demo.secret.yaml
# 查看密钥
$ kubectl get secret
NAME TYPE DATA AGE
default-token-wq8kf kubernetes.io/service-account-token 3 23h
demo Opaque 2 8s
self.hubkey kubernetes.io/dockerconfigjson 1 16h
# 输出密钥内容(密钥结果是被base64编码之后的值)
$ kubectl get secret demo -o yaml
apiVersion: v1
data:
server_name: cXZiaWxhbS1kZW1v
server_secret: cXZiaWxhbS1zZWNyZXQ=
测试
申请服务
# 申请 configMap
$ kubectl apply -f demo.config.yaml
# 申请 secret
$ kubectl apply -f demo.secret.yaml
# 申请 deploment
$ kubectl apply -f demo.deployment.yaml
# 申请 server
$ kubectl apply -f demo.server.yaml
查看配置
# 进入容器
$ kubectl exec -it demo-http-6b8b764765-qzjhm /bin/sh
# 查看配置
$ export | grep "export SERVER"
export SERVER_NAME='demo-http'
export SERVER_SECRET='qvbilam-secret'
访问测试
# 开放端口9011映射9001
$ kubectl port-forward service/demo-http 9011:9001 -n default
# 访问测试
$ curl 127.0.0.1:9011
{"version":"1.1.1","server_name":"demo-http","server_secret":"qvbilam-secret"}%