使用Kubectl搭配yaml檔案部署

Posted by Kubeguts on 2020-10-19

目前有一份定義好可部署於K8S的yaml檔案如下

nginx.deployment.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
apiVersion: apps/v1
kind: Deployment # 定義部署種類
metadata:
name: my-nginx # 定義部署名稱
labels:
app: my-nginx
spec:
replicas: 2 # 定義Pods內至少有多少個container是Running的
selector: # 待補充
matchLabels:
app: my-nginx
template: # 待補充
metadata:
labels:
app: my-nginx
spec:
containers: # 定義容器內容
- name: my-nginx
image: nginx:alpine
ports:
- containerPort: 80
resources:
limits:
memory: "128Mi" #128 MB
cpu: "200m" #200 millicpu (.2 cpu or 20% of the cpu)

部署動作

指令 nginx.deployment.yml 檔案,並使用 --save-config 儲存設定,可供後續做調整

1
kubectl create -f nginx.deployment.yml --save-config

可以看到目前有

  • 2個Pods
  • 1個services
  • 1個deployment
  • 1個replicaset
1
2
3
4
5
6
7
8
9
10
11
12
13
kubectl get all
NAME READY STATUS RESTARTS AGE
pod/my-nginx-6f5645dc6c-dslqd 1/1 Running 0 10h
pod/my-nginx-6f5645dc6c-rxrhz 1/1 Running 0 10h

NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
service/kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 10h

NAME READY UP-TO-DATE AVAILABLE AGE
deployment.apps/my-nginx 2/2 2 2 10h

NAME DESIRED CURRENT READY AGE
replicaset.apps/my-nginx-6f5645dc6c 2 2 2 10h

若需要看到在k8s中Pods所運行的nginx伺服器,需要使用 Port forwarding的動作

假設若要看到Pods: my-nginx-6f5645dc6c-dslqd 這台伺服器

1
kubectl port-forward my-nginx-6f5645dc6c-dslqd 8080:80

查到瀏覽器就可以看到如下資訊,表示運行成功

1
2
3
4
5
6
7
Welcome to nginx!
If you see this page, the nginx web server is successfully installed and working. Further configuration is required.

For online documentation and support please refer to nginx.org.
Commercial support is available at nginx.com.

Thank you for using nginx.

調整replicaset內 nginx 的數量

若要scale out服務的數量,可以在yaml檔案內中 replicaset進行調整

這次把nginx調整為4台

1
2
spec:
replicas: 4 # 定義Pods內至少有多少個container是Running的

再次透過 kubectl apply -f <yaml> 重新設定

1
2
3
$ kubectl apply -f nginx.deployment.yml

deployment.apps/my-nginx configured

透過 kubectl get pods 查看是否有運行4台nginx

1
2
3
4
5
6
kubectl get pods
NAME READY STATUS RESTARTS AGE
my-nginx-6f5645dc6c-4j7cn 1/1 Running 0 59s
my-nginx-6f5645dc6c-dslqd 1/1 Running 0 11h
my-nginx-6f5645dc6c-gpbb4 1/1 Running 0 59s
my-nginx-6f5645dc6c-rxrhz 1/1 Running 0 11h