Kubernetes tutorial follows official documentation to build K8S from scratch

The article addresses: blog.piaoruiqing.com/2019/09/17/…

preface

This article will guide you through the installation and deployment of Kubernetes with reference to the official documentation. Kubernetes updates quickly, and tutorials on books and websites may not apply to the new version, but official documentation does.

Read this article and you will learn:

  • How to read the official Kubernetes installation guide and build a Kubernetes environment.
  • Kubernetes installation process precautions.
  • Avoid common potholes.

To read this article you need:

  • Familiar with Linux commands.
  • Know what Kubernetes are for: intersect; intersect;
  • Know the Docker

Equipment preparation

Document link: Before You Begin

The serial number The name of the The number of note
1 The server 2 Operating system: Linux(centos7, other operating systems are also available, similar installation process, please refer to the official documentation)

Machine configuration: CPU >= 2, memory >= 2G

Find kubeadm installation documentation entry from the official website, documentation is very detailed. Readers who have no difficulty in reading English are recommended to directly view the English document. Problems may occur if the Chinese document is incomplete and the update is not installed in time.

preparation

I have pre-installed two virtual machines, centos7(CPUx2, 2.5g memory). The IP addresses of the two VMS are fixed on the router.

Change the hostname

[root@k8s-master ~]$ vim /etc/hostname # change the hostname
[root@k8s-master ~]$ vim /etc/hosts	Point the local IP address to hostname
[root@k8s-master ~]$ reboot -h 		Restart (you can restart after you have done all the preparatory work)
Copy the code

After the modification, the configurations of the two VMS are as follows:

# in k8s-master[root @ k8s - master ~] $cat/etc/hostname k8s - master/root @ k8s - master ~ $cat/etc/hosts | grep k8s 10.33.30.92 k8s - master 10.33.30.91 k8s - worker# in k8s-worker[root @ k8s - worker ~] $cat/etc/hostname k8s - worker/root @ k8s - worker ~ $cat/etc/hosts | grep k8s 10.33.30.92 k8s - master 10.33.30.91 k8s - workerCopy the code

Verify the uniqueness of MAC and product_uUID

Verify the MAC address and product_uuid are unique for every node

[root@k8s-master ~]$ ifconfig -a    # see MAC
[root@k8s-master ~]$ cat /sys/class/dmi/id/product_uuid	# see product_uuid
Copy the code

Note: if you don’t have the ifconfig command for centos7, you can run yum install net-tools to install it.

Configuring the Firewall

Document link: Check required ports

As a result of the local Intranet test environment, the author figure convenient, directly closed the firewall. If security requirements are high, you can refer to official documents to permit ports.

[root@k8s-master ~]$ systemctl stop firewalld	# service shutdown
[root@k8s-master ~]$ systemctl disable firewalld	# disable service
Copy the code

Disable SELinux

Coredns Pods have CrashLoopBackOff or Error state

Modify /etc/selinux/config to set selinux =disabled. Restart the machine.

[root@k8s-master ~]$ sestatus	Check SELinux status
SELinux status: disabled
Copy the code

Disabling Swap Partitions

Document link: Before You Begin

Swap disabled. You MUST disable swap in order for the kubelet to work properly.

Edit /etc/fstab to comment out swap. Restart the machine.

[root@k8s-master ~]$ vim /etc/fstab 
#/dev/mapper/cl-swap swap swap defaults 0 0
Copy the code

Install the Docker

Get Docker Engine – Community for CentOS

Docker official documentation has described the installation steps in sufficient detail, and the process is not complicated, so this article will not repeat it.

  • Docker please use 18.09, k8S does not support the latest Docker version 19.x, Yum install Docker-ce-18.09.9-3. el7 Docker-ce-cli-18.09.9-3. el7 containerd. IO

  • If the network is not good, you can use domestic sources, Ali cloud, University of Science and Technology, etc. Attached here is ali Yunyuan Docker installation document address: container image service.

  • After installation, it is recommended to replace the docker source with domestic one. Ali cloud image acceleration, ali cloud account can be used for free. Ali Cloud -> Container Image Service -> Image Center -> Image Acceleration

