最新最全詳細 在centos上使用 Minikube 安裝 Kubernetes 教程並運行nginx服務以及go http hello服務示例

最新最全詳細 在centos上使用 Minikube 安裝 Kubernetes 教程,在安裝完k8s單機集羣后並運行一個nginx服務 和一個go 的http hello server 服務

本文已更新到 Minikube v1.11.0/Kubernetes v1.18+

什麼是Minikube

  • Minikube 是一種可以讓您在本地輕鬆運行 Kubernetes 的工具。Minikube 在筆記本電腦上的虛擬機(VM)中運行單節點 Kubernetes 集羣,供那些希望嘗試 Kubernetes 或進行日常開發的用戶使用

    參考官方文檔:
    https://kubernetes.io/zh/docs/tasks/tools/install-minikube/

pis:

  • 官方的在國內不怎麼好使,使用都是google源,大部分被牆了,下面安裝都是使用國內的源進行安裝。
  • 安裝k8s對機器硬件系統有一定要求,2G 2核 20G好像是最低要求,小於這個配置會提示你安裝不了k8s集羣。具體看官方配置要求。
    參考:https://www.jianshu.com/p/ae6260bd5596

注意: 本文安裝教程是基於centos系統的。安裝之前可以把yum源更換爲國內阿里源,然後可以yum date一下
參考:https://blog.csdn.net/sinat_33384251/article/details/91404617

一、安裝安裝 kubectl

kubectl是Kubernetes集羣的命令行工具,用來操作集羣的。
在 Kubernetes 上使用 Kubernetes 命令行工具 kubectl 部署和管理應用程序。使用 kubectl,您可以檢查集羣資源;創建、刪除和更新組件;查看您的新集羣;並啓動實例應用程序。
官方參考:https://kubernetes.io/zh/docs/tasks/tools/install-kubectl/

國內安裝快速安裝kubectl
參考:https://www.jianshu.com/p/b58c85436f0a

配置k8s的kubelet yum源

cat <<EOF > /etc/yum.repos.d/kubernetes.repo
[kubernetes]
name=Kubernetes
baseurl=https://mirrors.aliyun.com/kubernetes/yum/repos/kubernetes-el7-x86_64
enabled=1
gpgcheck=1
repo_gpgcheck=1
gpgkey=https://mirrors.aliyun.com/kubernetes/yum/doc/yum-key.gpg https://mirrors.aliyun.com/kubernetes/yum/doc/rpm-package-key.gpg
EOF

yum安裝kubectl:

# 安裝
yum install -y kubectl kubelet kubeadm
# 開機啓動
systemctl enable kubelet
# 啓動
systemctl start kubelet

查看版本 kubectl version
我這安裝的是1.18.3版本

[root@localhost k8s]# kubectl version
Client Version: version.Info{Major:"1", Minor:"18", GitVersion:"v1.18.3", GitCommit:"2e7996e3e2712684bc73f0dec0200d64eec7fe40", GitTreeState:"clean", BuildDate:"2020-05-20T12:52:00Z", GoVersion:"go1.13.9", Compiler:"gc", Platform:"linux/amd64"}
The connection to the server localhost:8080 was refused - did you specify the right host or port?

二、先把docker安裝上吧

在安裝Minikube 之前把docker安裝好吧,如果docker版本比較則最好更新好最新的版本免得後面要安裝出現問題。
參考:https://www.runoob.com/docker/centos-docker-install.html

curl -fsSL https://get.docker.com | bash -s docker --mirror Aliyun

更改docker鏡像源
參考:https://www.jianshu.com/p/4002f93c87c4

vim /etc/docker/daemon.json #沒有則創建daemon.json文件
{
    "registry-mirrors":["你個人的加速器地址"]
}
#加速地址自行搜索阿里雲docker配置

我的:

root@localhost k8s]# vim /etc/docker/daemon.json
[root@localhost k8s]# cat /etc/docker/daemon.json
{
    "registry-mirrors":["https://qdsf52uj.mirror.aliyuncs.com"]
}

重啓docker

systemctl daemon-reload
systemctl restart docker

三、安裝 Minikube

minikube
阿里雲發佈的minikube
github地址:https://github.com/AliyunContainerService/minikube

curl -Lo minikube https://kubernetes.oss-cn-hangzhou.aliyuncs.com/minikube/releases/v1.11.0/minikube-linux-amd64 && chmod +x minikube && sudo mv minikube /usr/local/bin/

啓動單機集羣

我使用–driver=none模式

minikube start --driver=none

第一次需要一點時間下載,耐心等待吧…

