본문 바로가기

Kubernetes - 환경구성 본문

Kubernetes

Kubernetes - 환경구성

Seongjun_You 2023. 12. 5. 21:25

과거 공부했었던 kubernetes

복습겸 쭉 정리를 해본다.

 

 

# -*- mode: ruby -*-
# vi: set ft=ruby :

## configuration variables ##
# max number of worker nodes
N = 3 
# each of components to install 
k8s_V = '1.22.0'           # Kubernetes 
docker_V = '20.10.8-3.el7' # Docker  
ctrd_V = '1.4.9-3.1.el7'   # Containerd 
## /configuration variables ##

Vagrant.configure("2") do |config| #api버전을 2로 사용해서 쓰겠다. do end가 한세트임
  
  #=============#
  # Master Node #
  #=============#

    config.vm.define "WO-m-k8s-#{k8s_V[0..3]}" do |cfg|  # vm을 정의하는 부분인데 [0..3]이 변수 문자열 읽어드리는 부분 좀 생소하네
      cfg.vm.box = "sysnet4admin/CentOS-k8s" # 우리가 사용하는 vm 이미지
      cfg.vm.provider "virtualbox" do |vb| # 우리가 실제로 사용하고있는 가상머신 하드웨어
        vb.name = "WO-m-k8s-#{k8s_V[0..3]}(github_SysNet4Admin)"
        vb.cpus = 2
        vb.memory = 2048
        vb.customize ["modifyvm", :id, "--groups", "/WO-k8s-SgMST-#{k8s_V[0..3]}(github_SysNet4Admin)"] # 그룹 설정
      end
      cfg.vm.host_name = "m-k8s" #호스트 이름 설정
      cfg.vm.network "private_network", ip: "192.168.1.10" # 랩탑과 가상머신이 통신할수있는 ip설정
      cfg.vm.network "forwarded_port", guest: 22, host: 60010, auto_correct: true, id: "ssh" # 포트포워딩 60010으로 접속하게
      cfg.vm.synced_folder "../data", "/vagrant", disabled: true   # 가상머신과 랩탑의 폴더 싱크인데 비활성화 해둠
      cfg.vm.provision "shell", path: "k8s_env_build.sh", args: N         #파일들은 가상머신에 업로드해 동작하도록 하는게 shell
      cfg.vm.provision "shell", path: "k8s_pkg_cfg.sh", args: [ k8s_V, docker_V, ctrd_V ]
      #cfg.vm.provision "shell", path: "master_node.sh"
      cfg.vm.provision "shell", path: "k_cfg_n_git_clone.sh" # add kubectl config & git clone source
    end                                                     #원래 마스터 노드에 포함되는 애인데 잠시
                                                            #마스터 노드를 주석처리해서 따로 파둔애
  #==============#
  # Worker Nodes #
  #==============#

  (1..N).each do |i| # 반복문 얘는 3까지 포함
    config.vm.define "WO-w#{i}-k8s-#{k8s_V[0..3]}" do |cfg|
      cfg.vm.box = "sysnet4admin/CentOS-k8s"
      cfg.vm.provider "virtualbox" do |vb|
        vb.name = "WO-w#{i}-k8s-#{k8s_V[0..3]}(github_SysNet4Admin)"
        vb.cpus = 1
        vb.memory = 1536
        vb.customize ["modifyvm", :id, "--groups", "/WO-k8s-SgMST-#{k8s_V[0..3]}(github_SysNet4Admin)"]
      end
      cfg.vm.host_name = "w#{i}-k8s"
      cfg.vm.network "private_network", ip: "192.168.1.10#{i}"
      cfg.vm.network "forwarded_port", guest: 22, host: "6010#{i}", auto_correct: true, id: "ssh"
      cfg.vm.synced_folder "../data", "/vagrant", disabled: true
      cfg.vm.provision "shell", path: "k8s_env_build.sh", args: N
      cfg.vm.provision "shell", path: "k8s_pkg_cfg.sh", args: [ k8s_V, docker_V, ctrd_V ]
      #cfg.vm.provision "shell", path: "work_nodes.sh"
    end
  end