Configuration Docker

Document address: Container Runtimes

Modify /etc/docker-daemon. json to the following:

{
  "registry-mirrors": ["https://xxxxxxxx.mirror.aliyuncs.com"]."exec-opts": ["native.cgroupdriver=systemd"]."log-driver": "json-file"."log-opts": {
    "max-size": "100m"
  },
  "storage-driver": "overlay2"
}
Copy the code
  • Among themhttps://xxxxxxxx.mirror.aliyuncs.comforAli cloudMirror acceleration address,xxxxxxxxYou need to replace it with the address in your own account. As shown in figure:

After the installation and configuration is complete, perform the following operations:

[root@k8s-master ~]$ systemctl enable docker
[root@k8s-master ~]$ systemctl start docker
Copy the code

Install Kubernetes

Installing Kubeadm, kubelet and kubectl

Add the source

Due to domestic network reasons, the address in the official document is not available, this article is replaced by the address of Ali Cloud mirror, execute the following code:

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

The installation

[root@k8s-master ~]$ yum install -y kubelet kubeadm kubectl --disableexcludes=kubernetes
[root@k8s-master ~]$ systemctl enable kubelet && systemctl start kubelet
Copy the code

Modifying Network Configurations

cat <<EOF >  /etc/sysctl.d/k8s.conf
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1
EOF
sysctl --system
Copy the code

Note: At this point, all the above operations need to be performed on the Worker machine. Note that hostname and so on should not be the same.

Initialize the Master

Generate the initialization file

[root@k8s-master ~]$ kubeadm config print init-defaults > kubeadm-init.yaml
Copy the code

There are two modifications to this file:

  • willAdvertiseAddress: 2.Change the address to the local address
  • willimageRepository: k8s.gcr.ioModified toimageRepository: registry.cn-hangzhou.aliyuncs.com/google_containers

After the modification, the file is as follows:

apiVersion: kubeadm.k8s.io/v1beta2
bootstrapTokens:
- groups:
  - system:bootstrappers:kubeadm:default-node-token
  token: abcdef.0123456789abcdef
  ttl: 24h0m0s
  usages:
  - signing
  - authentication
kind: InitConfiguration
localAPIEndpoint:
  advertiseAddress: 10.3330.92.
  bindPort: 6443
nodeRegistration:
  criSocket: /var/run/dockershim.sock
  name: k8s-master
  taints:
  - effect: NoSchedule
    key: node-role.kubernetes.io/master
---
apiServer:
  timeoutForControlPlane: 4m0s
apiVersion: kubeadm.k8s.io/v1beta2
certificatesDir: /etc/kubernetes/pki
clusterName: kubernetes
controllerManager: {}
dns:
  type: CoreDNS
etcd:
  local:
    dataDir: /var/lib/etcd
imageRepository: registry.cn-hangzhou.aliyuncs.com/google_containers
kind: ClusterConfiguration
kubernetesVersion: v1.15.0
networking:
  dnsDomain: cluster.local
  serviceSubnet: 10.96. 0. 0/ 12
scheduler: {}
Copy the code

Download mirror

[root@k8s-master ~]$ kubeadm config images pull --config kubeadm-init.yaml
Copy the code
[Copyright Notice]


This article was published on
Park Seo-kyung’s blog, allow non-commercial reprint, but reprint must retain the original author
PiaoRuiQingAnd links:
blog.piaoruiqing.comFor negotiation or cooperation on authorization, please contact:
[email protected].

Perform initialization

[root@k8s-master ~]$ kubeadm init --config kubeadm-init.yaml
Copy the code

After the command is executed, the following information is displayed:

. Your Kubernetes control-plane has initialized successfully! . Then you can join any number of worker nodes by running the following on each as root: Kubeadm join 10.33.30.92:6443 --token abcdef.0123456789abcdef \ --discovery-token-ca-cert-hash sha256:2883b1961db36593fb67ab5cd024f451b934fc0e72e2fa3858dda3ad3b225837 
Copy the code

