Kubernetes入門,使用minikube 搭建本地k8s 環境

平凡鍵客發表於2021-05-19

這是一篇 K8S 的 HelloWorld,在學習K8S官方文件時搭建環境搭建的一個記錄,照著文件下來還是比較順利的。

一、安裝kubectl

下載 kubectl
curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"

下載 checksum
curl -LO "https://dl.k8s.io/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl.sha256"

檢查sha265sum
arvin@ubuntu:~$ echo "$(<kubectl.sha256) kubectl" | sha256sum --check
kubectl: OK

安裝 
sudo install -o root -g root -m 0755 kubectl /usr/local/bin/kubectl

安裝結果
arvin@ubuntu:~$ kubectl version --client
Client Version: version.Info{Major:"1", Minor:"21", GitVersion:"v1.21.1", GitCommit:"5e58841cce77d4bc13713ad2b91fa0d961e69192", GitTreeState:"clean", BuildDate:"2021-05-12T14:18:45Z", GoVersion:"go1.16.4", Compiler:"gc", Platform:"linux/amd64"}

二、安裝minikube

minikube是本地的Kubernetes,致力於使Kubernetes易於學習和開發。

 下載minikube
 curl -LO https://storage.googleapis.com/minikube/releases/latest/minikube-linux-amd64
 安裝
 sudo install minikube-linux-amd64 /usr/local/bin/minikube

三、啟動minikube

minikube start

四、碰到的問題

1.提示docker 驅動不能與管理員許可權一起使用

arvin@ubuntu:~$ sudo minikube start
? minikube v1.20.0 on Ubuntu 20.10
✨ Automatically selected the docker driver. Other choices: none, ssh
? The "docker" driver should not be used with root privileges.
? If you are running minikube within a VM, consider using --driver=none:
? https://minikube.sigs.k8s.io/docs/reference/drivers/none/

❌ Exiting due to DRV_AS_ROOT: The "docker" driver should not be used with root privileges.

2.提示docker 沒有許可權

arvin@ubuntu:~$ minikube start
? minikube v1.20.0 on Ubuntu 20.10
? Unable to pick a default driver. Here is what was considered, in preference order:
▪ podman: Not installed: exec: "podman": executable file not found in $PATH
▪ virtualbox: Not installed: unable to find VBoxManage in $PATH
▪ vmware: Not installed: exec: "docker-machine-driver-vmware": executable file not found in $PATH
▪ docker: Not healthy: "docker version --format {{.Server.Os}}-{{.Server.Version}}" exit status 1: Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Get http://%2Fvar%2Frun%2Fdocker.sock/v1.24/version: dial unix /var/run/docker.sock: connect: permission denied
▪ kvm2: Not installed: exec: "virsh": executable file not found in $PATH

❌ Exiting due to DRV_NOT_DETECTED: No possible driver was detected. Try specifying --driver, or see https://minikube.sigs.k8s.io/docs/start/

查閱docker 手冊

The docker daemon binds to a Unix socket instead of a TCP port. By
default that Unix socket is owned by the user root and other users can
only access it using sudo. The docker daemon always runs as the root
user.

If you don’t want to use sudo when you use the docker command, create
a Unix group called docker and add users to it. When the docker daemon
starts, it makes the ownership of the Unix socket read/writable by the
docker group.

解決辦法

arvin@ubuntu:~$ sudo groupadd docker    #新增docker使用者組
groupadd: group 'docker' already exists
arvin@ubuntu:~$ sudo gpasswd -a $USER docker #將登陸使用者加入到docker使用者組中
Adding user arvin to group docker
arvin@ubuntu:~$ newgrp docker  #更新使用者組

五、執行minikube

成功啟動

arvin@ubuntu:~$ minikube start
?  minikube v1.20.0 on Ubuntu 20.10
✨  Automatically selected the docker driver. Other choices: none, ssh
?  Starting control plane node minikube in cluster minikube
?  Pulling base image ...
?  Downloading Kubernetes v1.20.2 preload ...
    > preloaded-images-k8s-v10-v1...: 491.71 MiB / 491.71 MiB  100.00% 3.31 MiB
    > index.docker.io/kicbase/sta...: 358.10 MiB / 358.10 MiB  100.00% 1.39 MiB
