카테고리 없음

Kubernetes Explorer: From Zero to Inception-of-Things

BOOKSEAL 2025. 5. 1. 22:41

(이 문서는 이전에 생성된 "Kubernetes Explorer 00"과 "01" 매뉴얼을 통합한 버전입니다. 쿠버네티스 기본 개념부터 실전 프로젝트까지 다룹니다.)
(This document combines the previously generated "Kubernetes Explorer 00" and "01" manuals, covering basic Kubernetes concepts through to a hands-on project.)

 

Part 0: Mastering Container Orchestration / Part 0: 컨테이너 오케스트레이션 마스터하기

What's next after Docker Compose? Want a smarter way to handle many Docker containers? Let's explore Kubernetes! This wiki uses our meeting notes to guide you through the key ideas of Kubernetes in an easy and interesting way.

도커 컴포즈 다음 단계는 무엇일까요? 여러 개의 도커 컨테이너를 더 스마트하게 관리하고 싶으신가요? 쿠버네티스의 세계로 떠나봅시다! 이 위키는 회의록을 바탕으로 쿠버네티스의 핵심 개념을 쉽고 흥미롭게 안내합니다.


Step 1: First Look at Kubernetes - K8s vs K3s / 1단계: 쿠버네티스 첫인상 - K8s vs K3s

  • What is Kubernetes (K8s)?: It's a powerful tool to manage and deploy many Docker containers together. Think of it like a conductor leading an orchestra of containers.
  • 쿠버네티스(K8s)란 무엇일까요?: 여러 개의 도커 컨테이너를 묶어 관리하고 배포하는 강력한 도구입니다. 마치 오케스트라 지휘자처럼 컨테이너들을 조율하죠.
  • But what is K3s?: It's a lighter version of K8s with just the essential features. It has fewer parts and is smaller to install (under 100MB!), making it easier to learn and test. The name '3' is like half of '8', showing it's lighter.
  • 그런데 K3s는 뭔가요?: K8s의 핵심 기능만 남긴 가벼운 버전입니다. 모듈 수가 적고 설치 용량도 작아서(100MB 이하!) 배우거나 테스트하기에 부담이 적습니다. '8'을 반으로 가른 '3'이라는 이름처럼, 더 가볍고 빠르죠!
  • Why start with K3s?: The main ideas are similar to K8s, but it's simpler, which is great for beginners. It's light, so it can even run in places with fewer resources, like embedded devices.
  • 왜 K3s로 시작할까요?: 핵심 개념은 K8s와 비슷하지만, 구조가 단순해서 처음 배우기 좋습니다. 가볍기 때문에 리소스가 적은 환경(임베디드 등)에서도 사용할 수 있다고 합니다.

Step 2: Looking Inside Kubernetes - Core Parts / 2단계: 쿠버네티스 핵심 부품 살펴보기

  • Pod: The smallest unit you deploy in Kubernetes. It holds one or more Docker containers. Think of it as almost the same as a Docker container.
  • Pod (파드): 쿠버네티스 배포의 가장 작은 단위입니다. 도커 컨테이너 하나 또는 여러 개가 모여 하나의 파드를 이룹니다. 도커 컨테이너와 거의 같다고 생각해도 좋습니다.
  • Node: A worker machine (real server or virtual machine) where Pods run. A Node groups multiple Pods.
  • Node (노드): 파드들이 실제로 실행되는 작업 공간(물리 서버 또는 가상 머신)입니다. 여러 개의 파드를 묶어서 하나의 노드가 됩니다.
  • Cluster: The whole system, made up of multiple Nodes grouped together. Like managing computers in different data centers (Seoul, Chuncheon, Seongnam) as one.
  • Cluster (클러스터): 여러 노드를 묶은 전체 시스템입니다. 서울, 춘천, 성남에 있는 데이터 센터 컴퓨터들을 하나로 묶어 관리하는 것과 비슷합니다.
  • kubectl: The command-line tool (CLI) to talk to your Kubernetes cluster. Both K8s and K3s use the same commands.
  • kubectl (큐브컨트롤): 쿠버네티스 클러스터와 대화하는 명령어 도구(CLI)입니다. K8s와 K3s 모두 동일한 명령어를 사용합니다.
  • Kubelet: An agent that runs on each Node. It gets instructions from the master and manages the Pods on its Node, like a site manager.
  • Kubelet (큐블렛): 각 노드에서 실행되며, 마스터의 지시를 받아 파드를 관리하는 '현장 감독관' 같은 에이전트입니다.
  • Control Plane / Server: The 'brain' of the cluster that manages and controls everything. Usually, you don't run your apps (Pods) directly here; they run on Agent/Worker Nodes. K8s often calls this the Control Plane, while K3s might call it the Server.
  • Control Plane (컨트롤 플레인) / Server: 클러스터 전체를 관리하고 제어하는 '두뇌'입니다. 워크로드(애플리케이션 파드)는 보통 여기에 직접 올리지 않고, 에이전트 노드에 배치합니다. K8s에서는 컨트롤 플레인, K3s에서는 서버라고 부르기도 합니다.
  • etcd / Built-in DB: A database that stores all the information about the cluster's state (like which Pods are running where). K8s usually uses etcd, while K3s uses its own lightweight built-in database (like Kine). This stores Kubernetes' own info, different from a Docker Compose volume.
  • etcd / 내장 DB: 클러스터의 모든 상태 정보(어떤 파드가 어디서 실행 중인지 등)를 저장하는 데이터베이스입니다. K8s는 보통 etcd를, K3s는 자체 개발한 가벼운 내장 DB(예: Kine)를 사용합니다. 도커 컴포즈의 볼륨과는 다른, 쿠버네티스 자체 메타데이터 저장소입니다.