end

"Vagrantfile" 메인 스크립트 파일이다.

 

 

#!/usr/bin/env bash

# vim configuration 
echo 'alias vi=vim' >> /etc/profile #조금더 개선된 프로그램을 호출하는 코드인데 안해도딤

# swapoff -a to disable swapping
swapoff -a   #스왑이 켜져있으면 쿠버네티스 설치가 진행되지 않는다.
# sed to comment the swap partition in /etc/fstab
sed -i.bak -r 's/(.+ swap .+)/#\1/' /etc/fstab # 리부트가 일어나도 다시 스왑을 하지 않는다.

# kubernetes repo
gg_pkg="packages.cloud.google.com/yum/doc" # Due to shorten addr for key
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 # 아래꺼하고 원래는 1로 설정하는게 맞는데 가끔 오류 이슈때문에 0으로 해둠 보안측면에서는 하는게 맞음
repo_gpgcheck=0
gpgkey=https://${gg_pkg}/yum-key.gpg https://${gg_pkg}/rpm-package-key.gpg
EOF

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

# Set SELinux in permissive mode (effectively disabling it)
setenforce 0 #이것도 보안 측면에서 원래 키는게 좋다고는 하다
sed -i 's/^SELINUX=enforcing$/SELINUX=permissive/' /etc/selinux/config

# RHEL/CentOS 7 have reported traffic issues being routed incorrectly due to iptables bypassed
cat <<EOF >  /etc/sysctl.d/k8s.conf 
net.bridge.bridge-nf-call-ip6tables = 1 #네트워크 관련부분 1로 해두는게 좋다.
net.bridge.bridge-nf-call-iptables = 1
EOF
modprobe br_netfilter

# local small dns & vagrant cannot parse and delivery shell code.
echo "192.168.1.10 m-k8s" >> /etc/hosts #노드의 이름을 자동으로 디플로이 하는 부분
for (( i=1; i<=$1; i++  )); do echo "192.168.1.10$i w$i-k8s" >> /etc/hosts; done

# config DNS  
cat <<EOF > /etc/resolv.conf #dns 이슈를 막기위해 고정 시켜둠
nameserver 1.1.1.1 #cloudflare DNS
nameserver 8.8.8.8 #Google DNS
EOF

"k8s_env_build.sh" 쿠버네티스 환경을 구성하는 스크립트

 

 

k8s_pkg_cfg
#!/usr/bin/env bash

# install util packages 
yum install epel-release -y   #centos 패키지 확장
yum install vim-enhanced -y   # 꼭 필요하진않지만 걍써둠
yum install git -y

# install docker 
yum install docker-ce-$2 docker-ce-cli-$2 containerd.io-$3 -y # 메인스크립에서 전달받은 인자값을 사용

# install kubernetes
# both kubelet and kubectl will install by dependency
# but aim to latest version. so fixed version by manually
yum install kubelet-$1 kubectl-$1 kubeadm-$1 -y 

# Ready to install for k8s 
systemctl enable --now docker
systemctl enable --now kubelet

"k8s_pkg_cfg" 쿠버네티스를 설치하기위한 패키지 와 실습 편의성을 높이는 도구 구성

 

k_cfg_n_git_clone

#!/usr/bin/env bash

# install bash-completion for kubectl 
yum install bash-completion -y   #kubectl 명령을 자동완성할수있는 패키지

# kubectl completion on bash-completion dir
kubectl completion bash >/etc/bash_completion.d/kubectl  #자동완성 구현

# alias kubectl to k 
echo 'alias k=kubectl' >> ~/.bashrc
echo 'complete -F __start_kubectl k' >> ~/.bashrc

# git clone k8s-code
git clone https://github.com/sysnet4admin/_Lecture_k8s_learning.kit.git
mv /home/vagrant/_Lecture_k8s_learning.kit $HOME
find $HOME/_Lecture_k8s_learning.kit -regex ".*\.\(sh\)" -exec chmod 700 {} \;