❗  minikube was unable to download gcr.io/k8s-minikube/kicbase:v0.0.22, but successfully downloaded kicbase/stable:v0.0.22 as a fallback image
?  Creating docker container (CPUs=2, Memory=2200MB) ...
❗  This container is having trouble accessing https://k8s.gcr.io
?  To pull new external images, you may need to configure a proxy: https://minikube.sigs.k8s.io/docs/reference/networking/proxy/
?  Preparing Kubernetes v1.20.2 on Docker 20.10.6 ...
    ▪ Generating certificates and keys ...
    ▪ Booting up control plane ...
    ▪ Configuring RBAC rules ...
?  Verifying Kubernetes components...
    ▪ Using image gcr.io/k8s-minikube/storage-provisioner:v5
?  Enabled addons: storage-provisioner, default-storageclass
?  Done! kubectl is now configured to use "minikube" cluster and "default" namespace by default

檢視kuberners 狀態

minikube dashboard --url
?  Verifying dashboard health ...
?  Launching proxy ...
?  Verifying proxy health ...
http://127.0.0.1:34235/api/v1/namespaces/kubernetes-dashboard/services/http:kubernetes-dashboard:/proxy/

六、部署Demo

建立一個develpment 
kubectl create deployment hello-minikube --image=k8s.gcr.io/echoserver:1.4

kubectl expose deployment hello-minikube --type=NodePort --port=8080

arvin@ubuntu:~$ kubectl get services hello-minikube
NAME             TYPE       CLUSTER-IP      EXTERNAL-IP   PORT(S)          AGE
hello-minikube   NodePort   10.96.129.107   <none>        8080:31559/TCP   46s

arvin@ubuntu:~$ minikube service hello-minikube
|-----------|----------------|-------------|---------------------------|
| NAMESPACE |      NAME      | TARGET PORT |            URL            |
|-----------|----------------|-------------|---------------------------|
| default   | hello-minikube |        8080 | http://192.168.49.2:30064 |
|-----------|----------------|-------------|---------------------------|
?  Opening service default/hello-minikube in default browser...

發現網頁無法訪問
檢視pod資訊
arvin@ubuntu:~$ kubectl get pods  -o wide
NAME                              READY   STATUS             RESTARTS   AGE   IP           NODE       NOMINATED NODE   READINESS GATES
hello-minikube-6ddfcc9757-njfpc   0/1     ImagePullBackOff   0          13m   172.17.0.5   minikube   <none>           <none>

發現處於imagepullbackoff 狀態
檢視pod 詳細描述
arvin@ubuntu:~$ kubectl describe pod
Name:         hello-minikube-6ddfcc9757-njfpc
Namespace:    default
Priority:     0
Node:         minikube/192.168.49.2
Start Time:   Wed, 19 May 2021 00:38:52 +0800
Labels:       app=hello-minikube
              pod-template-hash=6ddfcc9757
Annotations:  <none>
Status:       Pending
IP:           172.17.0.5
IPs:
  IP:           172.17.0.5
Controlled By:  ReplicaSet/hello-minikube-6ddfcc9757
Containers:
  echoserver:
    Container ID:   
    Image:          k8s.gcr.io/echoserver:1.4
    Image ID:       
    Port:           <none>
    Host Port:      <none>
    State:          Waiting
      Reason:       ImagePullBackOff
    Ready:          False
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-9rdjm (ro)
Conditions:
  Type              Status
  Initialized       True 
  Ready             False 
  ContainersReady   False 
  PodScheduled      True 
Volumes:
  default-token-9rdjm:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-9rdjm
    Optional:    false
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  15m                   default-scheduler  Successfully assigned default/hello-minikube-6ddfcc9757-njfpc to minikube
  Normal   Pulling    12m (x4 over 15m)     kubelet            Pulling image "k8s.gcr.io/echoserver:1.4"
  Warning  Failed     12m (x4 over 14m)     kubelet            Failed to pull image "k8s.gcr.io/echoserver:1.4": rpc error: code = Unknown desc = Error response from daemon: Get https://k8s.gcr.io/v2/: net/http: request canceled while waiting for connection (Client.Timeout exceeded while awaiting headers)
  Warning  Failed     12m (x4 over 14m)     kubelet            Error: ErrImagePull
  Warning  Failed     12m (x6 over 14m)     kubelet            Error: ImagePullBackOff
  Normal   BackOff    4m56s (x35 over 14m)  kubelet            Back-off pulling image "k8s.gcr.io/echoserver:1.4"