Step 3: Magic of Deploying and Managing Apps / 3단계: 애플리케이션 배포와 관리 마법

  • Deployment: Defines how to deploy and update your application (Pods). You can tell it, "Always keep 3 copies of this app running".
  • Deployment (디플로이먼트): 애플리케이션(파드)을 어떻게 배포하고 업데이트할지 정의합니다. "이 앱은 항상 3개를 실행시켜줘" 같은 명령을 내릴 수 있습니다.
  • ReplicaSet: Works with Deployments to make sure the right number of Pod copies (replicas) are always running. If a Pod dies, the ReplicaSet automatically starts a new one to prevent downtime. Having extra copies might seem wasteful, but it's key for keeping your service stable.
  • ReplicaSet (레플리카셋): 디플로이먼트의 지시에 따라 지정된 수의 파드 복제본을 항상 유지하는 역할을 합니다. 만약 파드 하나가 죽으면, 레플리카셋이 자동으로 새 파드를 띄워 서비스 중단을 막습니다. 놀고 있는 복제본이 낭비처럼 보일 수 있지만, 서비스 안정성을 위한 필수 요소입니다.
  • Service: Groups Pods together and gives them a single, stable network address (endpoint) so they can be reached from inside or outside the cluster. This is different from the services: in Docker Compose. Kubernetes Services are more about managing network connections for Pods.
  • Service (서비스): 여러 파드를 하나로 묶어 외부 또는 내부에서 접근할 수 있는 고정된 네트워크 주소(엔드포인트)를 제공합니다. 도커 컴포즈의 services: 와는 역할이 다릅니다. 쿠버네티스의 서비스는 파드들을 관리하고 연결하는 네트워크 개념에 가깝습니다.
  • Ingress: Acts as a 'gateway' for traffic coming from outside the cluster to reach services inside. It can set up rules, like sending traffic to different services based on the URL path.
  • Ingress (인그레스): 클러스터 외부에서 내부 서비스로 들어오는 트래픽을 관리하는 '관문'입니다. URL 경로에 따라 다른 서비스로 트래픽을 보내는 라우팅 규칙 등을 설정할 수 있습니다.
  • Load Balancing: Spreads incoming traffic evenly across multiple Pods behind a Service or Ingress. It can even automatically increase the number of Pods if traffic gets heavy.
  • Load Balancing (로드 밸런싱): 서비스나 인그레스를 통해 들어온 트래픽을 여러 파드에 골고루 분산시켜 주는 기능입니다. 트래픽이 몰리면 자동으로 파드 수를 늘리는 것도 가능합니다.

Step 4: Handy Tools for Easier Kubernetes Use / 4단계: 더 편리한 쿠버네티스 활용 도구들

  • Argo CD: A tool for GitOps. It automatically syncs the state defined in a Git repository with the actual state of your Kubernetes cluster. When you push code changes to Git, Argo CD detects them, deploys them to the cluster, and monitors the status.
  • Argo CD: Git 저장소에 정의된 상태와 쿠버네티스 클러스터의 실제 상태를 자동으로 동기화해주는 도구(GitOps)입니다. 코드 변경 사항을 Git에 푸시하면 Argo CD가 감지하여 클러스터에 자동으로 배포하고, 상태를 모니터링합니다.
  • Vagrant: A tool to easily create and manage Virtual Machine (VM) environments using code. It controls VM software like VirtualBox through APIs to automate everything from downloading an Ubuntu image to setting up networking and creating VMs. Useful for setting up a Kubernetes practice environment (Server Node VM, Agent Node VM).
  • Vagrant (바그란트): 코드를 통해 가상 머신(VM) 환경을 쉽게 만들고 관리하는 도구입니다. VirtualBox 같은 VM 프로그램을 API로 제어하여, 우분투 이미지 다운로드부터 네트워크 설정, VM 생성까지 스크립트로 자동화할 수 있습니다. 쿠버네티스 실습 환경(서버 노드, 에이전트 노드 VM) 구축에 유용합니다.
  • K3d: A tool to quickly create K3s clusters locally using Docker. It runs K3s inside Docker containers without needing full VMs, making it a very fast and light way to test Kubernetes.
  • K3d: 도커를 사용하여 K3s 클러스터를 로컬 환경에 빠르게 생성하는 도구입니다. VM 없이 도커 안에서 K3s를 실행하므로, 더 가볍고 빠르게 쿠버네티스를 테스트해볼 수 있습니다.
  • GitLab: A Git repository management tool you can install and run on your own server. You can set up a local GitLab server instead of using GitHub and practice connecting it with Argo CD.
  • GitLab: 로컬 환경에 직접 설치하여 사용하는 Git 저장소 관리 도구입니다. GitHub 대신 로컬 GitLab 서버를 구축하여 Argo CD와 연동하는 실습도 가능합니다.

Ready to start your Kubernetes adventure? Follow these steps to explore the world of container orchestration!
이제 쿠버네티스 탐험을 시작할 준비가 되셨나요? 각 단계를 차근차근 따라가며 컨테이너 오케스트레이션의 세계를 경험해보세요!



실전 프로젝트: Inception-of-Things / Hands-on Project: Inception-of-Things

이전 파트에서 쿠버네티스의 기본 개념을 익혔습니다. 이제 "Inception-of-Things" 프로젝트를 통해 실제 환경을 구축하고 애플리케이션을 배포하는 실습을 진행합니다. 이 프로젝트는 K3s, K3d, Vagrant, Argo CD 등의 도구를 사용합니다. 제공된 프로젝트 설명서(PDF), 관련 회의록(txt), 그리고 각 파트의 코드 예시를 바탕으로 최대한 자세하게 설명합니다.