Save the last two lines, kubeadm join… Is the command to be executed to join the worker node.

Next, configure the environment so that the current user can execute kubectl commands:

mkdir -p $HOME/.kube
sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
sudo chown $(id -u):$(id -g) $HOME/.kube/config
Copy the code

Test this: NotReady is used because the network has not been configured.

[root@k8s-master kubernetes]$kubectl get node NAME STATUS ROLES AGE VERSION k8s-master NotReady master 3M25s v1.15.3Copy the code

Configure the network

Document address: Instructions

Download the description file

[root @ k8s - master ~] $wget HTTP: / / https://docs.projectcalico.org/v3.8/manifests/calico.yaml/root @ k8s - master ~ $cat Kubeadm - init. Yaml | grep serviceSubnet: serviceSubnet: 10.96.0.0/12Copy the code

Open calico.yaml and change 192.168.0.0/16 to 10.96.0.0/12

. It is important to note that the calico yaml of IP and kubeadm – init. Yaml need consistent, either initialize before modifying kubeadm – init. Yaml, or modify the calico. After initialization yaml.

Execute kubectl apply -f calico.yaml to initialize the network.

Check node information. The master state is Ready.

[root@k8s-master ~]$kubectl get node NAME STATUS ROLES AGE VERSION k8S - Master Ready Master 15m V1.15.3Copy the code

Install the Dashboard

Document address: Web UI (Dashboard)

Deploy the Dashboard

Uild-the Dashboard UI

[root@k8s-master ~]$ wget https://raw.githubusercontent.com/kubernetes/dashboard/v2.0.0-beta4/aio/deploy/recommended.yaml/root @ k8s - master ~ $ kubectl apply-f recommended.yaml 
Copy the code

Kubectl get Pods –all-namespaces to check pods status

[root@k8s-master kubernetes]$ kubectl get pods --all-namespaces | grep dashboard
NAMESPACE              NAME                                        READY   STATUS   
kubernetes-dashboard   dashboard-metrics-scraper-fb986f88d-m9d8z   1/1     Running
kubernetes-dashboard   kubernetes-dashboard-6bb65fcc49-7s85s       1/1     Running 
Copy the code

Create a user

Document address: Creating sample user

Create a user to log in to Dashboard. Create the dashboard-adminuser.yaml file as follows:

apiVersion: v1
kind: ServiceAccount
metadata:
  name: admin-user
  namespace: kube-system
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: admin-user
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: cluster-admin
subjects:
- kind: ServiceAccount
  name: admin-user
  namespace: kube-system
Copy the code

Run kubectl apply -f dashboard-adminuser.yaml.

Generate a certificate

Document address: Accessing Dashboard 1.7.x and above

The official document provides the login method of 1.7.X or later, but it is not clear. The author does not completely follow the method in the document.

[root@k8s-master ~]$ grep 'client-certificate-data' ~/.kube/config | head -n 1 | awk '{print $2}' | base64 -d >> kubecfg.crt
[root@k8s-master ~]$ grep 'client-key-data' ~/.kube/config | head -n 1 | awk '{print $2}' | base64 -d >> kubecfg.key
[root@k8s-master ~]$ openssl pkcs12 -export -clcerts -inkey kubecfg.key -in kubecfg.crt -out kubecfg.p12 -name "kubernetes-client"
Copy the code

The third command will prompt you to enter the password when the certificate is generated. You can skip it by pressing enter twice.

Kubecfg. p12 is the certificate of the client machine to be imported. Copy the certificate to the client and import it.

~ $SCP [email protected]: / root /. Kube/kubecfg p12. /Copy the code
  • Note: If you skip the password when generating the certificate, you can enter the password directly when importing the certificate, and do not worry about the password (゚▽゚)/