"k_cfg_n_git_clone"

 

 

여기까지 스크립트들을 구성했으면

다운받아야할 친구가있다.

Vagrant, VM virtual box

그리고 나는 많은 노드들을 쉽게 접근하기 위한

Tabby를 설치했다.

Tabby 이 친구 히트다.

 

 

 

이제 Vagrantfile이 있는 경로에서 cmd를 키고

"vagrant up"

을 입력하면 자동으로 노드들이 구성된다.

좀 시간이 걸린다.

 

 

기다리다 보면 이렇게 4개의 노드 친구들이 생긴다.

맨 위쪽이 마스터 노드 그 아래 쪽이 워커노드 3개이다.

 

 

그 전에 먼저 tabby 설정을 해보자

version: 3
profiles:
  - type: ssh
    icon: fas fa-desktop
    options:
      host: 127.0.0.1
      port: 60010
      algorithms:
        hmac:
          - hmac-sha1
          - hmac-sha1-etm@openssh.com
          - hmac-sha2-256
          - hmac-sha2-256-etm@openssh.com
          - hmac-sha2-512
          - hmac-sha2-512-etm@openssh.com
        kex:
          - curve25519-sha256
          - curve25519-sha256@libssh.org
          - diffie-hellman-group-exchange-sha256
          - diffie-hellman-group14-sha256
          - diffie-hellman-group15-sha512
          - diffie-hellman-group16-sha512
          - diffie-hellman-group17-sha512
          - diffie-hellman-group18-sha512
          - ecdh-sha2-nistp256
          - ecdh-sha2-nistp384
          - ecdh-sha2-nistp521
        cipher:
          - aes128-ctr
          - aes128-gcm
          - aes128-gcm@openssh.com
          - aes192-ctr
          - aes256-ctr
          - aes256-gcm
          - aes256-gcm@openssh.com
        serverHostKey:
          - ecdsa-sha2-nistp256
          - ecdsa-sha2-nistp384
          - ecdsa-sha2-nistp521
          - rsa-sha2-256
          - rsa-sha2-512
          - ssh-ed25519
          - ssh-rsa
      auth: password
      privateKeys: []
      forwardedPorts: []
      scripts: []
    weight: -1
    name: m-k8s
    group: 쿠버네티스-클러스터(github_SysNet4Admin)
    color: '#23a1e0'
    id: ssh:custom:m-k8s:0b16cf0c-bf56-47ca-b2ea-b6abbdb1223c
  - type: ssh
    icon: fas fa-desktop
    options:
      host: 127.0.0.1
      port: 60101
      algorithms:
        hmac:
          - hmac-sha1
          - hmac-sha1-etm@openssh.com
          - hmac-sha2-256
          - hmac-sha2-256-etm@openssh.com
          - hmac-sha2-512
          - hmac-sha2-512-etm@openssh.com
        kex:
          - curve25519-sha256
          - curve25519-sha256@libssh.org
          - diffie-hellman-group-exchange-sha256
          - diffie-hellman-group14-sha256
          - diffie-hellman-group15-sha512
          - diffie-hellman-group16-sha512
          - diffie-hellman-group17-sha512
          - diffie-hellman-group18-sha512
          - ecdh-sha2-nistp256
          - ecdh-sha2-nistp384
          - ecdh-sha2-nistp521
        cipher:
          - aes128-ctr
          - aes128-gcm
          - aes128-gcm@openssh.com
          - aes192-ctr
          - aes256-ctr
          - aes256-gcm
          - aes256-gcm@openssh.com
        serverHostKey:
          - ecdsa-sha2-nistp256
          - ecdsa-sha2-nistp384
          - ecdsa-sha2-nistp521
          - rsa-sha2-256
          - rsa-sha2-512
          - ssh-ed25519
          - ssh-rsa
      auth: password
      privateKeys: []
      forwardedPorts: []
      scripts: []
    weight: -1
    name: w1-k8s
    group: 쿠버네티스-클러스터(github_SysNet4Admin)
    id: ssh:custom:w1-k8s:427fde20-56de-40fd-92e2-32e93454e95d
    color: '#8cb63c'
  - type: ssh
    icon: fas fa-desktop
    options:
      host: 127.0.0.1
      port: 60102
      algorithms:
        hmac:
          - hmac-sha1
          - hmac-sha1-etm@openssh.com
          - hmac-sha2-256
          - hmac-sha2-256-etm@openssh.com
          - hmac-sha2-512
          - hmac-sha2-512-etm@openssh.com
        kex:
          - curve25519-sha256
          - curve25519-sha256@libssh.org
          - diffie-hellman-group-exchange-sha256
          - diffie-hellman-group14-sha256
          - diffie-hellman-group15-sha512
          - diffie-hellman-group16-sha512
          - diffie-hellman-group17-sha512
          - diffie-hellman-group18-sha512
          - ecdh-sha2-nistp256
          - ecdh-sha2-nistp384
          - ecdh-sha2-nistp521
        cipher:
          - aes128-ctr
          - aes128-gcm
          - aes128-gcm@openssh.com
          - aes192-ctr
          - aes256-ctr
          - aes256-gcm
          - aes256-gcm@openssh.com
        serverHostKey:
          - ecdsa-sha2-nistp256
          - ecdsa-sha2-nistp384
          - ecdsa-sha2-nistp521
          - rsa-sha2-256
          - rsa-sha2-512
          - ssh-ed25519
          - ssh-rsa
      auth: password
      privateKeys: []
      forwardedPorts: []
      scripts: []
    weight: -1
    group: 쿠버네티스-클러스터(github_SysNet4Admin)
    name: w2-k8s
    id: ssh:custom:w2-k8s:4dd12ddf-adb8-4be6-95a3-65424f25fc14
    color: '#8cb63c'
  - type: ssh
    icon: fas fa-desktop
    options:
      host: 127.0.0.1
      port: 60103
      algorithms:
        hmac:
          - hmac-sha1
          - hmac-sha1-etm@openssh.com
          - hmac-sha2-256
          - hmac-sha2-256-etm@openssh.com
          - hmac-sha2-512
          - hmac-sha2-512-etm@openssh.com
        kex:
          - curve25519-sha256
          - curve25519-sha256@libssh.org
          - diffie-hellman-group-exchange-sha256
          - diffie-hellman-group14-sha256
          - diffie-hellman-group15-sha512
          - diffie-hellman-group16-sha512
          - diffie-hellman-group17-sha512
          - diffie-hellman-group18-sha512
          - ecdh-sha2-nistp256
          - ecdh-sha2-nistp384
          - ecdh-sha2-nistp521
        cipher:
          - aes128-ctr
          - aes128-gcm
          - aes128-gcm@openssh.com
          - aes192-ctr
          - aes256-ctr
          - aes256-gcm
          - aes256-gcm@openssh.com
        serverHostKey:
          - ecdsa-sha2-nistp256
          - ecdsa-sha2-nistp384
          - ecdsa-sha2-nistp521
          - rsa-sha2-256
          - rsa-sha2-512
          - ssh-ed25519
          - ssh-rsa
      auth: password
      privateKeys: []
      forwardedPorts: []
      scripts: []
    weight: -1
    name: w3-k8s
    group: 쿠버네티스-클러스터(github_SysNet4Admin)
    id: ssh:custom:w3-k8s:9bf4212a-acd3-4e2c-84cc-19b1baf367e8
    color: '#8cb63c'
