IT

쿠버네티스(kubernetes),도커(docker) 설치 본문

Kubernetes(쿠버네티스)

쿠버네티스(kubernetes),도커(docker) 설치

셋글자 2020. 8. 14. 11:19
728x90

※ 목표

쿠버네티스(kubernetes),도커(docker) 설치(1)

kuberentes(쿠버네티스) 대시보드 설치, metrics-server설치, 대시보드 접속(2)

kuberentes(쿠버네티스) 대시보드 외부접속 작업(3)

docker private registry 생성 (4)

kubernetes(쿠버네티스)를 통해  deployment pod 배포 (5)

kuberentes(쿠버네티스), 프로메테우스(prometheus), 그라파나(grafana) 연동 (6)

현재 서비스와 kubernets api를 연동하여 deplyment replicas를 제어 (7)

 

쿠버네티스(kubernetes),도커(docker) 설치

아래와 같이 128서버를 master로 두고 node(worker) 서버2대로 구성해본다.

192.168.217.128 master
192.168.217.130 node1
192.168.217.129 node2

(VM Ware로 진행)

 

 

--1 호스트 정보 설정 (전체서버 적용)

 # vi /etc/hosts

127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4

::1         localhost localhost.localdomain localhost6 localhost6.localdomain6

192.168.217.128 master

192.168.217.130 node1

192.168.217.129 node2

 

--2 호스트 네임 설정 (전체서버 적용)

# hostnamectl set-hostname master --static (128서버)

# hostnamectl set-hostname node1 --static (130서버)

# hostnamectl set-hostname node2 --static (129서버)

 

  ** 참고 호스트네임 대문자 설정시 --static옵션을 넣어주어야 대문자 가능(소문자일때 넣어도 무관함)

 

--3 방화벽 비활성화(전체서버 적용)

# systemctl stop firewalld

# systemctl disable firewalld

# systemctl status firewalld

 

** 방화벽 비활성화가 여건상 안된다면 필요포트를 열어준다.(구글링 참조) 

** 아래 포트 외에 더 필요한 포트가 있을 수 있음.

# firewall-cmd --zone=public --permanent --add-port=10251/tcp

# firewall-cmd --zone=public --permanent --add-port=10252/tcp

firewall-cmd --zone=public --permanent --add-port=6443/tcp

firewall-cmd --zone=public --permanent --add-port=2379-2380/tcp

# firewall-cmd --zone=public --permanent --add-port=10250/tcp

# firewall-cmd --reload

 

--4 Disable selinux(전체서버 적용)

**적용전

# sestatus --> selinux 상태 확인 명령어

SELinux status:                 enabled

SELinuxfs mount:                /sys/fs/selinux

SELinux root directory:         /etc/selinux

Loaded policy name:             targeted

Current mode:                   enforcing

Mode from config file:          enforcing

Policy MLS status:              enabled

Policy deny_unknown status:     allowed

Max kernel policy version:      31

 

  # setenforce 0 

  # sed -i --follow-symlinks 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/sysconfig/selinux

 

**적용후

# 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:          disabled

Policy MLS status:              enabled

Policy deny_unknown status:     allowed

Max kernel policy version:      31

 

 

--Enable br_netfilter Kernel Module(전체서버 적용, sudo 말고 root로 실행)

**CNI플러그인이 작동하기 위한 요구사항(pod네트워크애드온 Flannel 작동시 필요)

# modprobe br_netfilter

# echo '1' > /proc/sys/net/bridge/bridge-nf-call-iptables

# modprobe br_netfilter

 

modprobe 실행시 bridge 관련 모듈 추가됨

# ll /proc/sys/net/

dr-xr-xr-x. 1 root root 0  7월  9 11:02 bridge

dr-xr-xr-x. 1 root root 0  7월  9 11:03 core

dr-xr-xr-x. 1 root root 0  7월  8 11:07 ipv4

dr-xr-xr-x. 1 root root 0  7월  8 11:07 ipv6

dr-xr-xr-x. 1 root root 0  7월  8 11:07 netfilter

-rw-r--r--. 1 root root 0  7월  9 11:03 nf_conntrack_max

dr-xr-xr-x. 1 root root 0  7월  8 11:07 unix

 

**구글링시 위의 작업은 마스터 서버에서만 진행을 많이 하였지만

나같은 경우는 VM재부팅시 node서버가 master에 조인하지 못하는 경우가 있었음.

node서버에서도 적용하여도 실제 운영상에는 문제가 없었음.

 

 

--Disable SWAP(전체서버 적용)

swap 파티션이나 swap 파일의 구동을 중단시키는 명령어

#swapoff -a

 

