---
# System prepended metadata

title: Kubectl
tags: [k8s]

---

---
title: Kubectl
tags: k8s
---

# install
* install [gcloud cli](https://cloud.google.com/sdk/docs/install)
* [oh-my-zsh plugin](https://github.com/ohmyzsh/ohmyzsh/tree/master/plugins/kubectl)
```
gcloud components install kubectl
gcloud components update kubectl
```


# syntax
kubectl [command] [TYPE] [NAME] [flags]
* [command](https://kubernetes.io/zh-cn/docs/reference/kubectl/#%E6%93%8D%E4%BD%9C): 對資源進行的操作, ex: create, get, describe, delete
* [TYPE](https://kubernetes.io/zh-cn/docs/reference/kubectl/#%E8%B5%84%E6%BA%90%E7%B1%BB%E5%9E%8B): 資源類型, ex: pod, deploy, svc...
* NAME: 資源的名稱
* flags: 可選的參數

# kubectx & kubens
```
brew install kubectx
sudo apt install kubectx
choco install kubens kubectx
```

# example
```
kubectl version --short
kubectl cluster-info
kubectl config

kubectx -h
kubectx
kubectx s2
kubectx -
kubectl -d s2

kubens -h
kubectl create ns abc
kubens
kubens abc
kubens default
kubens -d abc
```

# pod
```
kubectl run w1 --image nginx:1.21.6-alpine --port 80
kubectl get pod -o wide
kubectl describe pod w1
kubectl logs -f w1
kubectl port-forward w1 8080:80
kubectl delete pod w1
```

# deploy
```
kubectl create deploy w2 --image nginx:1.21.6-alpine --port 80 --replicas 3
watch kubectl get pod
watch 'kubectl describe deploy w2 | tail -n 5'
kubectl export deploy w2 --port 8080 --target-port 80 --type LoadBalancer
kubectl scale deploy w2 --replicas 5
kubectl delete deploy,svc --all
```

# YAML
* [安裝 vscode](https://code.visualstudio.com/)
* [安裝 kubernetes extension](https://marketplace.visualstudio.com/items?itemName=ms-kubernetes-tools.vscode-kubernetes-tools)
```
kubectl apply -f .
```