方法一:命令執(zhí)行生成nginx.yaml 和 nginx-web.yaml文件
- 生成yaml配置文件
kubectl create deployment web --image=nginx -o yaml --dry-run >> nginx.yaml
- 使用yaml文件進行部署
kubectl apply -f nginx.yaml
- 查看創(chuàng)建的pod ---- kubectl get pods
[root@k8s-master ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
web-96d5df5c8-ddbp4 0/1 ContainerCreating 0 7s
- 對外暴露訪問端口有咨,生成yaml配置文件
對外暴露的訪問端口為yaml文件的NodePort 參數(shù)值
kubectl expose deployment web --port=80 --type=NodePort --target-port=80 --name=web1 -o yaml >> nginx-web1.yaml
- 查看pod和svc ---- kubectl get pod,svc
[root@k8s-master ~]# kubectl get pod,svc
NAME READY STATUS RESTARTS AGE
pod/web-96d5df5c8-ddbp4 0/1 ContainerCreating 0 29s
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
service/kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 42h
service/web1 NodePort 10.100.138.209 <none> 80:32459/TCP 14s
-
訪問nginx服務,查看上面生成的nginx-web.yaml文件,訪問端口為32499巧娱,且虛擬機IP地址為192.168.36.137沈自,所以在瀏覽器的訪問地址為192.168.36.137:32499
也可以使用命令curl localhost:32459 在虛擬機本機訪問稚伍,返回頁面信息則表示成功
[root@k8s-master ~]# curl localhost:32459
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
body {
width: 35em;
margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif;
}
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>
<p>For online documentation and support please refer to
<a >nginx.org</a>.<br/>
Commercial support is available at
<a >nginx.com</a>.</p>
<p><em>Thank you for using nginx.</em></p>
</body>
</html>
方法二:手動編寫yaml文件
- 編寫配置文件web-nginx.yaml
# ./web-nginx.yml
apiVersion: apps/v1
kind: Deployment
metadata:
name: web-nginx
namespace: default
spec:
replicas: 5
selector:
matchLabels:
type: web
template:
metadata:
labels:
type: web
spec:
containers:
- name: web-nginx
image: nginx:1.17.6-alpine
---
apiVersion: v1
kind: Service
metadata:
name: web-nginx-entrypoint
namespace: default
spec:
type: NodePort
selector:
type: web
ports:
- port: 80
targetPort: 80
nodePort: 30001
- 編寫deploy-web-nginx.yml
# ./deploy-web-nginx.yml
---
- name: 部署 Nginx Pods
gather_facts: no
hosts: all[0]
tasks:
- name: 上傳 nginx podspec 文件到控制面板
copy:
src: ./web-nginx.yml
dest: ~/web-nginx.yml
- name: 部署 nginx pods
shell: kubectl apply -f ~/web-nginx.yml
- name: 暫停 10s疼蛾,等待部署完成
pause:
seconds: 10
- name: 羅列集群當前的 deployments
shell: kubectl get deployments
- name: 羅列集群當前的 services
shell: kubectl get services
- name: 羅列集群當前正在運行的 pods
shell: kubectl get pods --all-namespaces
- 執(zhí)行命令
ansible-playbook -i hosts.ini -v deploy-web-nginx.yml
現(xiàn)在如果登錄控制面板服務器,執(zhí)行 curl localhost:30001 就能看到 nginx 默認的 html 輸出內容了愉舔,這也證明了我們的 K8S 搭建成功了