Having learned the basic concepts of Kubernetes in the previous part, we now proceed with the "Inception-of-Things" project for hands-on practice in building environments and deploying applications. This project utilizes tools such as K3s, K3d, Vagrant, and Argo CD. This guide provides detailed explanations based on the provided project description (PDF), related meeting transcripts (txt), and code examples for each part.

목차 (Table of Contents)

  1. Part 1: K3s와 Vagrant 시작하기 (Setting Up K3s with Vagrant)
  2. Part 2: K3s와 간단한 애플리케이션 3개 배포하기 (Deploying Applications with K3s & Ingress)
  3. Part 3: K3d와 Argo CD 연동하기 (Integrating K3d and Argo CD)
  4. 보너스 파트: GitLab 연동하기 (Bonus: Integrating GitLab)

Part 1: K3s와 Vagrant 시작하기 / Part 1: Setting Up K3s with Vagrant

목표 (Goal)

  • Vagrant를 사용해 가상머신(VM) 2개를 설정하고, K3s (쿠버네티스의 가벼운 버전)를 설치하여 서버-에이전트(워커) 구조의 기본 클러스터를 구성합니다.
  • This part aims to set up two virtual machines (VMs) using Vagrant and install K3s (a lightweight Kubernetes version) to create a basic server-agent (worker) cluster structure.