--swap 관련 주석처리(전체서버 적용)

# vi /etc/fstab

/dev/mapper/centos-root /                       xfs     defaults        0 0

UUID=e6ee9759-98e4-4cfd-8963-9d130776daa1 /boot                   xfs     defaults        0 0

/dev/mapper/centos-home /home                   xfs     defaults        0 0

#/dev/mapper/centos-swap swap                    swap    defaults        0 0

 

 

--포트포워딩 허용 ipv4 설정 (전체서버 적용)

내가 작업당시에는 VM ware가 아닌 실제서버설치시 아래 설정이 없으면 docker private registry images를

공유하지 못하여서 구글링후 작업 적용

# vi /etc/sysct.conf

net.ipv4.ip_forward = 1

 

 

--Docker 설치(전체서버 적용)

**docker는 docker 공홈 설치방법을 적용.

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

# yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo 

# yum -y install docker-ce

 

**검색당시 중요하진 않지만 18.06.3.ce버전이 호환?이 제일 잘된다고 하여 작업에는 18.06.3ce버전을 설치하였다.

# yum install -y docker-ce-18.06.3.ce  (특정버전)

 

서버리부트시 도커 재시작 및 현재 도커 실행

# systemctl enable docker && systemctl start docker

 

--Docker  그룹에 non-root 사용자 추가(전체서버적용)

나는 root로 진행하였기 때문에 이번 작업은 적용하지 않음.

# usermod -aG docker [your-user-id]

 

--k8s.conf 파일생성(전체서버적용)

# vi /etc/sysctl.d/k8s.conf

===========

net.bridge.bridge-nf-call-ip6tables = 1

net.bridge.bridge-nf-call-iptables = 1

============ 

 

설정 적용되었는지 확인

# sysctl --system

* Applying /usr/lib/sysctl.d/00-system.conf ...

net.bridge.bridge-nf-call-ip6tables = 0

net.bridge.bridge-nf-call-iptables = 0

net.bridge.bridge-nf-call-arptables = 0

* Applying /usr/lib/sysctl.d/50-default.conf ...

kernel.sysrq = 16

kernel.core_uses_pid = 1

net.ipv4.conf.default.rp_filter = 1

net.ipv4.conf.all.rp_filter = 1

net.ipv4.conf.default.accept_source_route = 0

net.ipv4.conf.all.accept_source_route = 0

net.ipv4.conf.default.promote_secondaries = 1

net.ipv4.conf.all.promote_secondaries = 1

fs.protected_hardlinks = 1

fs.protected_symlinks = 1

* Applying /usr/lib/sysctl.d/60-libvirtd.conf ...

fs.aio-max-nr = 1048576

* Applying /usr/lib/sysctl.d/99-docker.conf ...

* Applying /etc/sysctl.d/99-sysctl.conf ...

* Applying /etc/sysctl.d/k8s.conf ...

net.bridge.bridge-nf-call-ip6tables = 1

net.bridge.bridge-nf-call-iptables = 1

* Applying /etc/sysctl.conf ...

 

--cgroup driver 설정(전체서버 적용)<선택사항>

** kubernetes 설치시 docker cgroup을 systemd로 권장? 및 경고한다.

나같은경우는 아래와 같이 docker cgroup를 systemd로 변경 후 설치해보았지만 kubenetes가 정상작동하지 않았다.

(설치 당시 다른오류와 겹쳤을 수도 있음)

나의 경우 작업당시에는 자꾸 오류나서 적용하지않음.

쿠버네티스 운용당시 문제없었음.

 

[cgroup driver정보 조회]

# docker info | grep -i cgroup

Cgroup Driver: cgroupfs

 

--cgroup 변경하는 검색시 나오는 방법

[구글링시 10-kubeadm.conf]

# sed -i 's/cgroup-driver=systemd/cgroup-driver=cgroupfs/g' /etc/systemd/system/kubelet.service.d/10-kubeadm.conf

 

[나의 경우는 버전차이인지는 모르겟지만 다르게 10-kubeadm.conf가 다른곳에 위치하였음]

# sed -i 's/cgroup-driver=systemd/cgroup-driver=cgroupfs/g' /usr/lib/systemd/system/kubelet.service.d/10-kubeadm.conf

/usr/lib/systemd/system/kubelet.service.d/10-kubeadm.conf -> 파일은 여기있음.

 

=============================

위의 작업으로 cgroup driver변화가 없어서 아래와 같이 해보니 systemd변경은 잘되었다.