hotkeys:
  toggle-window:
    - Ctrl-Space
  copy-current-path: []
  ctrl-c:
    - Ctrl-C
  copy:
    - ⌘-C
  paste:
    - ⌘-V
  clear:
    - ⌘-K
  select-all:
    - ⌘-A
  zoom-in:
    - ⌘-=
    - ⌘-Shift-=
  zoom-out:
    - ⌘--
    - ⌘-Shift--
  reset-zoom:
    - ⌘-0
  home:
    - ⌘-Left
    - Home
  end:
    - ⌘-Right
    - End
  previous-word:
    - ⌥-Left
  next-word:
    - ⌥-Right
  delete-previous-word:
    - ⌥-Backspace
  delete-line:
    - ⌘-Backspace
  delete-next-word:
    - ⌥-Delete
  search:
    - ⌘-F
  pane-focus-all:
    - ⌘-Shift-I
  focus-all-tabs:
    - ⌘-⌥-Shift-I
  scroll-to-top:
    - Shift-PageUp
  scroll-up:
    - ⌥-PageUp
  scroll-down:
    - ⌥-PageDown
  scroll-to-bottom:
    - Shift-PageDown
  restart-telnet-session: []
  restart-ssh-session: []
  launch-winscp: []
  settings-tab: {}
  settings:
    - ⌘-,
  serial:
    - Alt-K
  restart-serial-session: []
  new-window:
    - ⌘-N
  new-tab:
    - ⌘-T
  profile: {}
  profile-selectors: {}
  toggle-fullscreen:
    - Ctrl+⌘+F
  close-tab:
    - ⌘-W
  reopen-tab:
    - ⌘-Shift-T
  toggle-last-tab: []
  rename-tab:
    - ⌘-R
  next-tab:
    - Ctrl-Tab
  previous-tab:
    - Ctrl-Shift-Tab
  move-tab-left:
    - ⌘-Shift-Left
  move-tab-right:
    - ⌘-Shift-Right
  rearrange-panes:
    - Ctrl-Shift
  tab-1:
    - ⌘-1
  tab-2:
    - ⌘-2
  tab-3:
    - ⌘-3
  tab-4:
    - ⌘-4
  tab-5:
    - ⌘-5
  tab-6:
    - ⌘-6
  tab-7:
    - ⌘-7
  tab-8:
    - ⌘-8
  tab-9:
    - ⌘-9
  tab-10:
    - ⌘-0
  duplicate-tab: []
  restart-tab: []
  explode-tab:
    - ⌘-Shift-.
  combine-tabs:
    - ⌘-Shift-,
  tab-11: []
  tab-12: []
  tab-13: []
  tab-14: []
  tab-15: []
  tab-16: []
  tab-17: []
  tab-18: []
  tab-19: []
  tab-20: []
  split-right:
    - ⌘-Shift-D
  split-bottom:
    - ⌘-D
  split-left: []
  split-top: []
  pane-nav-right:
    - ⌘-⌥-Right
  pane-nav-down:
    - ⌘-⌥-Down
  pane-nav-up:
    - ⌘-⌥-Up
  pane-nav-left:
    - ⌘-⌥-Left
  pane-nav-previous:
    - ⌘-⌥-[
  pane-nav-next:
    - ⌘-⌥-]
  pane-nav-1: []
  pane-nav-2: []
  pane-nav-3: []
  pane-nav-4: []
  pane-nav-5: []
  pane-nav-6: []
  pane-nav-7: []
  pane-nav-8: []
  pane-nav-9: []
  pane-maximize:
    - ⌘-⌥-Enter
  close-pane:
    - ⌘-Shift-W
  pane-increase-vertical: []
  pane-decrease-vertical: []
  pane-increase-horizontal: []
  pane-decrease-horizontal: []
  profile-selector:
    - ⌘-E
  switch-profile:
    - ⌘-Shift-E
  command-selector:
    - ⌘-Shift-P
  reconnect-tab: []
