오늘 포스팅을 위해

그동안 많은 과정을 거쳐왔나보다 ^^

 

- 오래된 노트북 - 우분투 서버로 만들기 (Ubuntu 20.04 Server)

- Ubuntu 18.04 에서 Python3 편하게 사용하기
- Kubernetes Install (Ubuntu 20.04)
- Kubespray 이용하여 Kubernetes 설치하기
- Vagrant 이미지 업로드 (VirtualBox)
- Vagrant 사용하기 - 기본

- Vagrant 여러 개의 VM 생성하기

 

포스팅으로만 하면 위의 내용 정도뿐이지만,

그 뒤에서 공부하고 시행착오를 겪은 것을 합치면.... 에휴...

멍청하면 손발 뿐만 아니라 온몸이 고생한다더니...

 

 

로컬 환경에서 VM을 이용한 Kubernetes 실습 환경을 갖추는 것이 목표이다.

 

VM 생성도 Vagrant를 이용해서 기본적인 사항은 편하게 할 수 있도록 했고,

Kubernetes 설치 과정은 공부를 위해 직접 수행하는 방식으로 구성했다.

 

즉, Ubuntu 꾸미기(?) 등과 같은 과정은 Skip 하고

공부가 필요한 Kubernetes 설치 과정은 가급적 직접 수행해보자.

 

(물론 Kubespray를 사용하지 않고 정말 쌩으로 해보면 좋겠지만... 어느 정도는 ^^)

 

 

 

0. Host Environment

  - 다음 Spec이 최소사양이라는 말은 아니고, 참고하시라고...

    . CPU: AMD Ryzen 5 3600X

    . RAM: 32GB

    . VGA: Nvidia GeForce RTX 2060

    . OS: Windows 10 Pro

 

 

1. Vagrant 설치

  - https://www.vagrantup.com/

 

 

2. VirtualBox 설치

  - https://www.virtualbox.org/

 

 

3. Vagrant Up

  - 다음 내용의 Vagrantfile을 이용해서 VM을 생성하자

    (개인적인 취향으로 Host의 git-bash 환경에서 작업하는 것을 좋아하기에

     아래 sh 명령어들이 linux 스타일로 되어있다)

 

host$ mkdir k8s-vm
host$ cd k8s-vm
host$ nano Vagrantfile
host$ vagrant up

 

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

N = 2


Vagrant.configure("2") do |config|


  config.vm.define "w-k8s-master" do |cfg|

    cfg.vm.box = "whatwant/Ubuntu-20.04-Server"
    cfg.vm.box_version = "0.2.0"

    cfg.vm.hostname = "master"
    cfg.vm.network "public_network", ip: "192.168.100.200"

    cfg.vm.provider "virtualbox" do |vb|
      vb.gui = false
      vb.cpus = "2"
      vb.memory = "2048"
    end

    cfg.vm.provision "shell", inline: <<-SHELL
      apt-get update
      apt-get upgrade -y
    SHELL

  end


  (1..N).each do |i|
    config.vm.define "w-k8s-worker#{i}" do |cfg|

      cfg.vm.box = "whatwant/Ubuntu-20.04-Server"
      cfg.vm.box_version = "0.2.0"

      cfg.vm.hostname = "worker#{i}"
      cfg.vm.network "public_network", ip: "192.168.100.20#{i}"

      cfg.vm.provider "virtualbox" do |vb|
        vb.gui = false
        vb.cpus = "1"
        vb.memory = "1280"
      end

      cfg.vm.provision "shell", inline: <<-SHELL
        apt-get update
        apt-get upgrade -y
      SHELL

    end
  end

end

 

  - master 1대, worker 2대 구성으로 했다.

  - VM 이미지는 Ubuntu 20.04 Server 기반으로 미리 살짝 꾸며둔 것을 이용했다.

  - VM의 CPU/RAM 설정은 가급적 최소한의 규격으로 잡아두었다.

  - `vagrant up` 했을 때 종종 실패를 하는데, 여러 번 try하면 결국 된다.

  - IP 설정은 각자의 공유기 셋팅에 따라 수정이 필요하다.

 

 

4. (master) Kubespray 실행 환경 만들기

  - Kubespray는 ansible 기반이기에 그에 따른 환경을 갖춰야 한다.

  - 필요한 package 설치 후 ssh 접근이 가능하도록 키 생성 & 배포를 진행한다.

  - 패스워드는 `vagrant`이다.

 

host$ ssh vagrant@192.168.100.200

master$ sudo apt install ansible python3-argcomplete

master$ ssh-keygen

master$ ssh-copy-id 192.168.100.200

master$ ssh-copy-id 192.168.100.201

master$ ssh-copy-id 192.168.100.202

 

  - ansible에서 접근할 서버 정보들을 입력해놓자

$ sudo nano /etc/ansible/hosts
[all]
master  ansible_ssh_host=192.168.100.200 ip=192.168.100.200 ansible_user=vagrant
worker1 ansible_ssh_host=192.168.100.201 ip=192.168.100.201 ansible_user=vagrant
worker2 ansible_ssh_host=192.168.100.202 ip=192.168.100.202 ansible_user=vagrant

[k8s_master]
master

[k8s_worker]
worker1
worker2

  - 테스트

$ ansible all -m ping

 

 

5. (master/worker) Kubernetes 설치를 위한 환경 설정

  - master/worker 모두 Kubernetes 설치를 위한 환경 설정을 진행해야 한다.

  - swap 공간 사용하지 않도록 하고, 서로 접근이 용이하게 되도록 host 설정을 해주자.

  - ip forward 기능도 활성화 시켜줘야 한다.

 

  - master/worker 접근은 앞에서 했던 것과 마찬가지로 `ssh vagrant@192.168.100.200/201/202` 방식으로...

 

master/worker$ sudo swapoff -a

master/worker$ sudo nano /etc/fstab
# /swap.img   none    swap    sw  0   0

master/worker$ sudo sh -c 'echo 1 > /proc/sys/net/ipv4/ip_forward'

master/worker$ sudo nano /etc/hosts
192.168.100.200 master
192.168.100.201 worker1
192.168.100.202 worker2

 

 

6. (master/worker) Restart

  - 깔끔한 진행을 위해 이 시점에서 모두 restart 진행하고 이후 진행하자!

 

 

7. (master) Kubespray 이요한 Kubernetes 설치

  - 이제 기본환경 준비는 끝났다.

  - Kubespray 설치 준비를 할 차례다.

host$ ssh vagrant@192.168.100.200

master$ cd /srv/install

master$ git clone https://github.com/kubernetes-sigs/kubespray.git

master$ cd kubespray

master$ git checkout v2.16.0

master$ sudo pip install -r requirements.txt

master$ cp -rfp inventory/sample inventory/mycluster

master$ declare -a IPS=(192.168.100.200 192.168.100.201 192.168.100.202)

master$ CONFIG_FILE=inventory/mycluster/hosts.yaml python contrib/inventory_builder/inventory.py ${IPS[@]}

master$ nano ./inventory/mycluster/hosts.yaml

  - 아래와 같이 수정해보자.

all:
  hosts:
    master:
      ansible_host: 192.168.100.200
      ip: 192.168.100.200
      access_ip: 192.168.100.200
    worker1:
      ansible_host: 192.168.100.201
      ip: 192.168.100.201
      access_ip: 192.168.100.201
    worker2:
      ansible_host: 192.168.100.202
      ip: 192.168.100.202
      access_ip: 192.168.100.202
  children:
    kube_control_plane:
      hosts:
        master:
    kube_node:
      hosts:
        worker1:
        worker2:
    etcd:
      hosts:
        master:
    k8s_cluster:
      children:
        kube_control_plane:
        kube_node:
    calico_rr:
      hosts: {}

  - 당연하게도 위의 설정은 각자 IP 환경에 맞게 업데이트

 

master$ nano ./inventory/mycluster/group_vars/k8s_cluster/addons.yml

 

  - addons는 아래 3개 정도만 해보자. (ingress는 나중에 직접 설치할 것이다)

