본문 바로가기
프로그램 활용/클라우드 가상화 도커

kubernetes 설치

by 3604 2023. 8. 3.
728x90

출처: kubernetes 설치 (tistory.com)

테스트 환경은 아래와 같습니다.

[root@km ~]# cat /etc/redhat-release
CentOS Linux release 7.9.2009 (Core)
[root@km ~]# cat /proc/cpuinfo | grep 'processor' | wc -l
4
[root@km ~]# free -h
              total        used        free      shared  buff/cache   available
Mem:            15G        612M         14G        9.0M        130M         14G
Swap:          7.9G          0B        7.9G

 

총 3대 노드에 설치 테스트를 진행할 예정임

/etc/hosts에 호스트를 등록해줬다.

vi /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
172.30.1.144 km.dd.io
172.30.1.145 kw1.dd.io
172.30.1.146 kw2.dd.io

 

linux 환경 설정

linux 환경을 세팅해봅시다. 모든 노드에서 동일하게 환경 설정이 진행되어야함. 

 

1. 방화벽 해제하고 확인

[root@hdm2 ~]# systemctl stop firewalld
[root@hdm2 ~]# systemctl disable firewalld

[root@hdm2 ~]# systemctl status firewalld
● firewalld.service - firewalld - dynamic firewall daemon
   Loaded: loaded (/usr/lib/systemd/system/firewalld.service; disabled; vendor preset: enabled)
   Active: inactive (dead)
     Docs: man:firewalld(1)

2. selinux 비활성화 및 확인

[root@km ~]# setenforce 0

[root@km ~]# sed -i 's/^SELINUX=enforcing$/SELINUX=permissive/' /etc/selinux/config


[root@km ~]# cat /etc/selinux/config

# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#     enforcing - SELinux security policy is enforced.
#     permissive - SELinux prints warnings instead of enforcing.
#     disabled - No SELinux policy is loaded.
SELINUX=permissive
# SELINUXTYPE= can take one of three values:
#     targeted - Targeted processes are protected,
#     minimum - Modification of targeted policy. Only selected processes are protected.
#     mls - Multi Level Security protection.
SELINUXTYPE=targeted



[root@km ~]# sestatus
SELinux status:                 enabled
SELinuxfs mount:                /sys/fs/selinux
SELinux root directory:         /etc/selinux
Loaded policy name:             targeted
Current mode:                   permissive
Mode from config file:          permissive
Policy MLS status:              enabled
Policy deny_unknown status:     allowed
Max kernel policy version:      31

 

3. swap 메모리 비활성화 및 확인

k8s는 메모리 스왑을 고려하지 않고 설계했다고 함. 비활성화 해준다.

swap을 off하고 /etc/fstab의 내용 중 swap 관련 설정을 주석처리해준다.

[root@hdm2 ~]# swapoff -a
[root@hdm2 ~]# sed -i '/ swap / s/^/#/' /etc/fstab


[root@hdm2 ~]# cat /etc/fstab
# Created by anaconda on Fri Apr 30 11:07:40 2021
#
# Accessible filesystems, by reference, are maintained under '/dev/disk'
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
#
/dev/mapper/centos-root /                       xfs     defaults        0 0
UUID=3899dde7-cb9a-4416-b9cc-160ffbc3a4ea /boot                   xfs     defaults        0 0
#/dev/mapper/centos-swap swap                    swap    defaults        0 0

 

4. br_netfilter 설정

bridge netfilter을 설정한다. 이걸 세팅해야 pod끼리 통신이 가능해진다고 한다.

cat <<EOF | sudo tee /etc/modules-load.d/k8s.conf
br_netfilter
EOF

 

5. iptables가 브리지된 트래픽을 보도록 iptables 커널 옵션을 활성화한다.

cat <<EOF | sudo tee /etc/sysctl.d/k8s.conf
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1
EOF

 

6. 4와 5번 설정을 시스템에 적용한다.

sysctl --system

 

7. 쿠버네티스 yum repository를 설정한다.

/etc/yum.repos.d/에 들어가면 kubernetes.repo 파일이 생성된 것을 확인할 수 있다.