[root@localhost k8s]# minikube start --driver=none
😄  minikube v1.11.0 on Centos 7.8.2003
✨  Using the none driver based on user configuration
👍  Starting control plane node minikube in cluster minikube
🤹  Running on localhost (CPUs=2, Memory=1819MB, Disk=17394MB) ...
ℹ️  OS release is CentOS Linux 7 (Core)
🐳  Preparing Kubernetes v1.18.3 on Docker 19.03.11 ...
    > kubeadm.sha256: 65 B / 65 B [--------------------------] 100.00% ? p/s 0s
    > kubelet.sha256: 65 B / 65 B [--------------------------] 100.00% ? p/s 0s
    > kubectl.sha256: 65 B / 65 B [--------------------------] 100.00% ? p/s 0s
    > kubeadm: 37.97 MiB / 37.97 MiB [------------] 100.00% 1011.17 KiB p/s 38s
    > kubectl: 41.99 MiB / 41.99 MiB [-------------] 100.00% 894.57 KiB p/s 48s
    > kubelet: 10.71 MiB / 108.04 MiB [>______] 9.91% 26.82 KiB p/s ETA 1h1m56s

出現錯誤:

/proc/sys/net/bridge/bridge-nf-call-iptables contents are not set to 1

解決方法:

[root@localhost k8s]# swapoff -a
[root@localhost k8s]#  echo 1 > /proc/sys/net/bridge/bridge-nf-call-iptables

看到下面信息就表示成功啓動k8s單機集羣了

[root@localhost k8s]# minikube start --driver=none
😄  minikube v1.11.0 on Centos 7.8.2003
✨  Using the none driver based on user configuration
👍  Starting control plane node minikube in cluster minikube
🤹  Running on localhost (CPUs=2, Memory=1819MB, Disk=17394MB) ...
ℹ️  OS release is CentOS Linux 7 (Core)
🐳  Preparing Kubernetes v1.18.3 on Docker 19.03.11 ...

🤹  Configuring local host environment ...

❗  The 'none' driver is designed for experts who need to integrate with an existing VM
💡  Most users should use the newer 'docker' driver instead, which does not require root!
📘  For more information, see: https://minikube.sigs.k8s.io/docs/reference/drivers/none/

❗  kubectl and minikube configuration will be stored in /root
❗  To use kubectl or minikube commands as your own user, you may need to relocate them. For example, to overwrite your own settings, run:

    ▪ sudo mv /root/.kube /root/.minikube $HOME
    ▪ sudo chown -R $USER $HOME/.kube $HOME/.minikube

💡  This can also be done automatically by setting the env var CHANGE_MINIKUBE_NONE_USER=true
🔎  Verifying Kubernetes components...
🌟  Enabled addons: default-storageclass, storage-provisioner
🏄  Done! kubectl is now configured to use "minikube"

打開Kubernetes控制檯

minikube dashboard

如果出現錯誤多執行幾次minikube dashboard: 因爲可能是容器沒完全拉下來

kubectl get pod --all-namespaces 查看是否全部拉下沒有 READY 狀態 1/1表完成 我下面0/1表示沒拉下。執行minikube dashboard直到都完全拉下來

kubectl get pod --all-namespaces
NAMESPACE              NAME                                            READY   STATUS             RESTARTS   AGE
kube-system            coredns-546565776c-lb46j                        0/1     Running            0          17m
kube-system            coredns-546565776c-sxfkw                        0/1     Running            0          17m
kube-system            etcd-localhost.localdomain                      1/1     Running            0          17m
kube-system            kube-apiserver-localhost.localdomain            1/1     Running            0          17m
kube-system            kube-controller-manager-localhost.localdomain   1/1     Running            0          17m
kube-system            kube-proxy-467j8                                1/1     Running            0          17m
kube-system            kube-scheduler-localhost.localdomain            1/1     Running            0          17m
kube-system            storage-provisioner                             1/1     Running            0          17m
kubernetes-dashboard   dashboard-metrics-scraper-84bfdf55ff-hdjhn      1/1     Running            0          13m
kubernetes-dashboard   kubernetes-dashboard-696dbcc666-tzzls           0/1     CrashLoopBackOff   7          13m

再次kubectl get pod --all-namespaces

[root@localhost ~]# kubectl get pod --all-namespaces
NAMESPACE              NAME                                            READY   STATUS             RESTARTS   AGE
kube-system            coredns-546565776c-lb46j                        1/1     Running            0          25m
kube-system            coredns-546565776c-sxfkw                        1/1     Running            0          25m
kube-system            etcd-localhost.localdomain                      1/1     Running            0          25m
kube-system            kube-apiserver-localhost.localdomain            1/1     Running            0          25m
kube-system            kube-controller-manager-localhost.localdomain   1/1     Running            0          25m
kube-system            kube-proxy-467j8                                1/1     Running            0          25m
kube-system            kube-scheduler-localhost.localdomain            1/1     Running            0          25m
kube-system            storage-provisioner                             1/1     Running            0          25m
kubernetes-dashboard   dashboard-metrics-scraper-84bfdf55ff-hdjhn      1/1     Running            0          21m
kubernetes-dashboard   kubernetes-dashboard-696dbcc666-tzzls           0/1     CrashLoopBackOff   8          21m

