部署nginx服务测试k8s集群

方法一:命令执行生成nginx.yaml 和 nginx-web.yaml文件
  1. 生成yaml配置文件
kubectl create deployment web --image=nginx -o yaml --dry-run >> nginx.yaml
  1. 使用yaml文件进行部署
kubectl apply -f nginx.yaml
  1. 查看创建的pod ---- kubectl get pods
[root@k8s-master ~]# kubectl get pods
NAME                  READY   STATUS              RESTARTS   AGE
web-96d5df5c8-ddbp4   0/1     ContainerCreating   0          7s
  1. 对外暴露访问端口,生成yaml配置文件
    对外暴露的访问端口为yaml文件的NodePort 参数值
kubectl expose deployment web --port=80 --type=NodePort --target-port=80 --name=web1 -o yaml >> nginx-web1.yaml
  1. 查看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                443/TCP        42h
service/web1         NodePort    10.100.138.209           80:32459/TCP   14s

  1. 访问nginx服务,查看上面生成的nginx-web.yaml文件,访问端口为32499,且虚拟机IP地址为192.168.36.137,所以在浏览器的访问地址为192.168.36.137:32499


    image.png

也可以使用命令curl localhost:32459 在虚拟机本机访问,返回页面信息则表示成功

[root@k8s-master ~]# curl localhost:32459



Welcome to nginx!



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.

方法二:手动编写yaml文件
  1. 编写配置文件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
  1. 编写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
  1. 执行命令
ansible-playbook -i hosts.ini -v deploy-web-nginx.yml

现在如果登录控制面板服务器,执行 curl localhost:30001 就能看到 nginx 默认的 html 输出内容了,这也证明了我们的 K8S 搭建成功了

你可能感兴趣的:(部署nginx服务测试k8s集群)