terminal:
  searchOptions: {}
  colorScheme:
    name: Argonaut
    foreground: '#fffaf4'
    background: '#0e1019'
    cursor: '#ff0018'
    colors:
      - '#232323'
      - '#ff000f'
      - '#8ce10b'
      - '#ffb900'
      - '#008df8'
      - '#6d43a6'
      - '#00d8eb'
      - '#ffffff'
      - '#444444'
      - '#ff2740'
      - '#abe15b'
      - '#ffd242'
      - '#0092ff'
      - '#9a5feb'
      - '#67fff0'
      - '#ffffff'
  customColorSchemes: []
ssh:
  knownHosts:
    - host: localhost
      port: 60010
      type: ecdsa-sha2-nistp256
      digest: l6XikZFgOibzSygqZ6+UYHUnEmjFEFhx7PpZw0I3WaM=
    - host: localhost
      port: 60101
      type: ecdsa-sha2-nistp256
      digest: l6XikZFgOibzSygqZ6+UYHUnEmjFEFhx7PpZw0I3WaM=
    - host: 127.0.0.1
      port: 60010
      type: ecdsa-sha2-nistp256
      digest: l6XikZFgOibzSygqZ6+UYHUnEmjFEFhx7PpZw0I3WaM=
    - host: 127.0.0.1
      port: 60101
      type: ecdsa-sha2-nistp256
      digest: l6XikZFgOibzSygqZ6+UYHUnEmjFEFhx7PpZw0I3WaM=
    - host: 127.0.0.1
      port: 60102
      type: ecdsa-sha2-nistp256
      digest: l6XikZFgOibzSygqZ6+UYHUnEmjFEFhx7PpZw0I3WaM=
    - host: 127.0.0.1
      port: 60103
      type: ecdsa-sha2-nistp256
      digest: l6XikZFgOibzSygqZ6+UYHUnEmjFEFhx7PpZw0I3WaM=