dashboard_enabled: true
helm_enabled: true
metrics_server_enabled: true

 

  - proxy mode도 iptables로 변경해보자

master$ nano ./inventory/mycluster/group_vars/k8s_cluster/k8s-cluster.yml
# Kube-proxy proxyMode configuration.
# Can be ipvs, iptables
kube_proxy_mode: iptables

 

 

8. (master) execute

  - 이제 정말로 준비는 끝났다. 설치 시작~!!

master$ cd /srv/install/kubespray

master$ ansible-playbook -i inventory/mycluster/hosts.yaml --become --become-user=root cluster.yml

 

 

9. (master) 계정 설정

  - root가 아닌 일반 계정에서 `kubectl` 명령어를 사용하기 위한 설정을 하자

 

master$ mkdir -p $HOME/.kube

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

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

master$ echo "source <(kubectl completion zsh)" >> ~/.zshrc

master$ source ~/.zshrc

 

 

10. (master) 점검

  - 잘 되었는지 살펴보자.

master$ kubectl cluster-info
Kubernetes control plane is running at https://127.0.0.1:6443

To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.



master$ kubectl get nodes
NAME    STATUS     ROLES                  AGE   VERSION
node1   Ready      control-plane,master   14m   v1.20.7
node2   NotReady   <none>                 13m   v1.20.7
node3   NotReady   <none>                 13m   v1.20.7

 

 

성공~!!!

반응형

'Dev Tools > Kubernetes' 카테고리의 다른 글

Kubernetes 설치  (0) 2023.04.17
Install `NGINX Ingress Controller` in Kubernetes  (4) 2021.09.18
MinIO StandAlone in Kubernetes  (0) 2021.05.13
Kubespray 이용하여 Kubernetes 설치하기  (4) 2021.05.04
Kubernetes Install (Ubuntu 20.04)  (0) 2020.12.28

 

지금까지 Vagrant 공부 내용

- Vagrant 이미지 업로드 (VirtualBox)

- Vagrant 사용하기 - 기본

 

 

지금 Vagrant를 이렇게 정리하면서 공부하는 이유는

Kubernetes 실습 환경 구축을 Vagrant를 이용해서 편하게 VirtualBox로 띄우고 싶어서이다.

 

최소한 "Master 1대 + Worker 2대 = 3대", 또는 "Master 1대 + Worker 3대 = 4대"

구성을 하고자 하는데 앞에서 알아본 Vagrantfile은 VM 1대 구성밖에 안되는 내용이었다.

 

그래서 이번에는 여러개의  VM을 생성하는 Vagrantfile에 대해서 알아보고자 한다.

 

 

지난 포스팅에서 작성해보았던 Vagrantfile을 살펴보면 다음과 같다.

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

Vagrant.configure("2") do |config|

  config.vm.box = "whatwant/Ubuntu-20.04-Server"
  config.vm.box_version = "0.1.0"

  config.vm.network "public_network", ip: "192.168.100.201"

  config.vm.provider "virtualbox" do |vb|
    vb.gui = false
    vb.cpus = "2"
    vb.memory = "2048"
  end

  config.vm.provision "shell", inline: <<-SHELL
    apt-get update
    apt-get upgrade -y
  SHELL

end

 

그러면 여러개의 VM을 정의하는 Vagrantfile은 어떻게 생겼을까?

 

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

N = 2


Vagrant.configure("2") do |config|


  config.vm.define "w-k8s-master" do |cfg|

    cfg.vm.box = "whatwant/Ubuntu-20.04-Server"
    cfg.vm.box_version = "0.2.0"

    cfg.vm.hostname = "master"
    cfg.vm.network "public_network", ip: "192.168.100.200"

    cfg.vm.provider "virtualbox" do |vb|
      vb.gui = false
      vb.cpus = "2"
      vb.memory = "2048"
    end

    cfg.vm.provision "shell", inline: <<-SHELL
      apt-get update
      apt-get upgrade -y
    SHELL

  end


  (1..N).each do |i|
    config.vm.define "w-k8s-worker#{i}" do |cfg|

      cfg.vm.box = "whatwant/Ubuntu-20.04-Server"
      cfg.vm.box_version = "0.2.0"

      cfg.vm.hostname = "worker#{i}"
      cfg.vm.network "public_network", ip: "192.168.100.20#{i}"

      cfg.vm.provider "virtualbox" do |vb|
        vb.gui = false
        vb.cpus = "1"
        vb.memory = "1024"
      end

      cfg.vm.provision "shell", inline: <<-SHELL
        apt-get update
        apt-get upgrade -y
      SHELL

    end
  end


end

 

더 이상 설명할 것이 없을 것 같다.

위의 2개 Vagrantfile을 비교해보면서 살펴보면 될 것 같다.

 

`N = 2` 값을 통해 아래 순환문을 컨트롤 하고...

`#{i}` 값을 통해서 숫자를 변수처럼 할당해서 hostname이나 ip값을 지정해주었다.

 

 

 

별도의 디렉토리를 생성한 뒤

위와 같은 `Vagrantfile`을 작성하고

`vagrant up` 명령어로 실행하면 간단하게 VM이 3개가 생성된다.

 

 

다만, 지난 번부터 `vagrant up` 실행했을 때 오류 메시지와 함께 실패를 종종 경험하게 되어 아쉬운 점은 있다.

다시 `vagrant up`을 하면 성공하기도 하고, 여러번 실행해야 성공하기도 하고

때로는 `vagrant destroy`로 전부 삭제 뒤, 다시 `vagrant up`을 해야하기도 했다.

 

 

밑의 3개 VM이 vagrant로 생성된 아이들이다.

 

반응형

 

Vagrant를 이용해서 VirtualBox에 설치할 이미지 만들기 및 등록까지 했으니

  - https://www.whatwant.com/entry/Vagrant-Box

 

이제는 실제 사용을 해보자.

 

 

01. create Workspace

  - Vagrant 사용을 위해서는 제일 먼저 작업을 실행할 Directory를 하나 만들어야 한다.

  - Workspace 하나 만든다고 생각하면 될 것 같다.

 

> mkdir vagrant-hello

    디렉터리: C:\Users\whatw\workspace

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d-----      2021-07-14   오후 2:00                vagrant-hello



> cd .\vagrant-hello\

 

 

02. init

  - Workspace 안에서 init 작업을 하면 된다.

  - `init` 뒤에는 사용할 이미지 주소를 적어주면 된다.

> vagrant init whatwant/Ubuntu-20.04-Server

==> vagrant: A new version of Vagrant is available: 2.2.17 (installed version: 2.2.16)!
==> vagrant: To upgrade visit: https://www.vagrantup.com/downloads.html

A `Vagrantfile` has been placed in this directory. You are now
ready to `vagrant up` your first virtual environment! Please read
the comments in the Vagrantfile as well as documentation on
`vagrantup.com` for more information on using Vagrant.


> dir

    디렉터리: C:\Users\whatw\workspace\vagrant-hello

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----      2021-07-14   오후 2:04           3104 Vagrantfile

 

03. check Vagrantfile

  - `init`을 하면 `Vagrantfile`을 생성해준다.

  - 첫 줄을 보면 알겠지만, ruby 포맷이다..... ㅠㅜ

 

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

