使用Rancher搭建Kubernetes集群

生活中,最使人疲惫的往往不是道路的遥远,而是心中的郁闷;最使人痛苦的往往不是生活的不幸,而是希望的破灭;最使人颓废的往往不是前途的坎坷,而是自信的丧失;最使人绝望的往往不是挫折的打击,而是心灵的死亡。所以我们要有自己的梦想,让梦想的星光指引着我们走出落漠,走出惆怅,带着我们走进自己的理想。

导读:本篇文章讲解 使用Rancher搭建Kubernetes集群,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

Rancher搭建Kubernetes集群

kubernetes有多种部署方式,已知的主要有kind、minikube、kubeadm、二进制包、Rancher

官网:https://kubernetes.io/zh/

中文社区: https://www.kubernetes.org.cn/

Rancher概述

Rancher是一个开源的企业级容器管理平台。使用Rancher,不必再从头搭建容器服务平台。

Rancher提供了在生产环境中使用的管理Docker和Kubernetes的全栈化容器部署与管理平台。

Rancher是K8S可视化管理工具,Rancher已经内置K8S,无需再额外安装,直接使用。

在这里插入图片描述

Rancher的安装

拉取镜像

docker pull rancher/rancher:v2.5.12

启动容器

docker run -p 80:80 -p 443:443 --name rancher --restart=unless-stopped --privileged -d rancher/rancher:v2.5.12

注意:Rancher 2.5.x 及之后的版本,需要添加–privileged标志变量,启用特权模式安装

Rancher的初始配置及概览

访问Rancher的主页,第一次需要设置管理员(admin)账号密码

在这里插入图片描述
设置Rancher的Server URL,其他Node都可以访问到的地址
在这里插入图片描述

进入Rancher首页,默认安装了k3s的集群
在这里插入图片描述
点击集群名称可以查看集群状态信息
在这里插入图片描述
点击仪表盘按钮,查看集群的各种Dashboard
在这里插入图片描述

Rancher应用部署

方式一

在这里插入图片描述
在这里插入图片描述
填写表单信息进行部署
在这里插入图片描述
导入YAML文件部署
在这里插入图片描述

在这里插入图片描述

方式二

1.创建Deployment对象

找到Deployments->Create-> Edit as YAML
在这里插入图片描述
在这里插入图片描述
填写deployment.yaml信息
在这里插入图片描述
2.创建Service暴露端口信息
在这里插入图片描述
在这里插入图片描述
填写service.yaml信息
在这里插入图片描述

Rancher部署MySQL应用

创建Deployment

# API版本
apiVersion: apps/v1
# API对象类型
kind: Deployment
metadata:
  # 指定Deployment的名称
  name: mysql-deployment
  # 指定Deployment的空间,否则会无法创建
  namespace: default
  # 指定Deployment的标签 
  labels:
    app: mysql
spec:
  # 指定创建的Pod副本数量 
  replicas: 1
  # 定义如何查找要管理的Pod
  selector:
    # 管理标签app为mysql的Pod
    matchLabels:
      app: mysql
  # 指定创建Pod的模板
  template:
    metadata:
      # 给Pod打上app:mysql标签
      labels:
        app: mysql
    # Pod的模板规约
    spec:
      containers:
        - name: mysql
          # 指定容器镜像
          image: mysql:5.7
          # 指定开放的端口
          ports:
            - containerPort: 3306
          # 设置环境变量
          env:
            - name: MYSQL_ROOT_PASSWORD
              value: root123456
          # 使用存储卷
          volumeMounts:
            # 将存储卷挂载到容器内部路径
            - mountPath: /var/log/mysql
              name: log-volume
            - mountPath: /var/lib/mysql
              name: data-volume
            - mountPath: /etc/mysql
              name: conf-volume
      # 定义存储卷
      volumes:
        - name: log-volume
          # hostPath类型存储卷在宿主机上的路径
          hostPath:
            path: /usr/local/program/mysql/log
            # 当目录不存在时创建
            type: DirectoryOrCreate
        - name: data-volume
          hostPath:
            path: /usr/local/program/mysql/data
            type: DirectoryOrCreate
        - name: conf-volume
          hostPath:
            path: /usr/local/program/mysql/conf
            type: DirectoryOrCreate

在这里插入图片描述
在这里插入图片描述

创建Service

apiVersion: v1
kind: Service
metadata:
  # 定义空间
  namespace: default
  # 定义服务名称,其他Pod可以通过服务名称作为域名进行访问
  name: mysql-service
spec:
  # 指定服务类型,通过Node上的静态端口暴露服务
  type: NodePort
  # 管理标签app为mysql的Pod
  selector:
    app: mysql
  ports:
    - name: http
      protocol: TCP
      port: 3307
      targetPort: 3306
      # Node上的静态端口
      nodePort: 30303