出現下面的信息表示完全啓動dashboard

 minikube dashboard
🤔  Verifying dashboard health ...
🚀  Launching proxy ...
🤔  Verifying proxy health ...



http://127.0.0.1:39798/api/v1/namespaces/kubernetes-dashboard/services/http:kubernetes-dashboard:/proxy/

通過apiserver訪問

對外暴露地址:

nohup kubectl proxy --port=8088 --address=‘192.168.1.128’ --accept-hosts=’^.*’ >/dev/null 2>&1 &
然後就可以在瀏覽器上訪問了:

http://192.168.1.128:8088/api/v1/namespaces/kubernetes-dashboard/services/http:kubernetes-dashboard:/proxy/

  • 完成安裝之後,我們就可以發佈,更新,回滾自己的程序。這個時候我們就需要了解Pod、ReplicaSet、Deployment、Service相關的概念。

使用k8s運行服務

1、運行nginx服務

創建第一個Deployment

  • 瞭解到只需要創建好Deployment就會自動完成ReplicaSet和pod。下面就創建一個Nginx的Deployment。

nginx-deployment.yaml文件內容

apiVersion: apps/v1 # for versions before 1.16.0 use extensions/v1beta1
kind: Deployment
metadata:
  name: nginx-deployment # deployment的名稱
spec:
  selector:
    matchLabels:
      app: nginx # 選擇器必須匹配 template中的metadata.labels
  replicas: 3 # tells deployment to run 3 pods matching the template
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.16.0
        ports:
        - containerPort: 80

創建deployment

kubectl create -f ./nginx-deployment.yaml --record

[root@localhost k8s]# kubectl create -f ./nginx-deployment.yaml --record
deployment.apps/nginx-deployment created

kubectl get deployments 查看

[root@localhost k8s]# kubectl get deployments
NAME               READY   UP-TO-DATE   AVAILABLE   AGE
nginx-deployment   3/3     3            3           62s
  • NAME 列出羣集中的部署名稱。
  • DESIRED 顯示應用程序的所需副本數,您在創建部署時定義這些副本。這是理想的狀態。
  • CURRENT 顯示當前正在運行的副本數量。
  • UP-TO-DATE 顯示已更新以實現所需狀態的副本數。
  • AVAILABLE 顯示用戶可以使用的應用程序副本數。
  • AGE 顯示應用程序運行的時間。

我們爲剛纔的nginx-deployment創建服務對象:

Service

一種抽象的方式暴露在一組運行的應用程序Pods作爲網絡服務。

使用Kubernetes,您無需修改​​應用程序即可使用不熟悉的服務發現機制。Kubernetes爲Pods提供了自己的IP地址和一組Pod的單個DNS名稱,並且可以在它們之間進行負載均衡。

nginx-service.yaml 文件內容

apiVersion: v1
kind: Service
metadata:
  name: nginx-service
spec:
  selector:
    app: nginx
  type: NodePort # 爲POD開放端口
  ports:
  - protocol: TCP
    port: 80
    nodePort: 30000 # 30000流量轉到80端口

執行kubectl apply -f nginx-service.yaml來創建Service

[root@localhost k8s]# kubectl apply -f nginx-service.yaml
service/nginx-service created

如果你使用的是minikube, 你通過minikube service nginx-service --url來獲取訪問入口

[root@localhost k8s]# minikube service nginx-service --url
http://192.168.1.128:30000

可以通過kubctl名來設置訪問的url

kubectl port-forward nginx-deployment-7d9d7464fb-mrc4h 30001:80

[root@localhost k8s]# kubectl port-forward nginx-deployment-9664d7db6-jfwvv  30001:80
Forwarding from 127.0.0.1:30001 -> 80
Forwarding from [::1]:30001 -> 80
  • ubectl port-forward需要的是pod名稱, 你可以通過kubectl get pods得到名稱.
[root@localhost k8s]# kubectl get pod
NAME                               READY   STATUS    RESTARTS   AGE
nginx-deployment-9664d7db6-jfwvv   1/1     Running   0          10m
nginx-deployment-9664d7db6-p9zhh   1/1     Running   0          10m
nginx-deployment-9664d7db6-wgxg7   1/1     Running   0          10m

2、運行自己的go http web服務

  • 創建自己的web服務
  • 創建服務的docker鏡像,需要些dockerfile文件
  • 部署服務到k8s

創建自己的web服務

server.go 文件

package main

import (
   "net/http"
   "log"
   "io"
)

func hello(w http.ResponseWriter,r *http.Request)  {
   io.WriteString(w,"hello, kubetnetes!\n")
}