# All Vagrant configuration is done below. The "2" in Vagrant.configure
# configures the configuration version (we support older styles for
# backwards compatibility). Please don't change it unless you know what
# you're doing.
Vagrant.configure("2") do |config|
  # The most common configuration options are documented and commented below.
  # For a complete reference, please see the online documentation at
  # https://docs.vagrantup.com.

  # Every Vagrant development environment requires a box. You can search for
  # boxes at https://vagrantcloud.com/search.
  config.vm.box = "whatwant/Ubuntu-20.04-Server"

  # Disable automatic box update checking. If you disable this, then
  # boxes will only be checked for updates when the user runs
  # `vagrant box outdated`. This is not recommended.
  # config.vm.box_check_update = false

  # Create a forwarded port mapping which allows access to a specific port
  # within the machine from a port on the host machine. In the example below,
  # accessing "localhost:8080" will access port 80 on the guest machine.
  # NOTE: This will enable public access to the opened port
  # config.vm.network "forwarded_port", guest: 80, host: 8080

  # Create a forwarded port mapping which allows access to a specific port
  # within the machine from a port on the host machine and only allow access
  # via 127.0.0.1 to disable public access
  # config.vm.network "forwarded_port", guest: 80, host: 8080, host_ip: "127.0.0.1"

  # Create a private network, which allows host-only access to the machine
  # using a specific IP.
  # config.vm.network "private_network", ip: "192.168.33.10"

  # Create a public network, which generally matched to bridged network.
  # Bridged networks make the machine appear as another physical device on
  # your network.
  # config.vm.network "public_network"

  # Share an additional folder to the guest VM. The first argument is
  # the path on the host to the actual folder. The second argument is
  # the path on the guest to mount the folder. And the optional third
  # argument is a set of non-required options.
  # config.vm.synced_folder "../data", "/vagrant_data"

  # Provider-specific configuration so you can fine-tune various
  # backing providers for Vagrant. These expose provider-specific options.
  # Example for VirtualBox:
  #
  # config.vm.provider "virtualbox" do |vb|
  #   # Display the VirtualBox GUI when booting the machine
  #   vb.gui = true
  #
  #   # Customize the amount of memory on the VM:
  #   vb.memory = "1024"
  # end
  #
  # View the documentation for the provider you are using for more
  # information on available options.

  # Enable provisioning with a shell script. Additional provisioners such as
  # Ansible, Chef, Docker, Puppet and Salt are also available. Please see the
  # documentation for more information about their specific syntax and use.
  # config.vm.provision "shell", inline: <<-SHELL
  #   apt-get update
  #   apt-get install -y apache2
  # SHELL
end

 

04. check IP

  - 이 부분은 필요하신 분들만 선택적으로 하면 된다.

  - Why : 이 부분을 진행하는 이유는 다음과 같다.

    . 집에서 공유기를 사용하고 있음

    . VirtualBox에서 Ubuntu를 여러개를 실행할 계획인데,

    . 서로 간의 통신을 구성하기 위해서 각 Ubuntu의 IP를 고정하고 싶음

 

  - 공유기에서 비어있는 IP를 확인해놓자

 

 

  - 각자의 공유기에 따라 관리 페이지 들어가서 현재 할당되어 있는 IP 내역 확인하고,

  - 나중에 MAC 주소에 따른 IP 할당 설정을 해보자.

 

 

05. edit Vagrant

  - 리소스 포함해서 원하는 VM 모습으로 설정해보자

 

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

Vagrant.configure("2") do |config|

  config.vm.box = "whatwant/Ubuntu-20.04-Server"
  config.vm.box_version = "0.1.0"

  config.vm.network "public_network", ip: "192.168.100.201"

  config.vm.provider "virtualbox" do |vb|
    vb.gui = false
    vb.cpus = "2"
    vb.memory = "2048"
  end

  config.vm.provision "shell", inline: <<-SHELL
    apt-get update
    apt-get upgrade -y
  SHELL

end

 

 

06. Vagrant Up

  - 실행해보자 !!

 

> vagrant up

Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'whatwant/Ubuntu-20.04-Server'...
==> default: Matching MAC address for NAT networking...
==> default: Checking if box 'whatwant/Ubuntu-20.04-Server' version '0.1.0' is up to date...
==> default: Setting the name of the VM: vagrant-hello_default_1626272864694_38723
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
    default: Adapter 2: bridged
==> default: Forwarding ports...
    default: 22 (guest) => 2222 (host) (adapter 1)
==> default: Running 'pre-boot' VM customizations...
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address: 127.0.0.1:2222
    default: SSH username: vagrant
    default: SSH auth method: private key
    default: Warning: Connection reset. Retrying...
    default: Warning: Connection aborted. Retrying...
    default:
    default: Vagrant insecure key detected. Vagrant will automatically replace
    default: this with a newly generated keypair for better security.
    default:
    default: Inserting generated public key within guest...
    default: Removing insecure key from the guest if it's present...
    default: Key inserted! Disconnecting and reconnecting using new SSH key...
==> default: Machine booted and ready!
==> default: Checking for guest additions in VM...
==> default: Configuring and enabling network interfaces...
==> default: Mounting shared folders...
    default: /vagrant => C:/Users/whatw/workspace/vagrant-hello