yum repolist 커맨드로 repository를 잘 가져오는 지 확인한다.

 

cat <<EOF > /etc/yum.repos.d/kubernetes.repo
[kubernetes]
name=Kubernetes
baseurl=https://packages.cloud.google.com/yum/repos/kubernetes-el7-x86_64
enabled=1
gpgcheck=0
EOF

[root@hdm2 yum.repos.d]# yum repolist
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: mirror.kakao.com
 * extras: mirror.kakao.com
 * updates: mirror.kakao.com
repo id                                                               repo name                                                                                           status
base/7/x86_64                                                         CentOS-7 - Base                                                                                     10,072
cloudera-manager                                                      Cloudera Manager, Version                                                                                6
epel/x86_64                                                           Extra Packages for Enterprise Linux 7 - x86_64                                                      13,749
extras/7/x86_64                                                       CentOS-7 - Extras                                                                                      509
kubernetes/x86_64                                                     Kubernetes                                                                                          17+768
updates/7/x86_64                                                      CentOS-7 - Updates                                                                                   3,573
repolist: 27,926

 

gpgcheck를 설정하면 아래와 같은 에러가 발생해서 gpgcheck=0으로 설정을 변경해줬다.

https://packages.cloud.google.com/yum/repos/kubernetes-el7-x86_64/repodata/repomd.xml: [Errno -1] repomd.xml signature could not be verified for kubernetes

 

8. Centos package를 업데이트 한다.

시간이 좀 걸린다.

yum update -y

 

9. docker 설치 전 필요 패키지 설치

device-mapper-persistent-data : Device Mapper는 Linux에서 많은 고급 볼륨 관리 기술을 뒷받침하는 커널 기반 프레임워크

LVM(Logical Volume Manager) : 관리자가 파일 시스템과 사용 중인 물리 저장소 사이의 추상 레이어를 제공하여 메타 장치를 만들 수 있게 한다. 

yum install -y yum-utils device-mapper-persistent-data lvm2

 

10. docker repository 설정

[root@hdm2 yum.repos.d]# yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
Loaded plugins: fastestmirror
adding repo from: https://download.docker.com/linux/centos/docker-ce.repo
grabbing file https://download.docker.com/linux/centos/docker-ce.repo to /etc/yum.repos.d/docker-ce.repo
repo saved to /etc/yum.repos.d/docker-ce.repo


[root@hdm2 yum.repos.d]# yum repolist
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: mirror.kakao.com
 * extras: mirror.kakao.com
 * updates: mirror.kakao.com
docker-ce-stable                                                                                                                                         | 3.5 kB  00:00:00
(1/2): docker-ce-stable/7/x86_64/updateinfo                                                                                                              |   55 B  00:00:00
(2/2): docker-ce-stable/7/x86_64/primary_db                                                                                                              |  73 kB  00:00:00
repo id                                                                   repo name                                                                                       status
base/7/x86_64                                                             CentOS-7 - Base                                                                                 10,072
cloudera-manager                                                          Cloudera Manager, Version                                                                            6
docker-ce-stable/7/x86_64                                                 Docker CE Stable - x86_64                                                                          146
epel/x86_64                                                               Extra Packages for Enterprise Linux 7 - x86_64                                                  13,749
extras/7/x86_64                                                           CentOS-7 - Extras                                                                                  509
kubernetes/x86_64                                                         Kubernetes                                                                                      17+768
updates/7/x86_64                                                          CentOS-7 - Updates                                                                               3,573
repolist: 28,072

 

11. docker 설치

yum install -y docker-ce docker-ce-cli containerd.io

 

12. cgroup driver 변경

kubelet과 Docker는 cgroupfs를 사용하고 나머지 프로세스는 systemd를 사용하도록 노드가 설정된 경우, 시스템 리소스 부족 현상이 발생할 수 있으므로 리눅스 init 시스템이 사용하는 cgroups 드라이버와 docker, kubelet의 드라이버를 맞춰준다.

mkdir /etc/docker

cat << EOF > /etc/docker/daemon.json
{
  "exec-opts": ["native.cgroupdriver=systemd"]
}
EOF

 