访问测试

获取Rancher容器IP地址

[root@administrator ~]# docker inspect rancher |grep IPAddress
            "SecondaryIPAddresses": null,
            "IPAddress": "172.17.0.2",
                    "IPAddress": "172.17.0.2",

连接数据库

[root@administrator ~]# mysql -h 172.17.0.2 -P 30303 -uroot -proot123456
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.7.37 MySQL Community Server (GPL)

Copyright (c) 2000, 2021, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

Rancher部署SpringBoot应用

创建Deployment

apiVersion: apps/v1
kind: Deployment
metadata:
  namespace: default
  name: jar-deployment
  labels:
    app: jar-test
spec:
  replicas: 1
  selector:
    matchLabels:
      app: jar-test
  template:
    metadata:
      labels:
        app: jar-test
    spec:
      containers:
        - name: jar-name
          # 指定Docker Hub中的镜像地址
          image: IP/jar-test:0.0.1-SNAPSHOT
          ports:
            - containerPort: 8080
          env:
            # 指定数据库连接地址
            - name: spring.datasource.url
              value: jdbc:mysql://mysql-service:3307/demo?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
            - name: logging.path
              value: /var/logs
          volumeMounts:
            - mountPath: /var/logs
              name: log-volume
      volumes:
        - name: log-volume
          hostPath:
            path: /usr/local/program/app/logs
            type: DirectoryOrCreate

创建Service

apiVersion: v1
kind: Service
metadata:
  namespace: default
  name: jar-service
spec:
  type: NodePort
  selector:
    app: jar-test
  ports:
    - name: http
      protocol: TCP
      port: 8080
      targetPort: 8080
      # Node上的静态端口
      nodePort: 30001

访问测试

curl http://172.17.0.2:30001index.html

添加集群

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在master节点运行命令导入rancher
在这里插入图片描述
在这里插入图片描述

Kubernetes基本操作

应用部署

创建一个名称为nginx-test的Deployment,同时指定应用镜像

kubectl create deployment nginx-test --image=nginx

查看所有Deployment:kubectl get deployments

NAME         READY   UP-TO-DATE   AVAILABLE   AGE
nginx-test   1/1     1            1           18s

删除部署应用

kubectl delete deployment  nginx-test

查看应用信息

查看所有Pod的状态:kubectl get pods

NAME                          READY   STATUS    RESTARTS   AGE
nginx-test-84b478f9c5-vz7bw   1/1     Running   0          29s

查看Pod的详细状态:kubectl describe pods

Name:         nginx-test-84b478f9c5-vz7bw
Namespace:    default
Priority:     0
Node:         minikube/192.168.49.2
Start Time:   Tue, 22 Mar 2022 09:03:09 +0800
Labels:       app=nginx-test
              pod-template-hash=84b478f9c5
Annotations:  <none>
Status:       Running
IP:           172.17.0.3
IPs:
  IP:           172.17.0.3
Controlled By:  ReplicaSet/nginx-test-84b478f9c5
Containers:
  nginx:
    Container ID:   docker://8f20af263a8c7dce564fa6d49943fbef4fe151aaaef24e3564e57e13787c7213
    Image:          nginx
    Image ID:       docker-pullable://nginx@sha256:e1211ac17b29b585ed1aee166a17fad63d344bc973bc63849d74c6452d549b3e
    Port:           <none>
    Host Port:      <none>
    State:          Running
      Started:      Tue, 22 Mar 2022 09:03:13 +0800
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-2hldl (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             True
  ContainersReady   True
  PodScheduled      True
Volumes:
  kube-api-access-2hldl:
    Type:                    Projected (a volume that contains injected data from multiple sources)
    TokenExpirationSeconds:  3607
    ConfigMapName:           kube-root-ca.crt
    ConfigMapOptional:       <nil>
    DownwardAPI:             true
QoS Class:                   BestEffort
Node-Selectors:              <none>
Tolerations:                 node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                             node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:
  Type    Reason     Age   From               Message
  ----    ------     ----  ----               -------
  Normal  Scheduled  39s   default-scheduler  Successfully assigned default/nginx-test-84b478f9c5-vz7bw to minikube
  Normal  Pulling    39s   kubelet            Pulling image "nginx"
  Normal  Pulled     36s   kubelet            Successfully pulled image "nginx" in 2.952573727s
  Normal  Created    35s   kubelet            Created container nginx
  Normal  Started    35s   kubelet            Started container nginx

将Pod名称设置为环境变量,方便使用$POD_NAME来应用Pod的名称

export NGINX_POD=nginx-test-84b478f9c5-vz7bw

查看Pod打印的日志:kubectl logs $NGINX_POD

/docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
/docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
/docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
10-listen-on-ipv6-by-default.sh: info: Getting the checksum of /etc/nginx/conf.d/default.conf
10-listen-on-ipv6-by-default.sh: info: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf
/docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
/docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh
/docker-entrypoint.sh: Configuration complete; ready for start up
2022/03/22 01:03:13 [notice] 1#1: using the "epoll" event method
2022/03/22 01:03:13 [notice] 1#1: nginx/1.21.6
2022/03/22 01:03:13 [notice] 1#1: built by gcc 10.2.1 20210110 (Debian 10.2.1-6)
2022/03/22 01:03:13 [notice] 1#1: OS: Linux 3.10.0-1160.59.1.el7.x86_64
2022/03/22 01:03:13 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1048576:1048576
2022/03/22 01:03:13 [notice] 1#1: start worker processes
2022/03/22 01:03:13 [notice] 1#1: start worker process 32
2022/03/22 01:03:13 [notice] 1#1: start worker process 33

使用exec在Pod的容器中执行命令

kubectl exec nginx-test-84b478f9c5-vz7bw -- echo hello world

进入容器内部并执行bash命令,退出容器使用exit命令

kubectl exec -it nginx-test-84b478f9c5-vz7bw  -- bash

公开暴露应用

默认Pod无法被集群外部访问,需要创建Service并暴露端口才能被外部访问。

创建Service暴露nginx-test这个Deployment,通过NodePort属性得到暴露到外部的端口

kubectl expose deployment nginx-test  --type=NodePort --port 80

查看所有Service的状态:kubectl get services

NAME         TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)        AGE
kubernetes   ClusterIP   10.96.0.1       <none>        443/TCP        16h
nginx-test   NodePort    10.101.176.18   <none>        80:32299/TCP   77s