주요 요구사항 (Key Requirements)

  • VM 설정 (VM Setup):
    • Vagrantfile을 작성하여 VM 2개를 만듭니다. 최신 안정 버전의 OS (Alpine Linux 3.12 - 코드 기준)를 사용하고, 리소스는 최소한(CPU 1개, RAM 1024MB)으로 설정합니다.
    • Create 2 VMs using a Vagrantfile. Use the latest stable OS (Alpine Linux 3.12 - based on the code) and minimal resources (1 CPU, 1024MB RAM).
  • VM 1 (서버 - Server):
    • 호스트 이름(Hostname): <로그인_이름>S (예: agloriosS)
    • IP 주소: 192.168.56.110 (private network)
    • K3s 역할: 컨트롤러(서버) 모드로 설치
    • Hostname: <your_login>S (e.g., agloriosS)
    • IP Address: 192.168.56.110 (private network)
    • K3s Role: Install in controller (server) mode
  • VM 2 (워커 - Server Worker):
    • 호스트 이름(Hostname): <로그인_이름>SW (예: agloriosSW)
    • IP 주소: 192.168.56.111 (private network)
    • K3s 역할: 에이전트 모드로 설치
    • Hostname: <your_login>SW (e.g., agloriosSW)
    • IP Address: 192.168.56.111 (private network)
    • K3s Role: Install in agent mode
  • 파일 공유 (File Sharing):
    • 호스트 머신의 ./confs 폴더를 각 VM의 /vagrant 경로와 동기화합니다. (토큰 공유 목적)
    • Sync the host machine's ./confs folder with /vagrant inside each VM (for sharing the token).
  • SSH 접속 (SSH Access):
    • 암호 없이 두 VM에 SSH로 접속 가능해야 합니다 (vagrant ssh <VM이름>).
    • Passwordless SSH access must be possible for both VMs (vagrant ssh <VM_name>).
  • K3s 설치 및 연결 (K3s Installation & Connection):
    • 각 VM에 맞는 모드로 K3s를 설치합니다. 서버는 설치 후 생성된 node-token을 공유 폴더(/vagrant/)에 복사합니다. 워커는 이 공유된 토큰을 읽어 서버(https://192.168.56.110:6443)에 연결합니다. K3S_KUBECONFIG_MODE="644" 옵션으로 Kubeconfig 파일 권한을 설정하고, INSTALL_K3S_EXEC="--flannel-iface eth1" 옵션으로 K3s가 사용할 네트워크 인터페이스(Flannel CNI 기준)를 eth1으로 지정합니다.
    • Install K3s in the correct mode on each VM. The server copies the generated node-token to the synced folder (/vagrant/) after installation. The worker reads this shared token to connect to the server (https://192.168.56.110:6443). The K3S_KUBECONFIG_MODE="644" option sets Kubeconfig file permissions, and INSTALL_K3S_EXEC="--flannel-iface eth1" specifies the network interface (eth1) for K3s to use (based on Flannel CNI).
  • 확인 (Verification):
    • kubectl get nodes -o wide 명령어로 두 노드가 'Ready' 상태인지 확인합니다.
    • ip a show eth1 명령어로 각 VM의 IP 주소(192.168.56.110, 192.168.56.111)를 확인합니다.
    • Use kubectl get nodes -o wide to check if both nodes are in the 'Ready' state.
    • Use ip a show eth1 to verify the IP addresses (192.168.56.110, 192.168.56.111) of each VM.

Part 1 코드 예시: Vagrantfile / Part 1 Code Example: Vagrantfile

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

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

  # Server VM Configuration
  config.vm.define "agloriosS" do |master|
    master.vm.box = "generic/alpine312" # Using Alpine Linux 3.12 box
    master.vm.network "private_network", ip: "192.168.56.110" # Assigning static private IP
    master.vm.hostname = "agloriosS" # Setting hostname
    # Syncing ./confs folder on host to /vagrant in VM using VirtualBox shared folders
    master.vm.synced_folder "./confs", "/vagrant", type:"virtualbox"
    master.vm.provider "virtualbox" do |vb| # VirtualBox specific settings
      vb.memory = "1024" # Setting RAM to 1024MB
      vb.cpus = "1"      # Setting 1 CPU core
      vb.name = "agloriosS" # Setting VM name in VirtualBox UI
    end

    # Provisioning script for the Server (Master) node, executed on `vagrant up`
    master.vm.provision "shell", inline: <<-SHELL
      # Download and execute K3s installation script using curl
      # K3S_KUBECONFIG_MODE="644": Make generated kubeconfig readable by non-root users
      # INSTALL_K3S_EXEC="--flannel-iface eth1": Tell K3s/Flannel CNI to use the eth1 interface
      # (eth1 is typically the interface associated with the private_network in Vagrant)
      curl -sfL [https://get.k3s.io](https://get.k3s.io) | K3S_KUBECONFIG_MODE="644" INSTALL_K3S_EXEC="--flannel-iface eth1" sh -

      # Wait briefly for K3s server to fully initialize and generate necessary files
      sleep 10 

      # Ensure kubeconfig permissions are set (might be redundant due to K3S_KUBECONFIG_MODE, but safe)
      sudo chmod 644 /etc/rancher/k3s/k3s.yaml

      # Define the path where K3s server stores the node token for agents to join
      NODE_TOKEN="/var/lib/rancher/k3s/server/node-token"

      # Loop and wait until the node token file is created by the K3s server
      # This ensures the token exists before attempting to copy it
      while [ ! -e ${NODE_TOKEN} ] 
      do
          echo "Waiting for node-token file..."
          sleep 2
      done
      echo "Node token file found."

      # Print the node token to the console (useful for debugging/info)
      echo "Node Token:"
      sudo cat ${NODE_TOKEN}

      # Copy the node token to the synced folder (/vagrant/) so the worker node can access it
      # The synced folder acts as a bridge between the two isolated VMs
      sudo cp ${NODE_TOKEN} /vagrant/
      echo "Node token copied to /vagrant/"

      # Define the path for the main K3s kubeconfig file
      KUBE_CONFIG="/etc/rancher/k3s/k3s.yaml"

      # Optionally copy the kubeconfig to the synced folder 
      # This allows accessing the cluster from the host machine if needed, using `kubectl --kubeconfig=./confs/k3s.yaml ...`
      sudo cp ${KUBE_CONFIG} /vagrant/
      echo "Kubeconfig copied to /vagrant/"
    SHELL
  end # End of Server VM definition

  # Worker VM Configuration
  config.vm.define "agloriosSW" do |node1|
    node1.vm.box = "generic/alpine312" # Using the same Alpine box
    node1.vm.hostname = "agloriosSW" # Setting hostname
    # Syncing ./confs folder - crucial for accessing the node-token copied by the server
    node1.vm.synced_folder "./confs", "/vagrant", type:"virtualbox" 
    node1.vm.network "private_network", ip: "192.168.56.111" # Assigning static private IP
    node1.vm.provider "virtualbox" do |vb| # VirtualBox specific settings
      vb.memory = "1024" # Setting RAM
      vb.cpus = "1"      # Setting CPU
      vb.name = "agloriosSW" # Setting VM name
    end

    # Provisioning script for the Worker (Agent) node
    node1.vm.provision "shell", inline: <<-SHELL
      # Wait until the node-token file (copied by the server) appears in the synced folder
      # This prevents the agent from trying to install before the token is available
      while [ ! -f /vagrant/node-token ]; do
        echo "Waiting for node-token in /vagrant..."
        sleep 5
      done
      echo "Node token found in /vagrant/, proceeding with K3s agent installation..."

      # Download and execute K3s installation script in agent mode
      # K3S_URL: Specifies the server URL (IP and default port 6443) the agent should connect to
      # K3S_TOKEN: Reads the token from the synced file `/vagrant/node-token`
      # INSTALL_K3S_EXEC="--flannel-iface eth1": Ensure the agent also uses the correct interface for networking
      curl -sfL [https://get.k3s.io](https://get.k3s.io) | K3S_URL=[https://192.168.56.110:6443](https://192.168.56.110:6443) K3S_TOKEN=$(sudo cat /vagrant/node-token) INSTALL_K3S_EXEC="--flannel-iface eth1" sh -

      # Wait briefly for the K3s agent to start and attempt registration with the server
      sleep 10 
      echo "K3s agent installation attempted."
    SHELL
  end # End of Worker VM definition

end # End of Vagrant configuration

코드 해설 (Code Explanation)

  • Vagrant.configure("2") do |config| ... end: Vagrant 설정 블록.
  • config.vm.define "VM_NAME" do |vm_config| ... end: 특정 VM("agloriosS", "agloriosSW") 정의.
  • vm_config.vm.box = "generic/alpine312": 사용할 Vagrant Box 이미지 (Alpine Linux 3.12).
  • vm_config.vm.network "private_network", ip: "IP_ADDRESS": VM 고정 사설 IP 할당.
  • vm_config.vm.hostname = "HOSTNAME": VM 내부 호스트 이름 설정.
  • vm_config.vm.synced_folder "./confs", "/vagrant", type:"virtualbox": 호스트의 ./confs 폴더를 VM의 /vagrant와 동기화 (토큰 공유).
  • vm_config.vm.provider "virtualbox" do |vb| ... end: VirtualBox 특화 설정 (메모리, CPU, UI 이름).
  • vm_config.vm.provision "shell", inline: <<-SHELL ... SHELL: VM 첫 부팅 시 실행될 셸 스크립트 (K3s 설치/설정).
  • Server Provisioning:
    • curl ... | sh -: K3s 설치 스크립트 다운로드 및 실행.
    • K3S_KUBECONFIG_MODE="644": Kubeconfig 파일 권한 설정 (sudo 없이 kubectl 사용).
    • INSTALL_K3S_EXEC="--flannel-iface eth1": K3s/Flannel CNI가 사용할 네트워크 인터페이스를 eth1로 지정.
    • sleep 10: K3s 서버 초기화 대기.
    • NODE_TOKEN="...": 워커 노드 인증 토큰 파일 경로.
    • while [ ! -e ${NODE_TOKEN} ] ... done: 토큰 파일 생성 대기 루프.
    • sudo cp ${NODE_TOKEN} /vagrant/: 생성된 토큰을 공유 폴더(/vagrant/)로 복사.
    • sudo cp ${KUBE_CONFIG} /vagrant/: Kubeconfig 파일을 공유 폴더로 복사 (선택적).
  • Worker Provisioning:
    • while [ ! -f /vagrant/node-token ] ... done: 공유 폴더에 토큰 파일 생성 대기 루프.
    • curl ... | sh -: K3s 에이전트 모드로 설치 스크립트 실행.
    • K3S_URL=https://192.168.56.110:6443: 연결할 K3s 서버 주소 지정.
    • K3S_TOKEN=$(sudo cat /vagrant/node-token): 공유된 토큰 파일 내용 읽어 환경 변수로 사용.
    • INSTALL_K3S_EXEC="--flannel-iface eth1": 워커 노드도 eth1 사용 설정.
  • English Explanation:
    • Vagrant.configure("2") do |config| ... end: Vagrant configuration block.
    • config.vm.define "VM_NAME" do |vm_config| ... end: Block defining a specific VM ("agloriosS", "agloriosSW").
    • vm_config.vm.box = "generic/alpine312": Specifies the Vagrant Box image (Alpine Linux 3.12).
    • vm_config.vm.network "private_network", ip: "IP_ADDRESS": Assigns a static private IP address.
    • vm_config.vm.hostname = "HOSTNAME": Sets the hostname inside the VM.
    • vm_config.vm.synced_folder "./confs", "/vagrant", type:"virtualbox": Syncs host's ./confs folder to VM's /vagrant (for token sharing).
    • vm_config.vm.provider "virtualbox" do |vb| ... end: VirtualBox specific settings (memory, CPU, UI name).
    • vm_config.vm.provision "shell", inline: <<-SHELL ... SHELL: Inline shell script for provisioning (K3s setup).
    • Server Provisioning:
      • curl ... | sh -: Downloads and executes K3s install script.
      • K3S_KUBECONFIG_MODE="644": Sets Kubeconfig file permissions (for non-root kubectl use).
      • INSTALL_K3S_EXEC="--flannel-iface eth1": Specifies eth1 interface for K3s/Flannel CNI.
      • sleep 10: Waits for K3s server initialization.
      • NODE_TOKEN="...": Path to the node token file.
      • while [ ! -e ${NODE_TOKEN} ] ... done: Loop waiting for the token file creation.
      • sudo cp ${NODE_TOKEN} /vagrant/: Copies the generated token to the shared folder (/vagrant/).
      • sudo cp ${KUBE_CONFIG} /vagrant/: Copies the Kubeconfig file to the shared folder (optional).
    • Worker Provisioning:
      • while [ ! -f /vagrant/node-token ] ... done: Loop waiting for the token file in the shared folder.
      • curl ... | sh -: Executes install script in K3s agent mode.
      • K3S_URL=https://192.168.56.110:6443: Specifies the K3s server address to connect to.
      • K3S_TOKEN=$(sudo cat /vagrant/node-token): Reads token from shared file and uses as environment variable.
      • INSTALL_K3S_EXEC="--flannel-iface eth1": Sets worker node to also use eth1.

주요 도구 및 개념 (Key Tools & Concepts)

  • Vagrant: VM 환경 코드 관리. (Vagrantfile, vagrant up, vagrant ssh)
  • Vagrant: Manages VM environments via code. (Vagrantfile, vagrant up, vagrant ssh)
  • K3s: 가벼운 쿠버네티스. (서버/에이전트 모드)
  • K3s: Lightweight Kubernetes. (Server/Agent modes)
  • kubectl: 쿠버네티스 CLI. (k alias)
  • kubectl: Kubernetes CLI. (k alias)
  • Kubeconfig: 클러스터 접속 정보 파일 (/etc/rancher/k3s/k3s.yaml).
  • Kubeconfig: Cluster access config file (/etc/rancher/k3s/k3s.yaml).
  • Node Token: 워커 노드 인증 토큰.
  • Node Token: Worker node authentication token.
  • Flannel: K3s 기본 CNI 플러그인. (--flannel-iface 옵션)
  • Flannel: K3s default CNI plugin. (--flannel-iface option)
  • Synced Folder: Vagrant 폴더 동기화 기능.
  • Synced Folder: Vagrant folder synchronization feature.
  • Provisioning: Vagrant 자동 스크립트 실행 기능.
  • Provisioning: Vagrant automatic script execution feature.

팁 및 주의사항 (Tips & Notes)

  • vagrant up 실행 시 VM 생성 및 K3s 설치에 시간이 소요됩니다.
  • Running vagrant up takes time for VM creation and K3s installation.
  • 서버-워커 연결 실패 시, 워커 로그에서 K3S_URL 또는 K3S_TOKEN 오류 확인, 공유 폴더 내 토큰 파일 존재 및 권한 확인이 필요합니다.
  • If server-worker connection fails, check worker logs for K3S_URL or K3S_TOKEN errors, and verify the token file's existence and permissions in the shared folder.
  • --flannel-iface eth1 설정이 중요하며, VM 내부에서 ip addr로 인터페이스 이름 확인이 필요할 수 있습니다.
  • The --flannel-iface eth1 setting is crucial; verify the interface name inside the VM with ip addr if needed.
  • VM 리소스 부족 시 K3s 작동이 불안정할 수 있습니다.
  • Insufficient VM resources can cause K3s instability.
  • 공유 폴더(/vagrant) 동기화에 시간이 걸릴 수 있으므로 워커 노드에서 토큰 파일을 사용하기 전에 대기하는 로직(while 루프)이 포함되었습니다.
  • Syncing the shared folder (/vagrant) might take time, hence the logic (while loop) in the worker node to wait for the token file before using it.

Part 2: K3s와 간단한 애플리케이션 3개 배포하기 / Part 2: Deploying Applications with K3s & Ingress

목표 (Goal)

  • 하나의 K3s 서버 VM 환경에서 3개의 웹 애플리케이션을 배포하고, Ingress를 설정하여 Host 헤더 기반으로 각 앱에 접근할 수 있도록 합니다. ReplicaSet 개념을 이해하고 적용합니다.
  • Deploy three web applications on a single K3s server VM environment, configure Ingress for access based on Host headers, and understand/apply the ReplicaSet concept.

주요 요구사항 (Key Requirements)

  • VM 설정 (VM Setup):
    • VM 1개만 사용. 호스트 이름 <로그인_이름>S (예: agloriosS), IP 192.168.56.110. K3s 서버 모드. 메모리 2048MB.
    • Use only one VM. Hostname <your_login>S (e.g., agloriosS), IP 192.168.56.110. K3s server mode. Memory 2048MB.
  • 애플리케이션 배포 (Application Deployment):
    • 웹 앱 3개 배포 (Deployment 리소스).
    • Deploy 3 web apps (Deployment resources).
  • Ingress 설정 (Ingress Setup):
    • Ingress 리소스로 192.168.56.110 요청을 Host 헤더 기반 라우팅:
      • Host: app1.com -> App 1 Service
      • Host: app2.com -> App 2 Service
      • Default -> App 3 Service
    • Route requests to 192.168.56.110 via Ingress based on Host header:
      • Host: app1.com -> App 1 Service
      • Host: app2.com -> App 2 Service
      • Default -> App 3 Service
  • 복제본 설정 (Replica Setup):
    • App 2는 3개 복제본 설정 (Deploymentreplicas: 3).
    • App 2 configured with 3 replicas (replicas: 3 in Deployment).
  • 확인 (Verification):
    • kubectl get all로 리소스 상태 확인.
    • curl -H "Host: <호스트명>" 192.168.56.110로 라우팅 확인.
    • Check resource status with kubectl get all.
    • Verify routing with curl -H "Host: <hostname>" 192.168.56.110.

Part 2 코드 예시: Vagrantfile / Part 2 Code Example: Vagrantfile

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

Vagrant.configure("2") do |config|
  # Use Alpine Linux 3.12 as the base box
  config.vm.box = "generic/alpine312"

  # Define a single VM for this part
  config.vm.define "agloriosS" do |master|
    # Configure private network with the required IP address
    master.vm.network "private_network", ip: "192.168.56.110"

    # Sync the ./confs directory on the host to /vagrant inside the VM
    # This directory should contain Kubernetes YAML files for deployments, services, ingress etc.
    master.vm.synced_folder "./confs", "/vagrant", type: "virtualbox"

    # Set the hostname for the VM
    master.vm.hostname = "agloriosS"

    # Configure VirtualBox provider specifics
    master.vm.provider "virtualbox" do |vb|
      # Allocate more memory (2GB) as this VM will run K3s server + applications
      vb.memory = "2048" 
      vb.cpus = "1"
      # Set the name visible in the VirtualBox UI
      vb.name = "agloriosS"
    end

    # Execute an external provisioning script located at ./scripts/setup.sh
    # This script is responsible for:
    # 1. Installing K3s in server mode (similar to Part 1 server).
    # 2. Applying the Kubernetes YAML configurations from the /vagrant (synced ./confs) folder
    #    (e.g., `kubectl apply -f /vagrant/deployment-app1.yaml`, `kubectl apply -f /vagrant/service-app1.yaml`, 
    #     `kubectl apply -f /vagrant/ingress.yaml`, etc.)
    master.vm.provision "shell", path: "./scripts/setup.sh"
  end
end

코드 해설 (Code Explanation)

  • VM 정의: VM 하나("agloriosS")만 정의.
  • 리소스: 메모리 2048MB로 증가 (K3s 서버 + 앱 3개 실행).
  • 프로비저닝: 외부 스크립트 setup.sh 사용.
    • setup.sh 내용: K3s 서버 설치 + /vagrant 폴더 내 YAML 파일들(deployment*.yaml, service*.yaml, ingress.yaml 등)을 kubectl apply -f로 적용하여 앱 및 Ingress 배포.
  • English Explanation:
    • VM Definition: Defines only one VM ("agloriosS").
    • Resources: Memory increased to 2048MB (to run K3s server + 3 apps).
    • Provisioning: Uses external script setup.sh.
      • setup.sh content: Installs K3s server + applies YAML files from /vagrant (like deployment*.yaml, service*.yaml, ingress.yaml) using kubectl apply -f to deploy apps and Ingress.

주요 도구 및 개념 (Key Tools & Concepts)

  • Deployment: 앱 상태 선언/관리.
  • Deployment: Declares/manages app state.
  • ReplicaSet: Pod 복제본 수 보장.
  • ReplicaSet: Ensures desired Pod replica count.
  • Service: Pod 그룹 내부 접근점 (ClusterIP).
  • Service: Internal access point for Pod group (ClusterIP).
  • Ingress: 외부 요청 라우팅 규칙 (Host 헤더 기반).
  • Ingress: External request routing rules (Host header-based).
  • Ingress Controller: Ingress 규칙 처리 (Traefik in K3s).
  • Ingress Controller: Processes Ingress rules (Traefik in K3s).
  • Host 헤더: curl -H "Host: ..." 사용.
  • Host Header: Use curl -H "Host: ...".
  • YAML: 쿠버네티스 리소스 정의 (./confs 폴더).
  • YAML: Defines Kubernetes resources (in ./confs folder).

팁 및 주의사항 (Tips & Notes)

  • Ingress YAML 파일에서 rules 설정이 핵심입니다.
  • The rules section in the Ingress YAML file is key.
  • 각 Deployment에 맞는 Service (ClusterIP)가 필요합니다.
  • Each Deployment needs a corresponding Service (ClusterIP).
  • setup.sh 스크립트 내 K3s 설치와 kubectl apply 사이에 sleep 이나 상태 확인 로직을 추가하면 안정성이 향상됩니다.
  • Adding sleep or status checks in setup.sh between K3s install and kubectl apply can improve stability.

Part 3: K3d와 Argo CD 연동하기 / Part 3: Integrating K3d and Argo CD

목표 (Goal)

  • Vagrant 대신 K3d를 사용하여 쿠버네티스 환경 구축. Argo CD를 설치하여 GitOps 워크플로우 구현 (Git 변경 시 자동 배포).
  • Set up Kubernetes using K3d instead of Vagrant. Install Argo CD to implement a GitOps workflow (automatic deployment on Git changes).

주요 요구사항 (Key Requirements)

  • K3d 설치/사용 (K3d Install/Usage):
    • 호스트에 DockerK3d 설치. K3d로 클러스터 생성 (k3d cluster create ...).
    • Install Docker & K3d on host. Create cluster with K3d (k3d cluster create ...).
    • 설치 스크립트 필요 (setup.sh).
    • Install script needed (setup.sh).
  • 네임스페이스 (Namespaces):
    • argocddev 네임스페이스 생성.
    • Create argocd and dev namespaces.
  • Argo CD 설치/설정 (Argo CD Setup):
    • argocd 네임스페이스에 Argo CD 설치.
    • Install Argo CD in argocd namespace.
    • Argo CD가 공개 GitHub 저장소를 바라보도록 설정.
    • Configure Argo CD to monitor a public GitHub repository.
  • 앱 배포 (App Deployment):
    • GitHub에 배포 설정 파일(YAML) 위치. 앱은 dev 네임스페이스에 배포.
    • Place deployment config (YAML) in GitHub. App deployed to dev namespace.
    • 앱은 v1, v2 태그 버전 필요 (차이점 존재). 제공된 이미지(wil42/playground:TAG) 또는 자체 이미지 사용.
    • App needs v1, v2 tagged versions (with differences). Use provided image (wil42/playground:TAG) or own image.
  • GitOps 확인 (GitOps Verification):
    • GitHub에서 이미지 태그 변경 (v1->v2) 후 git push.
    • Argo CD가 자동 동기화 후 앱 업데이트하는지 확인 (UI 상태, curl 결과).
    • Change image tag (v1->v2) in GitHub, git push.
    • Verify Argo CD auto-syncs and updates the app (check UI status, curl result).

Part 3 코드 예시: Makefile / Part 3 Code Example: Makefile

# Target to set up everything: K3d cluster, Argo CD, and the application link
all:
    ./scripts/setup.sh # This script likely creates the k3d cluster, installs Argo CD, and applies the Argo Application CRD

# Target to clean everything and then set up again
re: clean
    ./scripts/setup.sh

# Target to clean up resources
clean:
    # Try to delete the Argo CD Application CRD. The '-' ignores errors if it doesn't exist.
    -./scripts/clean.sh 
    # Force clean: Delete Argo CD itself and the K3d cluster.
    ./scripts/fclean.sh 

# Target to launch only the Argo CD Application CRD
# Assumes K3d cluster and Argo CD controller are already running
launch:
    ./scripts/launch.sh # This script likely just runs `kubectl apply -f <argo_app_crd.yaml>`

# Target to reload just the Argo CD Application definition
re_launch: clean_launch # First clean the application definition
    ./scripts/launch.sh # Then re-apply it

# Target to clean only the Argo CD Application definition
clean_launch:
    # Try to delete the Argo CD Application CRD. Ignore errors.
    -./scripts/clean.sh 

# Target to verify if the deployed application is working correctly
verify:
    ./scripts/verify.sh # This script likely runs curl commands against the app endpoint (via port-forwarding)

# Declare targets as phony to prevent conflicts with files of the same name
.PHONY: all re clean launch re_launch clean_launch verify

코드 해설 (Code Explanation)

  • Makefile: 빌드/정리/실행 자동화 도구.
  • all: 기본 타겟 (make). ./scripts/setup.sh 실행 (전체 설정).
  • re: cleansetup.sh 실행 (전체 재설정).
  • clean: ./scripts/clean.sh (Argo CD 앱 정의 삭제) 후 ./scripts/fclean.sh (Argo CD 및 K3d 클러스터 삭제) 실행.
  • launch: ./scripts/launch.sh 실행 (Argo CD 앱 정의만 배포).
  • re_launch: clean_launchlaunch.sh 실행 (Argo CD 앱 정의 재배포).
  • clean_launch: ./scripts/clean.sh 실행 (Argo CD 앱 정의만 삭제).
  • verify: ./scripts/verify.sh 실행 (배포된 앱 동작 확인, 예: curl).
  • .PHONY: 타겟들이 파일이 아님을 명시.
  • English Explanation:
    • Makefile: Tool for automating build/clean/run tasks.
    • all: Default target (make). Runs ./scripts/setup.sh (full setup).
    • re: Runs clean then setup.sh (full reset).
    • clean: Runs ./scripts/clean.sh (delete Argo CD app definition) then ./scripts/fclean.sh (delete Argo CD & K3d cluster).
    • launch: Runs ./scripts/launch.sh (deploy only Argo CD app definition).
    • re_launch: Runs clean_launch then launch.sh (redeploy Argo CD app definition).
    • clean_launch: Runs ./scripts/clean.sh (delete only Argo CD app definition).
    • verify: Runs ./scripts/verify.sh (check deployed app, e.g., curl).
    • .PHONY: Declares targets are not files.

주요 도구 및 개념 (Key Tools & Concepts)

  • K3d: Docker 기반 K3s 클러스터. (k3d cluster create/delete)
  • K3d: K3s cluster on Docker. (k3d cluster create/delete)
  • Docker: K3d 실행 환경.
  • Docker: Runtime for K3d.
  • Argo CD: GitOps 도구 (자동 동기화). (UI & CLI)
  • Argo CD: GitOps tool (auto-sync). (UI & CLI)
  • GitOps: Git 중심 배포 관리.
  • GitOps: Git-centric deployment management.
  • Namespace: 리소스 격리 (argocd, dev).
  • Namespace: Resource isolation (argocd, dev).
  • Image Tagging: Docker 이미지 버전 (v1, v2).
  • Image Tagging: Docker image version (v1, v2).
  • Makefile: 작업 자동화.
  • Makefile: Task automation.
  • Shell Scripts: 실제 로직 구현 (setup.sh 등).
  • Shell Scripts: Implement actual logic (setup.sh, etc.).

팁 및 주의사항 (Tips & Notes)

  • setup.sh는 K3d 클러스터 생성, Argo CD 설치, launch.sh 호출 등을 포함할 수 있습니다.
  • setup.sh might include K3d cluster creation, Argo CD installation, calling launch.sh, etc.
  • Argo CD UI/앱 접근을 위해 kubectl port-forward 필요.
  • kubectl port-forward needed for Argo CD UI / app access.
  • Git push 후 Argo CD 동기화까지 시간 소요될 수 있음 (기본 3분).
  • Delay possible between git push and Argo CD sync (default 3 min).
  • Argo CD 초기 관리자 비밀번호는 Secret에서 조회 필요.
  • Argo CD initial admin password needs retrieval from a Secret.

보너스 파트: GitLab 연동하기 / Bonus: Integrating GitLab

목표 (Goal)

  • Part 3 설정에서 GitHub 대신, 로컬 클러스터 내부에 설치한 GitLab을 사용하여 Argo CD와 연동합니다.
  • Modify Part 3 setup to use a locally installed GitLab instance (running inside the cluster) instead of GitHub, integrating it with Argo CD.

주요 요구사항 (Key Requirements)

  • GitLab 설치 (GitLab Installation):
    • 최신 GitLab 로컬 클러스터 내 설치 (Helm 권장).
    • Install latest GitLab locally in the cluster (Helm recommended).
  • 네임스페이스 (Namespace):
    • gitlab 네임스페이스 생성.
    • Create gitlab namespace.
  • Argo CD 연동 (Argo CD Integration):
    • Argo CD가 로컬 GitLab 저장소를 바라보도록 설정 변경 (내부 서비스 주소, 토큰 인증 필요).
    • Reconfigure Argo CD to monitor local GitLab repo (needs internal service address, token auth).
  • 기능 확인 (Functionality Check):
    • 로컬 GitLab에 push 시 Argo CD 자동 동기화 및 앱 업데이트 확인.
    • Verify auto-sync and app update on git push to local GitLab.

주요 도구 및 개념 (Key Tools & Concepts)

  • GitLab: 자체 설치형 Git 플랫폼.
  • GitLab: Self-hostable Git platform.
  • Helm: GitLab 설치/관리 도구 (values.yaml).
  • Helm: GitLab install/manage tool (values.yaml).
  • Local Integration: 클러스터 내부 서비스 간 연동 (내부 DNS/Service 주소, 인증).
  • Local Integration: Connecting internal cluster services (Internal DNS/Service address, auth).
  • GitLab Access Token: Argo CD 인증 수단.
  • GitLab Access Token: Authentication for Argo CD.
  • Argo CD Repository Credentials: 비공개 저장소 인증 정보 등록.
  • Argo CD Repository Credentials: Stores private repo credentials in Argo CD.

팁 및 주의사항 (Tips & Notes)

  • GitLab Helm 차트는 복잡하고 리소스 요구량이 많으므로 values.yaml에서 최소 기능만 활성화하세요 (회의록 참고).
  • GitLab Helm chart is complex and resource-heavy; enable minimal features in values.yaml (refer to transcript).
  • Argo CD에서 로컬 GitLab 등록 시 내부 서비스 주소(예: http://gitlab-webservice-default.gitlab.svc.cluster.local) 및 토큰 인증 설정이 필요합니다. HTTP 사용 시 --insecure 옵션이 필요할 수 있습니다.
  • Registering local GitLab in Argo CD requires internal service address (e.g., http://gitlab-webservice-default.gitlab.svc.cluster.local) and token auth. May need --insecure option if using HTTP.
  • 보너스 파트는 필수 파트가 완벽해야 평가됩니다.
  • Bonus part assessed only if mandatory part is flawless.