k8s 搭建nginx例項(service、configmap和deployment組合)
環境:k8sv1.18.5
網路環境:calico,通過nodePort方式對外提供nginx服務
一、建立nginx的service
1.定義nginx的service(nginx-service.yml)
apiVersion: v1 kind: Service metadata: name: nginx-service #定義service名稱為nginx-service labels: app: nginx-service #為service打上app標籤 spec: type: NodePort #使用NodePort方式開通,在每個Node上分配一個埠作為外部訪問入口 selector: app: my-nginx ports: - port: 8000 #port是k8s叢集內部訪問service的埠,即通過clusterIP: port可以訪問到某個service targetPort: 80 #targetPort是pod的埠,從port和nodePort來的流量經過kube-proxy流入到後端pod的targetPort上,最後進入容器 nodePort: 32500 #nodePort是外部訪問k8s叢集中service的埠,通過nodeIP: nodePort可以從外部訪問到某個service
埠type型別:
• ClusterIP:預設,分配一個叢集內部可以訪問的虛擬IP(VIP)
• NodePort:在每個Node上分配一個埠作為外部訪問入口
• LoadBalancer:工作在特定的Cloud Provider上,例如Google Cloud,AWS,OpenStack
2.建立nginx-service服務
kubectl create -f nginx-service.yml
3.驗證服務是否建立成功
kubectl get svc
二、建立ngixn的configmap配置檔案(nginx-configmap.yml)
1.定義nginx的configmap配置
apiVersion: v1 kind: ConfigMap metadata: name: nginx-configmap data: nginx_conf: |- #user nobody; worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; server { listen 80; server_name localhost; location / { root html; index index.html index.htm; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } }
2.建立nginx-configmap
kubectl create -f nginx-configmap.yml
3.驗證是否建立成功
kubectl get cm
三、建立nginx的deployment
1.定義nginx的deployment
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-nginx
spec:
selector:
matchLabels:
app: my-nginx
replicas: 2
template:
metadata:
labels:
app: my-nginx
spec:
containers:
- name: my-nginx
image: nginx
ports:
- containerPort: 80
volumeMounts:
- mountPath: /etc/nginx/nginx.conf
name: nginx
subPath: nginx.conf
volumes:
- name: nginx
configMap:
name: nginx-configmap
items:
- key: nginx_conf
path: nginx.conf
#resources:
# requests:
# cpu: 1
# memory: 500Mi
# limits:
# cpu: 2
# memory: 1024Mi
2.建立nginx的deployment
kubectl create -f nginx-deployment.yml
3.驗證deployment是否建立成功
kubectl get deploy
my-nginx就是建立的deploy,但是ready狀態是0,證明pod為能成功建立。後面排查發現,pod一直卡在了容器建立階段
4.驗證deployment對應的pod是否建立成功
kubectl get pod
容器一直卡在容器建立階段,需排查問題。
通過檢視某個容器的詳細資訊,發現是nginx的configmap的問題:
kubectldescribepodmy-nginx-65b859bc7b-qvh2t
Warning FailedMount 7m56s (x35 over 62m) kubelet, k8s-slave1 MountVolume.SetUp failed for volume "nginx" : configmap "nginx_configmap" not found
Warning FailedMount 2m (x23 over 60m) kubelet, k8s-slave1 Unable to attach or mount volumes: unmounted volumes=[nginx], unattached volumes=[nginx default-token-jd5zv]: timed out waiting for the condition。
原因:拉取nginx的最新映象失敗
解決方法:手動通過dockerpullnginx拉一次映象下來