13. docker 실행하고 cgroup 확인

systemctl daemon-reload
systemctl start docker
systemctl enable --now docker

[root@hdm2 yum.repos.d]# docker info | grep Cgroup
 Cgroup Driver: systemd
 Cgroup Version: 1

 

14. k8s 관련 패키지 설치

yum install -y --disableexcludes=kubernetes kubeadm kubectl kubelet

 

15. k8s 실행

systemctl enable --now kubelet

 

16. k8s master 초기화

master server에서만 다음 커맨드를 입력한다. (16~19 step은 master node에서만 실행한다.)

Network Plugin은 --pod-network-cidr을 통해 설정할 수 있다.

calico를 사용하기로함.

calico 기반 :  kubeadm init --pod-network-cidr=192.168.0.0/16
flannel 기반 : kubeadm init --pod-network-cidr=10.244.0.0/16

 

weave-net을 쓸 예정이라면 그냥 init만 하면 된다.

kubeadm init

 

성공적으로 init되면 아래와 같은 메시지가 출력된다. k8s worker node와 join하기 위해 필요하므로 잘 저장해둬야한다.

kubeadm join 172.30.1.144:6443 --token xk2apl.mu6nbpbdwxj2qyhv \
        --discovery-token-ca-cert-hash sha256:05874fd671aeaa23548c420dbe74709239e9d94d981f8c2dca1f1f3c7d0fa25b

 

17. k8s를 운영할 유저를 생성하고 sudo user로 등록해준다.

[root@hdm2 yum.repos.d]# adduser -m kube

[root@hdm2 yum.repos.d]# passwd kube
Changing password for user kube.
New password:
BAD PASSWORD: The password is shorter than 8 characters
Retype new password:
passwd: all authentication tokens updated successfully.

[root@hdm2 yum.repos.d]# usermod -aG wheel kube

 

18. kubectl을 실행하기 위한 환경변수를 설정한다.

admin.conf 파일이 kubectl을 실행하고자 하는 user의 /home/.kube에 있어야 kubectl 커맨드를 사용할 수 있다.

[root@hdm2 home]# mkdir -p $HOME/.kube
[root@hdm2 home]# sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
[root@hdm2 home]# sudo chown $(id -u):$(id -g) $HOME/.kube/config

[root@hdm2 home]# kubectl get nodes
NAME                STATUS     ROLES                  AGE   VERSION
hdm2.cdp.louis.io   NotReady   control-plane,master   35m   v1.23.5

 

kube user의 경우 conf 파일을 복사하지 않았기 때문에 아래와 같은 에러가 발생한다.

위와 conf file을 kube user의 /home/.kube 밑에 복사해주면 정상적으로 kubectl 명령을 실행할 수 있다.

[kube@hdm2 home]$ kubectl get nodes
error: the server doesn't have a resource type "nodes"

 

19. Network Plugin(CNI) 설정

k8s master에서만 실행한다.

kubectl get nodes 커맨드를 입력하면 아래와 같이 status가 NotReady로 나오는 것을 볼 수 있다.

이는 POD 사이의 통신을 지원하는 CNI가 설정되어있지 않기 때문이다.

[kube@hdm2 home]$ kubectl get nodes
NAME                STATUS     ROLES                  AGE   VERSION
hdm2.cdp.louis.io   NotReady   control-plane,master   40m   v1.23.5

 

아래 링크를 참고해 CALICO CNI를 설정함

https://projectcalico.docs.tigera.io/getting-started/kubernetes/quickstart

[root@km ~]# kubectl create -f https://projectcalico.docs.tigera.io/manifests/tigera-operator.yaml
[root@km ~]# kubectl create -f https://projectcalico.docs.tigera.io/manifests/custom-resources.yaml

[root@km ~]# watch kubectl get pods -n calico-system
NAME                                       READY   STATUS    RESTARTS   AGE
calico-kube-controllers-67f85d7449-gmc9h   1/1     Running   0          2m3s
calico-node-wd5wh                          1/1     Running   0          2m3s
calico-typha-7ddcb55499-b2pdx              1/1     Running   0          2m3s

 

