Kubernetes 通過資源配置運行容器
我們知道通過 run
命令啓動容器非常麻煩,Docker 提供了 Compose 爲我們解決了這個問題。那 Kubernetes 是如何解決這個問題的呢?其實很簡單,使用 kubectl create
命令就可以做到和 Compose 一樣的效果了,該命令可以通過配置文件快速創建一個集羣資源對象。
創建容器
以部署nginx爲例
在master機器上操作
創建一個文件夾,存放yml配置
mkdir -p /usr/local/k8s/nginx && cd /usr/local/k8s/nginx
創建nginx-deployment.yml配置
vim nginx-deployment.yml
內容如下
注意: extensions/v1beta1
不再支持部署 Deployment
,並且修改了少量命令
k8s v1.16.0 之前的版本
# Api版本號
apiVersion: extensions/v1beta1
# 類型,如:Pod/ReplicationController/Deployment/Service/Ingress
kind: Deployment
# 元數據
metadata:
# kind的名稱
name: nginx-app
spec:
# 部署實例數量
replicas: 2
template:
metadata:
labels:
# 容器標籤的名字
name: nginx
spec:
# 配置容器
containers:
# 容器名稱
- name: nginx
# 容器鏡像,必須指定鏡像版本,不能省略,不能爲lastest
image: nginx:1.17
# 鏡像拉取策略:只有鏡像不存在時才拉取
imagePullPolicy: IfNotPresent
# 暴露端口
ports:
# pod 端口
- containerPort: 80
k8s v1.16之後的版本
# API 版本號:由 extensions/v1beta1 修改爲 apps/v1
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-app
spec:
# 增加了選擇器配置
selector:
matchLabels:
app: nginx
replicas: 2
template:
metadata:
labels:
# 設置標籤由 name 修改爲 app
app: nginx
spec:
containers:
- name: nginx
image: nginx
ports:
- containerPort: 80
部署
kubectl create -f nginx-deployment.yml
查看容器
kubectl get pods
查看部署
kubectl get deployments
刪除部署
kubectl delete -f nginx-deployment.yml
發佈service
創建nginx-service.yml
(也可以在nginx-deployment.yml文件後面追加配置)
vim nginx-deployment.yml
添加內容
# k8s v1.16.0 之前
# API 版本號
apiVersion: v1
# 類型,如:Pod/ReplicationController/Deployment/Service/Ingress
kind: Service
# 元數據
metadata:
# Kind 的名稱
name: nginx-http
spec:
# 暴露端口
ports:
## Service 暴露的端口
- port: 80
## Pod 上的端口,這裏是將 Service 暴露的端口轉發到 Pod 端口上
targetPort: 80
# 類型
type: LoadBalancer
# 標籤選擇器
selector:
# 需要和上面部署的 Deployment 標籤名對應
name: nginx
*k8s v1.16.0 之前後
# k8s v1.16.0 之後
apiVersion: v1
kind: Service
metadata:
name: nginx-http
spec:
ports:
- port: 80
targetPort: 80
type: LoadBalancer
selector:
# 標籤選擇器由 name 修改爲 app
app: nginx
部署
kubectl create -f nginx-deployment.yml
kubectl create -f nginx-service.yml
查看服務
kubectl get service
瀏覽器中訪問
主機ip:30878
刪除service
kubectl delete -f nginx-service.yml