查看Service的详情

kubectl describe services nginx-test

访问服务:IP:32299

Name:                     nginx-test
Namespace:                default
Labels:                   app=nginx-test
Annotations:              <none>
Selector:                 app=nginx-test
Type:                     NodePort
IP Family Policy:         SingleStack
IP Families:              IPv4
IP:                       10.101.176.18
IPs:                      10.101.176.18
Port:                     <unset>  80/TCP
TargetPort:               80/TCP
NodePort:                 <unset>  32299/TCP
Endpoints:                172.17.0.3:80
Session Affinity:         None
External Traffic Policy:  Cluster
Events:                   <none>

标签的使用

通过给资源添加Label,可以方便地管理资源

查看Deployment中所包含的Label:kubectl describe deployment

Name:                   nginx-test
Namespace:              default
CreationTimestamp:      Tue, 22 Mar 2022 09:03:09 +0800
Labels:                 app=nginx-test
Annotations:            deployment.kubernetes.io/revision: 1
Selector:               app=nginx-test
Replicas:               1 desired | 1 updated | 1 total | 1 available | 0 unavailable
StrategyType:           RollingUpdate
MinReadySeconds:        0
RollingUpdateStrategy:  25% max unavailable, 25% max surge
Pod Template:
  Labels:  app=nginx-test
  Containers:
   nginx:
    Image:        nginx
    Port:         <none>
    Host Port:    <none>
    Environment:  <none>
    Mounts:       <none>
  Volumes:        <none>
Conditions:
  Type           Status  Reason
  ----           ------  ------
  Available      True    MinimumReplicasAvailable
  Progressing    True    NewReplicaSetAvailable
OldReplicaSets:  <none>
NewReplicaSet:   nginx-test-84b478f9c5 (1/1 replicas created)
Events:
  Type    Reason             Age   From                   Message
  ----    ------             ----  ----                   -------
  Normal  ScalingReplicaSet  32m   deployment-controller  Scaled up replica set nginx-test-84b478f9c5 to 1

通过Label查询Pod:kubectl get pods -l app=nginx-test

NAME                          READY   STATUS    RESTARTS   AGE
nginx-test-84b478f9c5-vz7bw   1/1     Running   0          34m

通过Label查询Service:kubectl get services -l app=nginx-test

NAME         TYPE       CLUSTER-IP      EXTERNAL-IP   PORT(S)        AGE
nginx-test   NodePort   10.101.176.18   <none>        80:32299/TCP   16m

给Pod添加Label:kubectl label pod nginx-test-84b478f9c5-vz7bw env_role=dev

查看Pod的详细信息:kubectl describe pods nginx-test-84b478f9c5-vz7bw

Name:         nginx-test-84b478f9c5-vz7bw
Namespace:    default
Priority:     0
Node:         minikube/192.168.49.2
Start Time:   Tue, 22 Mar 2022 09:03:09 +0800
Labels:       app=nginx-test
              env_role=dev

通过Label删除服务:kubectl delete service -l app=nginx-test

service "nginx-test" deleted

kubectl get service

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

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/136933.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!