configSync:
  parts: {}
clickableLinks: {}
accessibility: {}
appearance: {}
hacks: {}
language: ko-KR
enableWelcomeTab: false
profileDefaults: {}
providerBlacklist: []
pluginBlacklist: []
commandBlacklist: []

이 코드 넣으면 한번에 설정이 완료된다.

 

 

 

Tabby 터미널을 이용해 마스터 노드에 접속 후 "kubeadm" 명령어를 때렸다.

잘 작동한다.

 

그럼 워커노드를 전부 마스터 노드에 연결시켜주는 작업을 해주어야 한다.

 

#!/usr/bin/env bash

# init kubernetes 
# 토큰을 고정시키고 시간을 무한대로 늘려주기
# 파드가 소유할수있는 네트워크를 지정, 쿠버 api 서버의 광고 주소를 마스터노드의 ip주소로 넣었다.
kubeadm init --token 123456.1234567890123456 --token-ttl 0 \
--pod-network-cidr=172.16.0.0/16 --apiserver-advertise-address=192.168.1.10

# config for master node only 
# kubectl의 인증 정보를 자동으로 처리
mkdir -p $HOME/.kube
cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
chown $(id -u):$(id -g) $HOME/.kube/config

# raw_address for gitcontent
raw_git="raw.githubusercontent.com/sysnet4admin/IaC/master/manifests" 

# config for kubernetes's network 
kubectl apply -f https://$raw_git/172.16_net_calico_v1.yaml
# 네트워크 인터페이스 가져오기

마스터노드 배포 WO_master_node

 

 

#!/usr/bin/env bash

# config for work_nodes only 
kubeadm join --token 123456.1234567890123456 \
             --discovery-token-unsafe-skip-ca-verification 192.168.1.10:6443

# kubeadm으로 조인을 한다.

워커노드 WO_work_nodes

 

 

 

마스터 노드에서 'WO_master_node' 파일 실행

 

 

마스터 노드가 구성되어있다.

이제 워커노드 조인을 해보자

 

먼저 실시간 모니터링을 위해

마스터노드에서

"kubectl get node -w"

입력한다.

 

워커노드에서

WO_work_nodes를 실행한다.

 

조인중이다.

나머지 워커노드들도 전부 진행한다.

 

 

전부 조인되었다.

 

cmd에서 "vagrant suspend" 로 노드들 종료

 

'Kubernetes' 카테고리의 다른 글

Kubernetes - 볼륨 1부  (1) 2023.12.21
Kubernetes - 외부노출방법 2부  (0) 2023.12.12
Kubernetes - 외부노출방법 1부  (0) 2023.12.11
Kubernetes - 배포 종류  (1) 2023.12.09
kubernetes - 명령어  (0) 2023.12.06
Comments