cgroup driver 오류로 인한 설정 대체  (https://blog.naver.com/weplayicecream/221498635944)

# sudo vi /usr/lib/systemd/system/docker.service

-->수정 ExecStart=/usr/bin/dockerd --exec-opt native.cgroupdriver=systemd

 

# sudo systemctl daemon-reload

# sudo systemctl restart docker

# sudo docker info | grep -i cgroup

Cgroup Driver: systemd

 

 

--쿠버네티스(Kubernetes) 설치repo 작성(전체서버적용)

[kubernetes.repo 파일 생성]

# vi /etc/yum.repos.d/kubernetes.repo

 

================

[kubernetes]

name=Kubernetes

baseurl=https://packages.cloud.google.com/yum/repos/kubernetes-el7-x86_64

enabled=1

gpgcheck=1

repo_gpgcheck=1

gpgkey=https://packages.cloud.google.com/yum/doc/yum-key.gpg https://packages.cloud.google.com/yum/doc/rpm-package-key.gpg

================ 

 

--kubelet, kubeadm, kubectl 설치(전체서버 설치)<쿠버네티스설치>

쿠버네티스 설치(작업 버전 1.18.6설치됨)

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

 

다른버전 설치시 검색방법

#yum list kubelet kubeadm kubectl --disableexcludes=kubernetes --showduplicates

 

ex)특정버전 1.13버전 설치시

#yum install -y kubelet-1.13.1-0 kubeadm-1.13.1-0 kubectl-1.13.1-0 --disableexcludes=kubernetes 

 

kubelet 실행 및 서버재시작시 자동시작 등록 및 실행

# systemctl enable kubelet && systemctl start kubelet 

 

**위와 같이 kubelet을 시작하고

'systemctl status kubelet' 을 시작하였지만 active긴하지만 activating이 되지 않았다.(정상 동작이 되지 않았다라고 생각됨)

차후 작업중 마스터서버 kubeadm init시 정상동작 되니 신경안써도 될것.(나의 경우에는 이거때문에 괜한 구글링 및 시간을 너무 쏟았음)

 

 

-- kubernetes Cluster 설치(Master서버만 진행)

[쿠버네티스 마스터서버 Cluster설치]

pod-network-cidr 값은 현재 마스터서버와 같은대역만 아니면 되는것 같다.

검색시 10.244.0.0/16을 제일 많이 사용하여 아래와 같이 사용함.

 

# kubeadm init --apiserver-advertise-address=192.168.217.128 --pod-network-cidr=10.244.0.0/16

# kubeadm init --apiserver-advertise-address=<masterServer-ip> --pod-network-cidr=10.244.0.0/16

 

**오류사항**

마스터서버에 cluster설치시 오류또는 경고가 제일 많이 발생.

1. [ERROR NumCPU]: the number of available CPUs 1 is less than the required 2

쿠버네티스가 cpu 프로세스를 2개이상을 요구함

무시하고 설치하려면

# kubeadm init --apiserver-advertise-address=<masterServer-ip> --pod-network-cidr=10.244.0.0/16 --ignore-preflight-errors=NumCpu

 

위와 같이 설치하면 되지만 권장되지는 않는것 같다. VM수정 후 다시 진행함.

(애초에 cpu프로세스를 2개이상 요구하므로 2개미만일 경우 뭔가 동작이 잘 안될 것 같음.)

 

 

> cluster설치 완료 후

======================================= 

Your Kubernetes control-plane has initialized successfully!

 

To start using your cluster, you need to run the following as a regular user:

 

  mkdir -p $HOME/.kube

  sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config

  sudo chown $(id -u):$(id -g) $HOME/.kube/config

 

You should now deploy a pod network to the cluster.

Run "kubectl apply -f [podnetwork].yaml" with one of the options listed at:

  https://kubernetes.io/docs/concepts/cluster-administration/addons/

 

Then you can join any number of worker nodes by running the following on each as root:

 

kubeadm join 192.168.217.128:6443 --token ziq171.86u17stwc1k8fcnb \

    --discovery-token-ca-cert-hash sha256:e129b02da45586a55c235567a8310e00dda44d7e7e31c2e29b7e2d5787655a95

======================================= 

 

위의 빨간색 포인트 명령어는 node가 master와 조인될때 필요한 명령어이니 보관하여야 한다.

 

정상적 설치가 완료되었다면 아래와 같이 명령어 사용. (root이든 일반사용자든 진행)

#  mkdir -p $HOME/.kube

#  sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config

#  sudo chown $(id -u):$(id -g) $HOME/.kube/config

 

 

> kubectl 명령어 사용을 위한 설정 적용(reboot시에도 사용할수 있게)

# vi ~/.bash_profile

[.bash_profile]

....

PATH=$PATH:$HOME/bin

export PATH