func main() {
   http.HandleFunc("/hello",hello)
   err := http.ListenAndServe(":7070",nil)
   if err != nil {
      log.Panic(err)
   }
}

編譯之後可以運行起來。

[root@localhost src]# go build -o server server.go
[root@localhost src]# ./server
新開一個窗口進行curl,可以看到輸出了hello, kubetnetes!

[root@localhost ~]# curl 192.168.42.131:7070/hello
hello, kubetnetes!

創建服務docker鏡像

編寫Dockerfile

# Use the official Golang image to create a build artifact.
# https://hub.docker.com/_/golang
FROM golang:latest as builder

# Copy local code to the container image.
WORKDIR /root/k8s/godockerfile
COPY . .

RUN GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -o app http_server.go

# Use a Docker multi-stage build to create a lean production image.
# https://docs.docker.com/develop/develop-images/multistage-build/#use-multi-stage-builds
FROM alpine:latest

COPY --from=builder /root/k8s/godockerfile .

ENV PORT 7070

# Run the web service on container startup.
CMD ["./app"]

打包鏡像: docker build -t http_server.go:v1 .

[root@localhost dockerfile]# docker build -t server:v1 .
Sending build context to Docker daemon  3.584kB
Step 1/8 : FROM golang:latest as builder
 ---> 5fbd6463d24b
Step 2/8 : WORKDIR /root/k8s/godockerfile
 ---> Using cache
 ---> e493573ef164
Step 3/8 : COPY . .
 ---> 885e68693538
Step 4/8 : RUN GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -o app http_server.go
 ---> Running in 24a7027bdee3
Removing intermediate container 24a7027bdee3
 ---> c58ebb1735c1
Step 5/8 : FROM alpine:latest
latest: Pulling from library/alpine
df20fa9351a1: Pull complete 
Digest: sha256:185518070891758909c9f839cf4ca393ee977ac378609f700f60a771a2dfe321
Status: Downloaded newer image for alpine:latest
 ---> a24bb4013296
Step 6/8 : COPY --from=builder /root/k8s/godockerfile .
 ---> fc2c74b4c794
Step 7/8 : ENV PORT 7070
 ---> Running in 3b0dbbf02eea
Removing intermediate container 3b0dbbf02eea
 ---> c13bb216b91f
Step 8/8 : CMD ["./app"]
 ---> Running in a74c69d28545
Removing intermediate container a74c69d28545
 ---> 76bf3e25da25
Successfully built 76bf3e25da25
Successfully tagged server:v1

部署server到k8s

docker iamges 查看鏡像名

[root@localhost dockerfile]# docker images
REPOSITORY                                                                    TAG                 IMAGE ID            CREATED             SIZE
server                                                                        v1                  76bf3e25da25        3 minutes ago       13MB

使用 yaml 文件

touch hello-kubernetes.yaml
apiVersion: v1
kind: Service
metadata:
  name: hello-kubernetes
spec:
  selector:
    app: hello-kubernetes
  type: NodePort # 爲POD開放端口
  ports:
  - protocol: TCP
    port: 7070
    nodePort: 30001 # 30000流量轉到80端口
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: hello-kubernetes
spec:
  replicas: 1
  selector:
    matchLabels:
      app: hello-kubernetes
  template:
    metadata:
      labels:
        app: hello-kubernetes
    spec:
      containers:
      - name: hello-kubernetes
        image: server:v1
        imagePullPolicy: Never
        ports:
        - containerPort: 7070

執行部署

kubectl apply -f hello-kubernetes.yaml

root@localhost dockerfile]# kubectl apply -f hello-kubernetes.yaml
service/hello-kubernetes created
deployment.apps/hello-kubernetes created

kubectl get po 查看一下

[root@localhost dockerfile]# kubectl get svc
NAME               TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)          AGE
hello-kubernetes   NodePort    10.110.213.111   <none>        7070:30001/TCP   55s

kubectl get svc 查看一下

[root@localhost dockerfile]# kubectl get svc
NAME               TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)          AGE
hello-kubernetes   NodePort    10.110.213.111   <none>        7070:30001/TCP   94s

查看一下url

[root@localhost dockerfile]# minikube service hello-kubernetes  --url
http://192.168.1.128:30001

curl或者在瀏覽器中訪問:

[root@localhost dockerfile]# curl http://192.168.1.128:30001/hello
hello, kubetnetes!

刪除部署

$ kubectl delete -f hello-kubernetes.yaml

參考文章:

  • Minikube安裝成功Kubernetes,一次過!
  • https://www.cnblogs.com/0pandas0/p/12002386.html
  • https://yq.aliyun.com/articles/221687
  • https://www.cnblogs.com/0pandas0/p/12002386.html
  • https://blog.csdn.net/weixin_45536736/article/details/104087487
  • https://loocode.com/post/10174
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章