Now we can log in to the panel and access the address: https://{k8s-master-ip}:6443/api/v1/namespaces/kubernetes-dashboard/services/https:kubernetes-dashboard:/proxy/#/login, When you log in, you will be prompted to select the certificate. After confirming, you will be prompted to enter the current user name and password (note that it is the user name and password of the computer).

Login Dashboard

Document address :Bearer Token

Perform kubectl -n kube – system the describe secret $(kubectl – n kube – system get secret | grep admin – user | awk ‘} {print $1), The access Token.

[root@k8s-master .kube]$ kubectl -n kube-system describe secret $(kubectl -n kube-system get secret | grep admin-user | awk '{print $1}') Name: admin-user-token-dhhkb Namespace: kube-system Labels: <none> Annotations: kubernetes.io/service-account.name: admin-user kubernetes.io/service-account.uid: b20d1143-ce94-4379-9e14-8f80f06d8479 Type: kubernetes.io/service-account-token Data ==== ca.crt: 1025 bytes namespace: 11 bytes token: eyJhbGciOiJSUzI1NiIsImtpZCI6IiJ9.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9 uYW1lc3BhY2UiOiJrdWJlLXN5c3RlbSIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VjcmV0Lm5hbWUiOiJhZG1pbi11c2VyLXRva2VuLWRoaGt iIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQubmFtZSI6ImFkbWluLXVzZXIiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2V hY2NvdW50L3NlcnZpY2UtYWNjb3VudC51aWQiOiJiMjBkMTE0My1jZTk0LTQzNzktOWUxNC04ZjgwZjA2ZDg0NzkiLCJzdWIiOiJzeXN0ZW06c2VydmljZWF jY291bnQ6a3ViZS1zeXN0ZW06YWRtaW4tdXNlciJ9.f6IbPGwIdFZWStzBj8_vmF01oWW5ccaCpPuVQNLSK1pgEqn0kNVK_x0RYSuKEnujObzpQQdFiRYcI6 ITHja2PIVc5Nv83VCn5IaLvZdYuGZWUYRw0efJUBMA4J4N8-pRkiw6fYAuWLeGYghLNXL_nDdC_JkG75ASqrr3U1MVaikOcfrEPaI-T_AJ3TMYhI8aFoKiER pumu5W1K6Jl80Am9pWDX0Ywis5SSUP1VYfu-coI48EXSptcaxEyv58PrHUd6t_oMVV9rpqSxrNtMZvMeXqe8Hnl21vR7ls5yTZegYtHXSc3PKvCaIalKhYXA uhogNcIXHaMzvLSbf-DSQkVwCopy the code

Copy the Token to the login page and click login. The effect is as follows:

Add Worker node

Repeat all the steps of preparing – Modifying hostname – Installing Kubernetes- modifying network configuration to initialize a Worker machine.

Run the following command to add the Worker to the cluster:

Kubeadm join 10.33.30.92:6443 --token abcdef.0123456789abcdef \ --discovery-token-ca-cert-hash sha256:2883b1961db36593fb67ab5cd024f451b934fc0e72e2fa3858dda3ad3b225837 
Copy the code
  • Note: The secret key is generated after initializing Master, refer to the previous section.

After the node is added, check the node status on the Master:

[root@k8s-master ~]$kubectl get node NAME STATUS ROLES AGE VERSION k8S-master Ready Master 10h v1.15.3k8s-worker Ready The < none > 96 s v1.15.3Copy the code

It can also be viewed on the panel:

If this article is helpful to you, please give a thumbs up (~ ▽ ~)”

reference

  • kubernetes.io
  • Github.com/kubernetes/…

series

  • Build K8S from scratch with official documentation
  • Kubernetes(2) Application deployment
  • How do I access the service from outside

Welcome to pay attention to the public account (code such as poetry):

[Copyright Notice]


This article was published on
Park Seo-kyung’s blog, allow non-commercial reprint, but reprint must retain the original author
PiaoRuiQingAnd links:
blog.piaoruiqing.comFor negotiation or cooperation on authorization, please contact:
[email protected].