export KUBECONFIG=/etc/kubernetes/admin.conf   <--추가(최하단에 추가함)

 

>변경사항 적용

# source ~/.bash_profile

 

--falnnel 적용(Master서버만 진행)

# kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml

 

 

-- kubernetes Node조인(Node서버만 진행)

 

kubernetes Cluster 설치에서 보관한 조인명령어사용

전체서버진행에 대한 것이 모두 적용된 node서버에서만 적용

# kubeadm join 192.168.217.128:6443 --token ziq171.86u17stwc1k8fcnb \

    --discovery-token-ca-cert-hash sha256:e129b02da45586a55c235567a8310e00dda44d7e7e31c2e29b7e2d5787655a95

 

>> 조인시 오류사항 <<

1.

error execution phase preflight: [preflight] Some fatal errors occurred:

    [ERROR FileContent--proc-sys-net-ipv4-ip_forward]: /proc/sys/net/ipv4/ip_forward contents are not set to ~

[[아래명령어 입력후 재조인]]

# echo '1' > /proc/sys/net/ipv4/ip_forward

 

2.

error execution phase preflight: [preflight] Some fatal errors occurred:

    [ERROR FileContent--proc-sys-net-bridge-bridge-nf-call-iptables]: /proc/sys/net/bridge/bridge-nf-call-iptables contents are not set to 1

[[아래명령어 입력후 재조인]]

# echo '1' > /proc/sys/net/bridge/bridge-nf-call-iptables

 

그외의 오류일경우 검색.

 

-- Master와 Node확인(Master서버에서만 가능)

# kubectl get nodes

NAME     STATUS   ROLES    AGE     VERSION

master   Ready    master   7m24s   v1.18.6

node1    Ready    <none>   4m32s   v1.18.6

node2    Ready    <none>   4m11s   v1.18.6

 

*Ready 상태 되기 까지 조금걸림(약 2~3분 기다린듯함)

 

-- 간단히 테스트겸 Nginx배포(Master 서버 진행)

# kubectl create deployment nginx --image=nginx

deployment.extensions "nginx" created

 

# kubectl describe deployment nginx

Name:                   nginx

Namespace:              default

CreationTimestamp:      Tue, 29 Jan 2019 15:57:45 +0900

Labels:                 app=nginx

Annotations:            deployment.kubernetes.io/revision=1

Selector:               app=nginx

Replicas:               1 desired | 1 updated | 1 total | 1 available | 0 unavailable

StrategyType:           RollingUpdate

MinReadySeconds:        0

RollingUpdateStrategy:  1 max unavailable, 1 max surge

Pod Template:

  Labels:  app=nginx

  Containers:

   nginx:

    Image:        nginx

    Port:         <none>

    Host Port:    <none>

    Environment:  <none>

    Mounts:       <none>

  Volumes:        <none>

Conditions:

  Type           Status  Reason

  ----           ------  ------

  Available      True    MinimumReplicasAvailable

OldReplicaSets:  <none>

NewReplicaSet:   nginx-5c7588df (1/1 replicas created)

Events:

  Type    Reason             Age   From                   Message

  ----    ------             ----  ----                   -------

  Normal  ScalingReplicaSet  23s   deployment-controller  Scaled up replica set nginx-5c7588df to 1

 

> 서비스 생성

# kubectl create service nodeport nginx --tcp=80:80

service "nginx" created

 

> 서비스 확인

# kubectl get service

NAME                            TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)          AGE

kubernetes                      ClusterIP   10.96.0.1         <none>          443/TCP          4h

nginx                             NodePort  10.100.26.49     <none>          80:31871/TCP  24s

 

> 서비스 확인시 31871port확인

master서버이든 node서버든 전부 nginx응답이 와야함.

아래의 3개 명령어를 master,node1,node2 다실행해보았으며 전부 response가 아래와 같이 오면 성공.

# curl master:31871

# crul node1:31871

# crul node2:31871

<!DOCTYPE html>

<html>

<head>

<title>Welcome to nginx!</title>

<style>

    body {

        width: 35em;

        margin: 0 auto;

        font-family: Tahoma, Verdana, Arial, sans-serif;

    }

</style>

</head>

<body>

<h1>Welcome to nginx!</h1>

<p>If you see this page, the nginx web server is successfully installed and

working. Further configuration is required.</p>

 

<p>For online documentation and support please refer to

<a href="http://nginx.org/">nginx.org</a>.<br/>

Commercial support is available at

<a href="http://nginx.com/">nginx.com</a>.</p>

 

<p><em>Thank you for using nginx.</em></p>

</body>

</html>

 

 

기본적인 docker, kubernetes 설치는 완료되었음.