發現是缺少映象 
minikube ssh 
docker images 

arvin@ubuntu:~$ minikube ssh
Last login: Tue May 18 16:55:58 2021 from 192.168.49.1
docker@minikube:~$ docker images
REPOSITORY                                TAG        IMAGE ID       CREATED         SIZE
gcr.io/k8s-minikube/storage-provisioner   v5         6e38f40d628d   7 weeks ago     31.5MB
k8s.gcr.io/kube-proxy                     v1.20.2    43154ddb57a8   4 months ago    118MB
k8s.gcr.io/kube-controller-manager        v1.20.2    a27166429d98   4 months ago    116MB
k8s.gcr.io/kube-apiserver                 v1.20.2    a8c2fdb8bf76   4 months ago    122MB
k8s.gcr.io/kube-scheduler                 v1.20.2    ed2c44fbdd78   4 months ago    46.4MB
kubernetesui/dashboard                    v2.1.0     9a07b5b4bfac   5 months ago    226MB
k8s.gcr.io/etcd                           3.4.13-0   0369cf4303ff   8 months ago    253MB
k8s.gcr.io/coredns                        1.7.0      bfe3a36ebd25   11 months ago   45.2MB
kubernetesui/metrics-scraper              v1.0.4     86262685d9ab   13 months ago   36.9MB
k8s.gcr.io/pause  

發現沒有我們剛才部署的映象,這裡我們下載一個映象進行重新部署測試
下載映象

docker@minikube:~$ docker pull cilium/echoserver
Using default tag: latest
latest: Pulling from cilium/echoserver
a6014dd53961: Pull complete 
fedc7896051b: Pull complete 
5500b395a348: Pull complete 
880bf53d0210: Pull complete 
94791026eeca: Pull complete 
d51579691189: Pull complete 
7fd34bf14970: Pull complete 
4b12f3ef8e65: Pull complete 
b0e3c31807a2: Pull complete 
e0962580d825: Pull complete 
46b541e4c252: Pull complete 
Digest: sha256:d6bd1dee4502cc50a974a97563330b4caaa2ac5b00a20ad2b82f4aa0e25e14fe
Status: Downloaded newer image for cilium/echoserver:latest
docker.io/cilium/echoserver:latest

部署新的echoserver
kubectl create deployment testechoserver --image=cilium/echoserver
deployment.apps/testechoserver created

arvin@ubuntu:~$ kubectl expose deployment testechoserver --type=NodePort --port=8080
service/testechoserver exposed

檢視部署狀態 
arvin@ubuntu:~$ kubectl get deployment
NAME             READY   UP-TO-DATE   AVAILABLE   AGE
hello-minikube   0/1     1            0           26m
testechoserver   1/1     1            1           2m12s

檢視建立的服務 
arvin@ubuntu:~$ kubectl get services testechoserver
NAME             TYPE       CLUSTER-IP      EXTERNAL-IP   PORT(S)          AGE
testechoserver   NodePort   10.106.69.154   <none>        8080:32617/TCP   2m3s

設定埠轉發
arvin@ubuntu:~$ kubectl port-forward service/testechoserver 7080:8080
Forwarding from 127.0.0.1:7080 -> 8080
Forwarding from [::1]:7080 -> 8080

使用curl 檢視資訊
arvin@ubuntu:~$ curl http://127.0.0.1:7080


Hostname: testechoserver-5668cd9764-jslfz

Pod Information:
	-no pod information available-

Server values:
	server_version=nginx: 1.13.3 - lua: 10008

Request Information:
	client_address=::ffff:127.0.0.1
	method=GET
	real path=/
	query=
	request_version=1.1
	request_scheme=http
	request_uri=http://127.0.0.1:8080/

Request Headers:
	accept=*/*
	host=127.0.0.1:7080
	user-agent=curl/7.68.0

Request Body:
	-no body in request-

七、管理叢集

minikube 的一些命令

暫停叢集而不影響部署的應用程式
minikube pause 

停止叢集,相對應的是minikube start啟動叢集
minikube stop 

設定記憶體大小為2048MB,設定後建立新的叢集會使用改配置
minikube config set memory 2048 

檢視擴充套件外掛資訊
minikube addons list 

刪除叢集
minikube delete 

具體可根據minikube --help 檢視學習 

相關文章