==> default: Running provisioner: shell...
    default: Running: inline script
    default: Hit:1 http://kr.archive.ubuntu.com/ubuntu focal InRelease
    default: Get:2 http://kr.archive.ubuntu.com/ubuntu focal-updates InRelease [114 kB]
    default: Get:3 http://kr.archive.ubuntu.com/ubuntu focal-backports InRelease [101 kB]
    default: Get:4 http://kr.archive.ubuntu.com/ubuntu focal-security InRelease [114 kB]
    default: Get:5 http://kr.archive.ubuntu.com/ubuntu focal-updates/main amd64 Packages [1,086 kB]
    default: Get:6 http://kr.archive.ubuntu.com/ubuntu focal-updates/main Translation-en [239 kB]
    default: Get:7 http://kr.archive.ubuntu.com/ubuntu focal-updates/main amd64 c-n-f Metadata [13.8 kB]
    default: Get:8 http://kr.archive.ubuntu.com/ubuntu focal-updates/universe amd64 Packages [841 kB]
    default: Get:9 http://kr.archive.ubuntu.com/ubuntu focal-updates/universe Translation-en [176 kB]
    default: Get:10 http://kr.archive.ubuntu.com/ubuntu focal-updates/universe amd64 c-n-f Metadata [18.3 kB]
    default: Get:11 http://kr.archive.ubuntu.com/ubuntu focal-backports/universe amd64 Packages [5,792 B]
    default: Get:12 http://kr.archive.ubuntu.com/ubuntu focal-backports/universe amd64 c-n-f Metadata [288 B]
    default: Get:13 http://kr.archive.ubuntu.com/ubuntu focal-security/main amd64 Packages [745 kB]
    default: Get:14 http://kr.archive.ubuntu.com/ubuntu focal-security/main Translation-en [148 kB]
    default: Get:15 http://kr.archive.ubuntu.com/ubuntu focal-security/main amd64 c-n-f Metadata [8,036 B]
    default: Get:16 http://kr.archive.ubuntu.com/ubuntu focal-security/universe amd64 Packages [629 kB]
    default: Get:17 http://kr.archive.ubuntu.com/ubuntu focal-security/universe Translation-en [96.2 kB]
    default: Get:18 http://kr.archive.ubuntu.com/ubuntu focal-security/universe amd64 c-n-f Metadata [11.6 kB]
    default: Fetched 4,346 kB in 13s (322 kB/s)
    default: Reading package lists...
    default: Reading package lists...
    default: Building dependency tree...
    default:
    default: Reading state information...
    default: Calculating upgrade...
    default: The following packages will be upgraded:
    default:   libuv1 linux-base
    default: 2 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
    default: 1 standard security update
    default: Need to get 98.5 kB of archives.
    default: After this operation, 0 B of additional disk space will be used.
    default: Get:1 http://kr.archive.ubuntu.com/ubuntu focal-updates/main amd64 libuv1 amd64 1.34.2-1ubuntu1.3 [80.8 kB]
    default: Get:2 http://kr.archive.ubuntu.com/ubuntu focal-updates/main amd64 linux-base all 4.5ubuntu3.6 [17.8 kB]
    default: dpkg-preconfigure: unable to re-open stdin: No such file or directory
    default: Fetched 98.5 kB in 1s (73.4 kB/s)
    default: (Reading database ...
(Reading database ... 45%abase ... 5%
(Reading database ... 55%abase ... 50%
    default: (Reading database ... 60%
    default: (Reading database ... 65%
    default: (Reading database ... 70%
    default: (Reading database ... 75%
    default: (Reading database ... 80%
    default: (Reading database ... 85%
    default: (Reading database ... 90%
    default: (Reading database ... 95%
(Reading database ... 145156 files and directories currently installed.)
    default: Preparing to unpack .../libuv1_1.34.2-1ubuntu1.3_amd64.deb ...
    default: Unpacking libuv1:amd64 (1.34.2-1ubuntu1.3) over (1.34.2-1ubuntu1.1) ...
    default: Preparing to unpack .../linux-base_4.5ubuntu3.6_all.deb ...
    default: Unpacking linux-base (4.5ubuntu3.6) over (4.5ubuntu3.5) ...
    default: Setting up linux-base (4.5ubuntu3.6) ...
    default: Setting up libuv1:amd64 (1.34.2-1ubuntu1.3) ...
    default: Processing triggers for man-db (2.9.1-1) ...
    default: Processing triggers for libc-bin (2.31-0ubuntu9.2) ...

 

  - `Vagrantfile`에서 `vb.gui = false` 설정을 했기에, `VirtualBox`가 별도 실행되지 않는다.

  - 직접 `VirtualBox`를 실행해보면 다음과 같이 새로 머신이 하나 추가된 것을 볼 수 있다.

 

 

  - 머신 이름은 새로 생성한 Workspace(Directory) 이름 + 별칭 + 랜덤 숫자 ...

  - 머신을 더블 클릭하면 실행된 머신이 나타난다

 

 

  - 로그인 ID / Password는 모두 `vagrant`

 

 

07. status

  - 현재 `Vagrant`의 상태를 확인해보자.

  - 사용할 수 있는 명령어도 친절히 알려준다.

 

> vagrant status

Current machine states:

default                   running (virtualbox)

The VM is running. To stop this VM, you can run `vagrant halt` to
shut it down forcefully, or you can run `vagrant suspend` to simply
suspend the virtual machine. In either case, to restart it again,
simply run `vagrant up`.

 

여기까지 끄읕~

반응형

 

최근 Docker 또는 Kubernetes 인기로 인하여 Container가 인기의 주역이 되면서

주로 VM 환경과 같이 사용되는 Vagrant의 인기가 많이 줄어든 것 같다.

 

하지만, 여전히 VM에 대한 수요는 있고

Vagrant의 효용성도 여전히 높다고 여겨지기에 공부를 해보려 한다.

 

 

01. Vagrant

  - Vagrant 메인 사이트는 vagrant.com이 아니라 vagrantup.com 이다 ^^

  - https://www.vagrantup.com/

 

 

02. Install

  - 설치는 별거 없다. 그냥 슝슝~

 

 

03. Vagrant Hub ?

  - DockerHub처럼 Vagrant에서도 Hub가 있다 !!

  - https://app.vagrantup.com/

 

 

04. VirtualBox Guest OS 준비

  - Ubuntu 20.04 Server 이미지를 만들어서 업로드 해봤다.

  - Vagrant Box로 만들기 위해서는 다음의 과정을 거쳐야 한다.

 

  ① 작업 환경

    - Host PC(Windows 10)에서 VirtualBox 설치

    - VirtualBox에서 Guest OS로 Ubuntu 20.04 Server 설치

    → Vagrant Box 업로드 用 이미지로 만들기 위한 과정 진행 !!

 

  ② vagrant 계정 생성
    - 패스워드도 vagrant로 설정

$ sudo adduser vagrant

 

 

  ③ visudo 등록

 

$ sudo visudo

# Add the following line to the end of the file.
vagrant ALL=(ALL) NOPASSWD:ALL

 

  ④ SSH 설정

 

$ sudo su vagrant


$ cd

$ mkdir .ssh

$ wget --no-check-certificate https://raw.github.com/mitchellh/vagrant/master/keys/vagrant.pub -O .ssh/authorized_keys

--2021-07-04 18:37:56--  https://raw.github.com/mitchellh/vagrant/master/keys/vagrant.pub
Resolving raw.github.com (raw.github.com)... 185.199.111.133, 185.199.109.133, 185.199.108.133, ...
Connecting to raw.github.com (raw.github.com)|185.199.111.133|:443... connected.
HTTP request sent, awaiting response... 301 Moved Permanently
Location: https://raw.githubusercontent.com/mitchellh/vagrant/master/keys/vagrant.pub [following]
--2021-07-04 18:37:57--  https://raw.githubusercontent.com/mitchellh/vagrant/master/keys/vagrant.pub
Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.108.133, 185.199.111.133, 185.199.110.133, ...
Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.108.133|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 409 [text/plain]
Saving to: ‘.ssh/authorized_keys’

.ssh/authorized_keys             100%[========================================================>]     409  --.-KB/s    in 0s

2021-07-04 18:37:57 (36.9 MB/s) - ‘.ssh/authorized_keys’ saved [409/409]

 

  ⑤ SSH Server 설치

 

$ sudo apt install -y openssh-server

$ sudo nano /etc/ssh/sshd_config

Port 22
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
PermitEmptyPasswords no

$ sudo service ssh restart

 

  ⑥ hostname 변경

    - 이 부분은 꼭 필요한 과정은 아니고, 필요에 따라서...

 

$ hostnamectl set-hostname whatwant

 

  ⑦ 불필요한 계정 정리

    - 이 부분 역시 꼭 필요한 과정은 아니고, 필요에 따라서...

 

$ sudo deluser whatwant

 

  ⑧ 동적 디스크 정리

    - VIrtualBox의 디스크 영역을 깨끗하게 정리하기 위해서 수행

 

$ sudo dd if=/dev/zero of=/EMPTY bs=1M

$ sudo rm -f /EMPTY

 

  ⑨ 시스템 종료

 

$ sudo shutdown -h now

 

 

05. convert Image(Vagrant Box)

  - 이제 준비된 VirtualBox Image를 Vagrant Image로 convert 해보자.

  - VirtualBox Guest 파일들이 저장된 위치를 찾아서 이동

> dir
total 14473272
drwxr-xr-x 1 whatw 197609           0  7월  4 18:30  Logs/
drwxr-xr-x 1 whatw 197609           0  7월  4 18:23  Snapshots/
-rw-r--r-- 1 whatw 197609       20613  7월  4 18:30 'Ubuntu 20.04 Server Worker1.vbox'
-rw-r--r-- 1 whatw 197609       20642  7월  4 18:23 'Ubuntu 20.04 Server Worker1.vbox-prev'
-rw-r--r-- 1 whatw 197609 14820573184  5월  5 16:49 'Ubuntu Server 20.vdi'

  - `package` 명령어를 이용해서 convert 하면 된다.

  - 아래 타이핑한 내역을 잘 살펴보기 바란다 (.vbox 사용하지 않기와 같은...^^)

> vagrant package --base "Ubuntu 20.04 Server Worker1" --out "ubuntu2004server.box"
==> Ubuntu 20.04 Server Worker1: Attempting graceful shutdown of VM...
    Ubuntu 20.04 Server Worker1: Guest communication could not be established! This is usually because
    Ubuntu 20.04 Server Worker1: SSH is not running, the authentication information was changed,
    Ubuntu 20.04 Server Worker1: or some other networking issue. Vagrant will force halt, if
    Ubuntu 20.04 Server Worker1: capable.
==> Ubuntu 20.04 Server Worker1: Forcing shutdown of VM...
==> Ubuntu 20.04 Server Worker1: Exporting VM...
==> Ubuntu 20.04 Server Worker1: Compressing package to: C:/Users/whatw/VirtualBox VMs/Ubuntu 20.04 Server Worker1/ubuntu2004server.box

 

 

06. add Box

  - 위에서 만든 Box를 등록하는 과정이다

> vagrant box add "ubuntu2004server" "C:\Users\whatw\ubuntu2004server.box"

==> box: Box file was not detected as metadata. Adding it directly...
==> box: Adding box 'ubuntu2004server' (v0) for provider:
    box: Unpacking necessary files from: file:///C:/Users/whatw/ubuntu2004server.box
    box:
==> box: Successfully added box 'ubuntu2004server' (v0) for 'virtualbox'!

 

 

07. SHASUM

  - 뒤에 사용될 것을 미리 확인해놓자

  - 파일 이름 뒤의 `SHA256`을 꼭 써줘야 한다!!!

> certutil -hashfile .\ubuntu2004server.box sha256

SHA1의 .\ubuntu2004server.box 해시:
7e6b73addaaea6c430c54dc16fd968ba740c7272e68807e0cf57f6fa5e28c499
CertUtil: -hashfile 명령이 성공적으로 완료되었습니다.

 

08. Vagrant Cloud 준비

  - `03. Vagrant Hub ?`에서 회원가입을 했다면 아래와 같은 화면을 확인할 수 있다.

 

 

  - `Create a new Vagrant Box` 클릭하고 계속 진행해보자.

 

 

 

  - 버전은... 링크로 있는 `RubyGems versioning`을 한 번 확인해보기 바란다.

  - 제대로 사용하도록 하려면 사실 `1.0.0`으로 해주는 것이...

 

 

  - 앞에서 미리 확인한 SHA Checksum 값을 넣어주면 된다. (위의 이미지에 있는 Checksum 값은 틀렸다 ^^)

 

 

  - 업로드~ 쭉~ 쭉~ 쭉쭉쭉~

 

 

  - 처음에는 위와 같이 `unreleased` 상태로 나온다.

  - `Release` 버튼을 눌러버리면 ...

 

 

  - 이제 뭔가 잘 된 것 같다!

 

 

끄읕~~~ (정리는 왠지 항상 힘들어...)

반응형

MinIO

Amazon S3 서비스를 On-Premise 환경에서 사용할 수 있도록 해주는

최근 많은 인기를 얻고 있는 유명한 Object Storage 프로젝트이다.

 

https://min.io/

 

MinIO | High Performance, Kubernetes Native Object Storage

MinIO's High Performance Object Storage is Open Source, Amazon S3 compatible, Kubernetes Native and is designed for cloud native workloads like AI.

min.io

 

AI 개발환경을 On-Premise에서 구축할 때

사진, 동영상 같은 데이터 또는 컨테이너 이미지와 같은 비정형 데이터를 저장하기 위한 서비스 中

설치도 간편하고 Amazon S3와 호환이 되다보니 MinIO가 아주 유명세를 떨쳤다.

 

 

그래서, 신규 시스템을 구축할 때 스토리지 용도로 MinIO를 선택했는데...

막상 해보니... 쉬운 아이가 아닌 것 같다는....

 

 

 

지금부터 설명할 과정은 다음과 같은 환경에서 진행하였다.

 

- VirtualBox Guest 3개 구성

  . Guest OS : Ubuntu 20.04 Server - 64bit

  . Guest HW : CPU 2 core, MEM 4 GB

 

- Kubernetes : 1 master, 2 worker node 구성

  . 설치 도구 : Kubespray

  . K8s version : 1.20.6

 

 

 

MinIO 설치는 Kubernetes 환경에서 Standalone 방식으로 진행해보고자 한다.

 

참고했던 컨텐츠는 아래와 같다.

 

https://github.com/kubernetes/examples/tree/master/staging/storage/minio

 

kubernetes/examples

Kubernetes application example tutorials. Contribute to kubernetes/examples development by creating an account on GitHub.

github.com

 

 

1. StorageClass

    - 특정 노드의 local storage를 실제 저장공간으로 사용하기 위한 내용으로 작성했다.

    - dynamic provisioning을 위해 volumeBindingMode를 'WaitForFirstComsumer'로 잡았다.

 

 

[ minio-standalone-storageclass.yaml ]

apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  name: local-storage

provisioner: kubernetes.io/no-provisioner

volumeBindingMode: WaitForFirstConsumer

 

 

2. PersistentVolume

    - worker node 中 하나인, 'worker2'의 특정 디렉토리를 실제 저장 공간으로 정했다.

 

[ minio-standalone-pv.yaml ]

apiVersion: v1
kind: PersistentVolume
metadata:
  name: local-pv

spec:
  capacity:
    storage: 1Gi

  accessModes:
  - ReadWriteOnce

  persistentVolumeReclaimPolicy: Retain

  storageClassName: local-storage

  local:
    path: /data/volumes/pv1

  nodeAffinity:
    required:
      nodeSelectorTerms:
      - matchExpressions:
        - key: kubernetes.io/hostname
          operator: In
          values:
          - worker2

 

 

3. PersistentVolumeClaim

    - 앞에서 선언한 StorageClass, PersistentVolume과 매핑되는 PVC를 작성했다.

 

[ minio-standalone-pvc.yaml ]

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: minio-pv-claim
  labels:
    app: minio-storage-claim

spec:
  accessModes:
    - ReadWriteOnce

  storageClassName: local-storage

  resources:
    requests:
      storage: 1Gi

 

 

4. Deployment

    - MinIO 서비스를 위한 Deployment이며, 당연히 앞에서 선언한 PVC를 사용했다.

 

[ minio-standalone-deployment.yaml ]

apiVersion: apps/v1
kind: Deployment
metadata:
  name: minio-deployment

spec:
  selector:
    matchLabels:
      app: minio

  strategy:
    type: Recreate

  template:
    metadata:
      labels:
        app: minio

    spec:
      volumes:
      - name: storage
        persistentVolumeClaim:
          claimName: minio-pv-claim

      containers:
      - name: minio
        image: minio/minio:latest
        args:
        - server
        - /storage
        env:
        - name: MINIO_ACCESS_KEY
          value: "minio"
        - name: MINIO_SECRET_KEY
          value: "minio123"
        ports:
        - containerPort: 9000
          hostPort: 9000
        volumeMounts:
        - name: storage
          mountPath: "/storage"

 

 

5. Service

    - MinIO 서비스를 외부로 노출하기 위한 Service를 선언해보았다.

 

[ minio-standalone-service.yaml ]

apiVersion: v1
kind: Service
metadata:
  name: minio-service

spec:
  type: NodePort

  ports:
    - port: 9000
      targetPort: 9000
      nodePort: 30333

  selector:
    app: minio

 

 

[ 결과 ]

여기까지

차례대로 create 하면 MinIO 서비스 웹을 볼 수 있다.

 

MinIO

 

Access Key / Secret Key 값은 Deployment YAML을 보면 확인할 수 있다.

 

 

MinIO

 

 

오른쪽 하단에 있는 "+" 버튼을 통해 bucket도 생성할 수 있고, 파일도 업로드 할 수 있다.

물론 다운로드도 가능한 Storage 웹서비스를 확인할 수 있다.

 

 

반응형

Kubernetes를 쌩으로(?) 설치하기 너무 귀찮기에

조금 편하게 설치하기 위해 Kubespray를 이용해보기로 했다.

 

   - kubernetes.io/ko/docs/setup/production-environment/tools/kubespray/

 

Kubespray로 쿠버네티스 설치하기

이 가이드는 Kubespray를 이용하여 GCE, Azure, OpenStack, AWS, vSphere, Packet(베어메탈), Oracle Cloud infrastructure(실험적) 또는 베어메탈 등에서 운영되는 쿠버네티스 클러스터를 설치하는 과정을 보여준다. Kub

kubernetes.io

설치를 진행한 환경은 다음과 같다.

 

  - Location : Home (SKB Internet - 500Mbps)

  - Host OS : Windows 10 64bit

  - VM S/W : VirtualBox

  - Guest OS : Ubuntu 20.04 Server 64bit (3개 VM)

    . CPU : 2 Core

    . Mem : 4096 MB

    . N/W : Bridge

 

 

1. python 설치

  - 설치되어 있는 python을 확인해보자.

 

$ ls /usr/bin | grep python
python3
python3.8

 

  - ubuntu 20.04 에서는 기본적으로 3.8이 설치되어 있는듯하다.

  - 사용하기 편하도록 기본 `python`에 mapping 하자.

 

$ sudo update-alternatives --config python
update-alternatives: error: no alternatives for python

$ sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.8 1
$ sudo update-alternatives --config python

$ python --version
Python 3.8.5

 

  - `pip`도 설치해보자.

 

$ sudo apt install python3-pip

$ sudo update-alternatives --install /usr/bin/pip pip /usr/bin/pip3 1
$ sudo update-alternatives --config pip3

$ pip --version
pip 20.0.2 from /usr/lib/python3/dist-packages/pip (python 3.8)


2. ansible 설치

  - kubespray는 `ansible`을 기본으로 사용한다.

 

$ sudo apt install ansible python3-argcomplete

$ ansible --version
ansible 2.9.6
  config file = /etc/ansible/ansible.cfg
  configured module search path = ['/home/whatwant/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python3/dist-packages/ansible
  executable location = /usr/bin/ansible
  python version = 3.8.5 (default, Jan 27 2021, 15:41:15) [GCC 9.3.0]

 

3. SSH 키 복사하기

  - `ansible`을 기본으로 사용하기에, 3대의 VM에 ssh 접속을 바로 할 수 있도록 SSH 키를 모두 복사해야 한다.

 

  - `master`로 사용할 VM에서 `ssh-keygen`으로 key를 생성한 뒤, copy하면 된다.

  - 개인적으로 사용하는 SSH 키가 있다면 그것을 사용하면 되고...

 

$ ssh-keygen

$ ssh-copy-id 192.168.122.10
(Master Node와 Worker Node에 모두 키를 복사)

 

 

4. swap 메모리 비활성화

  - kubernetes를 설치하기 위해선 swap 메모리를 모두 비활성화 해야 한다.

  - master/worker node에 사용할 3대의 VM 모두 꺼버리자!

 

$ sudo swapoff -a

 

 

5. ip forward 설정

  - K8s는 가상 네트워크 환경을 사용해야 하기에 ip_forward를 활성화 해야 한다.

  - master/worker node에 사용할 3대의 VM 모두 적용 !!!

 

$ sudo sh -c 'echo 1 > /proc/sys/net/ipv4/ip_forward'

$ cat /proc/sys/net/ipv4/ip_forward
1

 

  - 위와 같은 설정은 본래 재부팅하면 풀려야 하는데... 재부팅해도 그대로 유지되기에 내버려두고 있다.
  - 나중에 한 번 확인해봐야 할 것 같다.

 

 

6. hosts 등록

  - hostname으로 서버에 접속할 수 있도록 hosts 파일에 3개 VM hostname을 등록하자.

  - master/worker node에 사용할 3대의 VM 모두 적용 !!!

 

$ sudo nano /etc/hosts
192.168.100.111 master-stg
192.168.100.112 worker1
192.168.100.113 worker2

 

  - 각자의 hostname 과 IP 상황에 맞게 적용하면 된다.

 

 

7. kubespray 실행

  - `git clone` 받은 뒤, 필요한 패키지 설치하도록 하고, 나만의 환경 설정을 하자.

 

$ git clone https://github.com/kubernetes-sigs/kubespray.git

$ cd kubespray

$ git checkout release-2.15

$ sudo pip install -r requirements.txt

$ cp -rfp inventory/sample inventory/mycluster

$ declare -a IPS=(192.168.100.111 192.168.100.112 192.168.100.113)

$ CONFIG_FILE=inventory/mycluster/hosts.yaml python3 contrib/inventory_builder/inventory.py ${IPS[@]}

 

  - `cp`를 하는 것은, sample을 기본으로 나만의 inventory를 만들기 위함이다.

  - `declare`는 설치할 VM들의 IP를 적어주면 된다.

  - `CONFIG_FILE`을 실행하면 `declare`로 알려준 VM 정보들을 이용하여 config file을 만들어준다.

 

  - master node로 사용할 아이와 worker node를 사용할 아이들에 대해서 설정을 맞춰주자.

  - hostname도 맞춰서 적어주는 것이 좋다.

 

$ nano inventory/mycluster/hosts.yaml

all:
  hosts:
    master-stg:
      ansible_host: 192.168.100.111
      ip: 192.168.100.111
      access_ip: 192.168.100.111
    worker1:
      ansible_host: 192.168.100.112
      ip: 192.168.100.112
      access_ip: 192.168.100.112
    worker2:
      ansible_host: 192.168.100.113
      ip: 192.168.100.113
      access_ip: 192.168.100.113
  children:
    kube_control_plane:
      hosts:
        master-stg:
    kube_node:
      hosts:
        worker1:
        worker2:
    etcd:
      hosts:
        master-stg:
    k8s_cluster:
      children:
        kube_control_plane:
        kube_node:
    calico_rr:
      hosts: {}

 

  - addon도 필요한 것들을 true로 만들어주자.

 

$ nano ./inventory/mycluster/group_vars/k8s_cluster/addons.yml

dashboard_enabled: true
metrics_server_enabled: true
ingress_nginx_enabled: true

 

 

8. Static IP 설정

  - DHCP 설정으로 되어있으면 Node의 `/etc/resolv.conf`에 잡스러운(?) 내용이 들어가고

  - 그렇게 되면 K8s의 coredns에서 Node의 `/etc/resolv.conf`를 참고하게 되면서

  - Pod의 Container 안에 있는 `/etc/resolv.conf`에도 그 내용이 반영되어서

  - FQDN 관련해서 원하지 않는 결과가 나올 수 있다.

 

❯ cd /etc/netplan/

❯ sudo cp ./00-installer-config.yaml ./00-installer-config.yaml.210504

❯ sudo nano ./00-installer-config.yaml

network:
  ethernets:
    enp0s3:
      dhcp4: no
      dhcp6: no
      addresses: [192.168.100.111/24]
      gateway4: 192.168.100.1
      nameservers:
        addresses: [8.8.8.8,8.8.4.4]
  version: 2

 

 

 

 

9. 설치

  - 이제 준비는 끝났다. 고! 고!

 

$ ansible-playbook -i inventory/mycluster/hosts.yaml  --become --become-user=root cluster.yml

 

 

10. 사용자 계정 설정

  - root 계정이 아닌 사용자 계정에서 `kubectl` 명령어를 사용하기 위해서는 다음과 같이...

 

$ mkdir -p $HOME/.kube

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

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

 

11. zsh 자동 완성 셋팅

 

 

> echo "source <(kubectl completion zsh)" >> ~/.zshrc
> source ~/.zshrc

 

 

 

12. 재부팅 후

  - 희한하게 서버들을 재부팅 하고, `kubectl` 사용을 하면 API Server 연결을 거부당했다는 메시지가 나온다.

  - 그러면 swap 메모리 설정을 한 번 해주면 해결이 된다.

 

$ sudo swapoff -a

 

 

13. 결과

  - 이렇게 잘 나온다~

 

$ kubectl get nodes -o wide
NAME         STATUS   ROLES                  AGE   VERSION   INTERNAL-IP       EXTERNAL-IP   OS-IMAGE             KERNEL-VERSION     CONTAINER-RUNTIME
master-stg   Ready    control-plane,master   37h   v1.20.6   192.168.100.111   <none>        Ubuntu 20.04.2 LTS   5.4.0-72-generic   docker://19.3.15
worker1      Ready    <none>                 37h   v1.20.6   192.168.100.112   <none>        Ubuntu 20.04.2 LTS   5.4.0-72-generic   docker://19.3.15
worker2      Ready    <none>                 37h   v1.20.6   192.168.100.113   <none>        Ubuntu 20.04.2 LTS   5.4.0-72-generic   docker://19.3.15

 

반응형

 

 

Kubernetes 설치를 해보자 한다.

 

 

Master Node & Worker Node 각 1대씩 구성을 하고자 한다.

 

물리적으로 분리된 BareMetal 구성을 하려고 했지만,

자유로운 설정을 통해 학습해보기 위해서 VirtualBox로 우선 진행해 보았다.

 

 

정말 훌륭한 레퍼런스는 아래 링크와 같다 !!!

  - https://medium.com/finda-tech/overview-8d169b2a54ff

 

 

 

 

1. Master & Worker Node H/W

 

  - Prerequisite

 

구분  CPU Memory Storage 
 Master 2 core 3 GB 30 GB
 Worker 2 core 2 GB 30 GB

 

  - VirtualBox

 

구분  CPU Memory Storage 
 Master 2 core 4 GB 50 GB
 Worker 2 core 4 GB 50 GB

 

    . 네트워크는 NAT가 아니라 Bridge로 잡아줬다. (공유기 환경)

 

 

 

 

 

2. Master & Worker Node S/W

 

  - Ubuntu 20.04 LTS Server 설치를 하면서, 기본적인 환경 설치는 아래 링크와 동일하게 구성하였다.

    . https://www.whatwant.com/entry/notebook-ubuntu-server

 

  - Docker 까지는 미리 설치해두었다. 설치 방법은 아래 링크와 같이 진행하였다.

    . https://www.whatwant.com/entry/Docker-Install-Ubuntu-Server-2004

 

    . kubernetes validated versions이 따로 있으니 이것에 맞추는 것을 추천한다.

 

 

 

 

3. Swap off

 

  - kubelet에서 swap을 지원하지 않기 때문에, Master/Worker 모두 swap 기능을 꺼야 한다.

 

$ sudo swapoff -a

 

  - 영구적으로 기능을 끄기 위해서는 추가 작업도 해줘야 한다.

 

$ sudo nano /etc/fstab

 

  - swap 부분을 찾아서 주석 처리 해주면 된다.

 

#/swap.img  none    swap    sw  0   0

 

 

 

 

4. cgroup driver 설정

 

  - 이미 설치된 docker에 대해서 cgroup driver를 변경해줘야 한다.

 

$ docker info

 

 

  - 지금은 "cgroupfs"로 설정되어 있는 것을 볼 수 있다. "systemd"로 변경해보자.

 

$ sudo nano /etc/docker/daemon.json

 

{

    "exec-opts": ["native.cgroupdriver=systemd"],

    "log-driver": "json-file",

    "log-opts": {

        "max-size": "100m"

    },

    "storage-driver": "overlay2"

}

 

$ sudo mkdir -p /etc/systemd/system/docker.service.d

 

$ sudo systemctl daemon-reload

 

$ sudo systemctl restart docker

 

 

  - "cgroup driver"가 잘 변경된 것을 볼 수 있다.

 

 

 

 

5. Kubernetes 기본 패키지 설치

 

  - Master/Worker Node 모두 [ kubeadm, kubelet, kubectl ] 3개의 패키지가 설치되어야 한다.

    . 부수적으로 [ kubernetes-cni, cri-tools ] 2개 패키지도 필요하다.

 

  - 아래에서 최신 버전의 주소(파일명) 확인 (16.04 이후 버전 모두 동일)

    . https://packages.cloud.google.com/apt/dists/kubernetes-xenial/main/binary-amd64/Packages

 

$ wget https://packages.cloud.google.com/apt/pool/cri-tools_1.13.0-01_amd64_4ff4588f5589826775f4a3bebd95aec5b9fb591ba8fb89a62845ffa8efe8cf22.deb

 

$ wget https://packages.cloud.google.com/apt/pool/kubeadm_1.20.1-00_amd64_7cd8d4021bb251862b755ed9c240091a532b89e6c796d58c3fdea7c9a72b878f.deb

 

$ wget https://packages.cloud.google.com/apt/pool/kubectl_1.20.1-00_amd64_b927311062e6a4610d9ac3bc8560457ab23fbd697a3052c394a1d7cc9e46a17d.deb

 

$ wget https://packages.cloud.google.com/apt/pool/kubelet_1.20.1-00_amd64_560a52294b8b339e0ca8ddbc480218e93ebb01daef0446887803815bcd0c41eb.deb

 

$ wget https://packages.cloud.google.com/apt/pool/kubernetes-cni_0.8.7-00_amd64_ca2303ea0eecadf379c65bad855f9ad7c95c16502c0e7b3d50edcb53403c500f.deb

 

  - 설치도 진행하자

 

$ sudo apt-get install socat conntrack ebtables

 

$ sudo dpkg --install ./kubernetes-cni_0.8.7-00_amd64_ca2303ea0eecadf379c65bad855f9ad7c95c16502c0e7b3d50edcb53403c500f.deb

 

$ sudo dpkg --install ./kubelet_1.20.1-00_amd64_560a52294b8b339e0ca8ddbc480218e93ebb01daef0446887803815bcd0c41eb.deb

 

$ sudo dpkg --install ./cri-tools_1.13.0-01_amd64_4ff4588f5589826775f4a3bebd95aec5b9fb591ba8fb89a62845ffa8efe8cf22.deb

 

$ sudo dpkg --install ./kubectl_1.20.1-00_amd64_b927311062e6a4610d9ac3bc8560457ab23fbd697a3052c394a1d7cc9e46a17d.deb

 

$ sudo dpkg --install ./kubeadm_1.20.1-00_amd64_7cd8d4021bb251862b755ed9c240091a532b89e6c796d58c3fdea7c9a72b878f.deb

 

 

 

 

6. Master Node 셋업

 

  - kubeadm을 이용하여 Master Node 셋업을 진행하자.

 

  - Master Node의 IP를 확인하자

 

$ ifconfig

 

  - 이제 셋업 시작~!! (뒤의 IP는 방금 확인한 IP로 교체!!)

 

$ sudo kubeadm init --pod-network-cidr=10.244.0.0/16 --apiserver-advertise-address=192.168.100.119

 

❯ sudo kubeadm init --pod-network-cidr=10.244.0.0/16 --apiserver-advertise-address=192.168.100.119

[init] Using Kubernetes version: v1.20.1

[preflight] Running pre-flight checks

[WARNING SystemVerification]: this Docker version is not on the list of validated versions: 20.10.1. Latest validated version: 19.03

[preflight] Pulling images required for setting up a Kubernetes cluster

[preflight] This might take a minute or two, depending on the speed of your internet connection

[preflight] You can also perform this action in beforehand using 'kubeadm config images pull'

[certs] Using certificateDir folder "/etc/kubernetes/pki"

[certs] Generating "ca" certificate and key

[certs] Generating "apiserver" certificate and key

[certs] apiserver serving cert is signed for DNS names [kubernetes kubernetes.default kubernetes.default.svc kubernetes.default.svc.cluster.local master-stg] and IPs [10.96.0.1 192.168.100.119]

[certs] Generating "apiserver-kubelet-client" certificate and key

[certs] Generating "front-proxy-ca" certificate and key

[certs] Generating "front-proxy-client" certificate and key

[certs] Generating "etcd/ca" certificate and key

[certs] Generating "etcd/server" certificate and key

[certs] etcd/server serving cert is signed for DNS names [localhost master-stg] and IPs [192.168.100.119 127.0.0.1 ::1]

[certs] Generating "etcd/peer" certificate and key

[certs] etcd/peer serving cert is signed for DNS names [localhost master-stg] and IPs [192.168.100.119 127.0.0.1 ::1]

[certs] Generating "etcd/healthcheck-client" certificate and key

[certs] Generating "apiserver-etcd-client" certificate and key

[certs] Generating "sa" key and public key

[kubeconfig] Using kubeconfig folder "/etc/kubernetes"

[kubeconfig] Writing "admin.conf" kubeconfig file

[kubeconfig] Writing "kubelet.conf" kubeconfig file

[kubeconfig] Writing "controller-manager.conf" kubeconfig file

[kubeconfig] Writing "scheduler.conf" kubeconfig file

[kubelet-start] Writing kubelet environment file with flags to file "/var/lib/kubelet/kubeadm-flags.env"

[kubelet-start] Writing kubelet configuration to file "/var/lib/kubelet/config.yaml"

[kubelet-start] Starting the kubelet

[control-plane] Using manifest folder "/etc/kubernetes/manifests"

[control-plane] Creating static Pod manifest for "kube-apiserver"

[control-plane] Creating static Pod manifest for "kube-controller-manager"

[control-plane] Creating static Pod manifest for "kube-scheduler"

[etcd] Creating static Pod manifest for local etcd in "/etc/kubernetes/manifests"

[wait-control-plane] Waiting for the kubelet to boot up the control plane as static Pods from directory "/etc/kubernetes/manifests". This can take up to 4m0s

[apiclient] All control plane components are healthy after 13.002889 seconds

[upload-config] Storing the configuration used in ConfigMap "kubeadm-config" in the "kube-system" Namespace

[kubelet] Creating a ConfigMap "kubelet-config-1.20" in namespace kube-system with the configuration for the kubelets in the cluster

[upload-certs] Skipping phase. Please see --upload-certs

[mark-control-plane] Marking the node master-stg as control-plane by adding the labels "node-role.kubernetes.io/master=''" and "node-role.kubernetes.io/control-plane='' (deprecated)"

[mark-control-plane] Marking the node master-stg as control-plane by adding the taints [node-role.kubernetes.io/master:NoSchedule]

[bootstrap-token] Using token: t4tcwj.22xh9lzstu56qyrb

[bootstrap-token] Configuring bootstrap tokens, cluster-info ConfigMap, RBAC Roles

[bootstrap-token] configured RBAC rules to allow Node Bootstrap tokens to get nodes

[bootstrap-token] configured RBAC rules to allow Node Bootstrap tokens to post CSRs in order for nodes to get long term certificate credentials

[bootstrap-token] configured RBAC rules to allow the csrapprover controller automatically approve CSRs from a Node Bootstrap Token

[bootstrap-token] configured RBAC rules to allow certificate rotation for all node client certificates in the cluster

[bootstrap-token] Creating the "cluster-info" ConfigMap in the "kube-public" namespace

[kubelet-finalize] Updating "/etc/kubernetes/kubelet.conf" to point to a rotatable kubelet client certificate and key

[addons] Applied essential addon: CoreDNS

[addons] Applied essential addon: kube-proxy

 

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

 

Alternatively, if you are the root user, you can run:

 

  export KUBECONFIG=/etc/kubernetes/admin.conf

 

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.100.119:6443 --token t4tcwj.22xh9lzstu56qyrb \

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

 

  - 사용자 계정에서 kubectl 실행을 위해 위의 가이드 내용 그대로 진행을 해보자.

 

$ mkdir -p $HOME/.kube

 

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

 

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

 

  - 잘 설치가 된 것을 확인해보자.

 

$ kubectl get pods --all-namespaces

 

$ kubectl get nodes

 

 

 

  - Pod Network 환경을 맞춰야 하는데, k8s 를 위한 layer 3 환경을 구축해주는 flannel을 사용해보겠다.

    . https://github.com/coreos/flannel/

 

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

 

 

  - coredns가 pending에서 running으로 바뀌었고, flannel이 추가 되었고, Master Node가 Ready 상태가 된 것을 볼 수 있다.

 

 
 
7. Worker Node 셋업
 
  - 기본 환경 설치를 모두 했다면, 아래 명령어만 실행하면 된다.
  - 아래 명령어는 Master Node 설치할 때 나왔던 가이드 밑에 있는 부분 그대로 하면 된다. (각자의 환경에 따라서 실행할 것!!!)
 
$ sudo kubeadm join 192.168.100.119:6443 --token t4tcwj.22xh9lzstu56qyrb \
    --discovery-token-ca-cert-hash sha256:eb3765b58c9140c9a89daf7ea21444ca44a142939ebb93aedad1ebc03202a1d7
 
❯ sudo kubeadm join 192.168.100.119:6443 --token t4tcwj.22xh9lzstu56qyrb \
    --discovery-token-ca-cert-hash sha256:eb3765b58c9140c9a89daf7ea21444ca44a142939ebb93aedad1ebc03202a1d7
 
[preflight] Running pre-flight checks
[WARNING SystemVerification]: this Docker version is not on the list of validated versions: 20.10.1. Latest validated version: 19.03
[preflight] Reading configuration from the cluster...
[preflight] FYI: You can look at this config file with 'kubectl -n kube-system get cm kubeadm-config -o yaml'
[kubelet-start] Writing kubelet configuration to file "/var/lib/kubelet/config.yaml"
[kubelet-start] Writing kubelet environment file with flags to file "/var/lib/kubelet/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.
 
  - Master Node에서 잘 붙었는지 확인해보자.
 
$ kubectl get nodes
 

 

 
 
 
 
 
8. hello kubernetes
 
  - Master Node에서 다음과 같이 deployment를 실행해보자.
 
$ kubectl create deployment kubernetes-bootcamp --image=gcr.io/google-samples/kubernetes-bootcamp:v1
 
  - 잘 되었는지 확인도 해보자.
 
$ kubectl get deployments
 
$ kubectl get pods -o wide
 

 

  - Worker Node에서 해당 서비스가 잘 되는지 확인해보자.

 

$ curl http://10.244.1.2:8080

 

 

 

 

 

 

여기까지~

 

 

반응형


오래된 노트북으로 서버 한 대를 셋팅하던 중, Docker를 설치하는 과정을 기록해보려 한다.



공식 홈페이지 가이드를 따라서 진행했다.

- https://docs.docker.com/engine/installation/linux/ubuntu/



※ 이 블로그를 계속 봐오신 분들은 아시겠지만... 아래 내용은 직접 실행해보면서 작성한 것입니다.



1. Ubuntu version

    - Ubuntu Focal 20.04 (LTS)


❯ lsb_release -a

No LSB modules are available.

Distributor ID: Ubuntu

Description: Ubuntu 20.04.1 LTS

Release: 20.04

Codename: focal


❯ uname -a  

Linux whatwant 5.4.0-58-generic #64-Ubuntu SMP Wed Dec 9 08:16:25 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux



2. Binary 확인

    - 웹으로 다운로드 받을 버전을 확인하자.


https://download.docker.com/linux/ubuntu/dists/focal/pool/stable/amd64/



3. Download 받기


$ wget https://download.docker.com/linux/ubuntu/dists/focal/pool/stable/amd64/containerd.io_1.4.3-1_amd64.deb

$ wget https://download.docker.com/linux/ubuntu/dists/focal/pool/stable/amd64/docker-ce-cli_20.10.1~3-0~ubuntu-focal_amd64.deb

$ wget https://download.docker.com/linux/ubuntu/dists/focal/pool/stable/amd64/docker-ce_20.10.1~3-0~ubuntu-focal_amd64.deb



4. Docker 설치하기


$ sudo dpkg --install ./containerd.io_1.4.3-1_amd64.deb

$ sudo dpkg --install ./docker-ce-cli_20.10.1~3-0~ubuntu-focal_amd64.deb

$ sudo dpkg --install ./docker-ce_20.10.1~3-0~ubuntu-focal_amd64.deb



5. sudo 없이 실행하기


$ sudo usermod -aG docker $USER


  - 로그아웃 후 재로그인해야 적용



6. Hello World


$ docker run hello-world

Unable to find image 'hello-world:latest' locally

latest: Pulling from library/hello-world

0e03bdcc26d7: Pull complete 

Digest: sha256:1a523af650137b8accdaed439c17d684df61ee4d74feac151b5b337bd29e7eec

Status: Downloaded newer image for hello-world:latest


Hello from Docker!

This message shows that your installation appears to be working correctly.


To generate this message, Docker took the following steps:

 1. The Docker client contacted the Docker daemon.

 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.

    (amd64)

 3. The Docker daemon created a new container from that image which runs the

    executable that produces the output you are currently reading.

 4. The Docker daemon streamed that output to the Docker client, which sent it

    to your terminal.


To try something more ambitious, you can run an Ubuntu container with:

 $ docker run -it ubuntu bash


Share images, automate workflows, and more with a free Docker ID:

 https://hub.docker.com/


For more examples and ideas, visit:

 https://docs.docker.com/get-started/



끝~



반응형

+ Recent posts