아래 링크를 참고해 WEAVENET CNI를 설정함

https://www.weave.works/docs/net/latest/kubernetes/kube-addon/

[kube@hdm2 home]$ kubectl apply -f "https://cloud.weave.works/k8s/net?k8s-version=$(kubectl version | base64 | tr -d '\n')"
serviceaccount/weave-net created
clusterrole.rbac.authorization.k8s.io/weave-net created
clusterrolebinding.rbac.authorization.k8s.io/weave-net created
role.rbac.authorization.k8s.io/weave-net created
rolebinding.rbac.authorization.k8s.io/weave-net created
daemonset.apps/weave-net created

 

CNI 설정 후 node의 status가 Ready로 변경되었다.

[kube@hdm2 root]$ kubectl get nodes
NAME                STATUS   ROLES                  AGE   VERSION
hdm2.cdp.louis.io   Ready    control-plane,master   65m   v1.23.5

 

20. k8s worker join

위에서 따로 복사해놓은 kubeadm join 커맨드를 worker node에 입력한다.

[root@kw1 ~]# kubeadm join 172.30.1.144:6443 --token xk2apl.mu6nbpbdwxj2qyhv \
        --discovery-token-ca-cert-hash sha256:05874fd671aeaa23548c420dbe74709239e9d94d981f8c2dca1f1f3c7d0fa25b
        
[preflight] Running pre-flight checks
[preflight] Reading configuration from the cluster...
[preflight] FYI: You can look at this config file with 'kubectl -n kube-system g                                                                                                                                                             et cm kubeadm-config -o yaml'
[kubelet-start] Writing kubelet configuration to file "/var/lib/kubelet/config.y                                                                                                                                                             aml"
[kubelet-start] Writing kubelet environment file with flags to file "/var/lib/ku                                                                                                                                                             belet/kubeadm-flags.env"
[kubelet-start] Starting the kubelet
[kubelet-start] Waiting for the kubelet to perform the TLS Bootstrap...

This node has joined the cluster:
* Certificate signing request was sent to apiserver and a response was received.
* The Kubelet was informed of the new secure connection details.

Run 'kubectl get nodes' on the control-plane to see this node join the cluster.

 

만약 kubeadm join시 아래와 같은 에러가 발생한다면 `kubeadm reset` 커맨드를 입력하고 다시 실행해보면 된다.

[preflight] Running pre-flight checks
error execution phase preflight: [preflight] Some fatal errors occurred:
        [ERROR FileAvailable--etc-kubernetes-kubelet.conf]: /etc/kubernetes/kubelet.conf already exists
        [ERROR Port-10250]: Port 10250 is in use
        [ERROR FileAvailable--etc-kubernetes-pki-ca.crt]: /etc/kubernetes/pki/ca.crt already exists
[preflight] If you know what you are doing, you can make a check non-fatal with `--ignore-preflight-errors=...`
To see the stack trace of this error execute with --v=5 or higher

 

k8s master에서 `kubectl get nodes` 커맨드를 통해 worker node가 join되었는 지 확인한다.

[root@km ~]# kubectl get nodes
NAME        STATUS   ROLES                  AGE   VERSION
km.dd.io    Ready    control-plane,master   10m   v1.23.5
kw1.dd.io   Ready    <none>                 59s   v1.23.5

 

worker node에서 `kubectl get nodes`를 입력하면 다음과 같은 에러가 발생한다.

[root@kw1 ~]# kubectl get nodes
The connection to the server localhost:8080 was refused - did you specify the right host or port?

 

master에 있는 admin.conf file을 worker node에 배포해야 kubectl 명령을 사용할 수 있다.

[root@kw1 ~]# scp 172.30.1.144:/etc/kubernetes/admin.conf $HOME/.kube/config

#worker node에서도 정상적으로 kubectl command를 사용할 수 있게 되었음
[root@kw1 ~]# kubectl get nodes
NAME        STATUS   ROLES                  AGE     VERSION
km.dd.io    Ready    control-plane,master   13m     v1.23.5
kw1.dd.io   Ready    <none>                 4m24s   v1.23.5

 

728x90