프로그래밍/코딩 공부

Kubeflow 구축하기

Tech코알라 2026. 2. 9. 15:59

Kubeflow 구축 완벽 가이드: 각 컴포넌트 상세 설치

Kubeflow는 Kubernetes 위에서 머신러닝 워크플로우를 구축, 배포, 관리하기 위한 오픈소스 플랫폼입니다. 이 가이드에서는 Kubeflow v1.10/v1.11 (최신 버전)을 기준으로 각 컴포넌트를 단계별로 상세하게 설치하는 방법을 알아보겠습니다.

목차

  1. Kubeflow 소개
  2. 사전 요구사항
  3. 설치 방법 선택
  4. 기본 인프라 컴포넌트 설치
  5. Kubeflow 핵심 컴포넌트 설치
  6. 클러스터 접속 및 검증
  7. 첫 워크플로우 실행

1. Kubeflow 소개

1.1 Kubeflow란?

Kubeflow는 ML 워크플로우를 간단하고, 이식 가능하며, 확장 가능하게 만들기 위한 머신러닝 툴킷입니다. 구글에서 시작되어 현재는 CNCF(Cloud Native Computing Foundation)에서 관리하고 있습니다.

1.2 주요 컴포넌트

Kubeflow는 다음과 같은 주요 컴포넌트들로 구성됩니다:

ML 워크플로우 및 파이프라인

  • Kubeflow Pipelines: ML 워크플로우 오케스트레이션
  • Katib: 하이퍼파라미터 튜닝 및 AutoML

모델 학습

  • Training Operators: TensorFlow, PyTorch, MXNet 등 분산 학습
  • Trainer (v2): 차세대 학습 오퍼레이터

모델 서빙

  • KServe: 모델 서빙 및 추론
  • Model Registry: 모델 버전 관리

개발 환경

  • Jupyter Notebooks: 인터랙티브 개발 환경
  • Volumes/Tensorboard: 데이터 관리 및 시각화

플랫폼 관리

  • Central Dashboard: 통합 UI
  • Profiles: 멀티테넌시 관리

1.3 최신 버전 정보

  • Kubeflow Platform: v1.10 (2025년 3월 릴리즈), v1.11 (2025년 12월 예정)
  • Kubeflow Pipelines: 2.15.2 (2025년 12월)
  • 지원 Kubernetes 버전: 1.31-1.33+
  • 주요 개선사항:
    • Istio CNI 도입으로 보안 강화
    • Pod Security Standards 적용
    • SeaweedFS 기본 아티팩트 스토어 전환
    • Kubernetes Native API 모드 파이프라인 지원

2. 사전 요구사항

2.1 하드웨어 요구사항

최소 사양

  • CPU: 4 코어
  • 메모리: 16 GB RAM
  • 디스크: 100 GB 이상

권장 사양 (프로덕션)

  • CPU: 8 코어 이상
  • 메모리: 32 GB RAM 이상
  • 디스크: 200 GB 이상 (SSD 권장)

2.2 소프트웨어 요구사항

# Kubernetes 클러스터 (1.31-1.33+)
kubectl version --client

# Kustomize 5.7.1+
kustomize version

# Docker 또는 Podman (Kind 사용 시)
docker version

2.3 리눅스 커널 설정 (Kind 사용 시)

# inotify 제한 증가 (많은 Pod 실행을 위해)
sudo sysctl fs.inotify.max_user_instances=2280
sudo sysctl fs.inotify.max_user_watches=1255360

# 영구 적용
echo "fs.inotify.max_user_instances=2280" | sudo tee -a /etc/sysctl.conf
echo "fs.inotify.max_user_watches=1255360" | sudo tee -a /etc/sysctl.conf

3. 설치 방법 선택

3.1 원클릭 설치 vs 컴포넌트별 설치

Kubeflow는 두 가지 설치 방법을 제공합니다:

방법 1: 원클릭 설치

  • 장점: 간단하고 빠름
  • 단점: 커스터마이징 제한
  • 용도: 개발 및 테스트 환경

방법 2: 컴포넌트별 설치 (이 가이드에서 다룸)

  • 장점: 필요한 컴포넌트만 선택 가능, 세밀한 제어
  • 단점: 복잡하고 시간 소요
  • 용도: 프로덕션 환경, 커스터마이징 필요 시

3.2 저장소 클론

# Kubeflow manifests 저장소 클론
git clone https://github.com/kubeflow/manifests.git
cd manifests

# 안정 버전 사용 (권장)
git checkout v1.10.0

# 또는 최신 개발 버전 사용
git checkout master

3.3 Kind 클러스터 생성 (로컬 개발용)

# Kind 클러스터 설정 파일 생성 및 클러스터 시작
cat <<EOF | kind create cluster --name=kubeflow --config=-
kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
nodes:
- role: control-plane
  image: kindest/node:v1.34.0@sha256:7416a61b42b1662ca6ca89f02028ac133a309a2a30ba309614e8ec94d976dc5a
  kubeadmConfigPatches:
  - |
    kind: ClusterConfiguration
    apiServer:
      extraArgs:
        "service-account-issuer": "https://kubernetes.default.svc"
        "service-account-signing-key-file": "/etc/kubernetes/pki/sa.key"
EOF

# kubeconfig 저장
kind get kubeconfig --name kubeflow > /tmp/kubeflow-config
export KUBECONFIG=/tmp/kubeflow-config

# 클러스터 확인
kubectl cluster-info
kubectl get nodes

4. 기본 인프라 컴포넌트 설치

Kubeflow의 핵심 컴포넌트들은 여러 공통 서비스에 의존합니다. 이들을 먼저 설치해야 합니다.

4.1 Kubeflow Namespace 생성

# Kubeflow 네임스페이스 생성
kustomize build common/kubeflow-namespace/base | kubectl apply -f -

# 확인
kubectl get namespace kubeflow

역할: Kubeflow 컴포넌트들이 배포될 기본 네임스페이스입니다.

4.2 Cert-Manager 설치

Cert-Manager는 TLS 인증서를 자동으로 관리하고 갱신합니다.

# Cert-Manager 설치
kustomize build common/cert-manager/base | kubectl apply -f -
kustomize build common/cert-manager/kubeflow-issuer/base | kubectl apply -f -

# Pod가 준비될 때까지 대기
echo "Waiting for cert-manager to be ready..."
kubectl wait --for=condition=Ready pod -l 'app in (cert-manager,webhook)' \
  --timeout=180s -n cert-manager
kubectl wait --for=jsonpath='{.subsets[0].addresses[0].targetRef.kind}'=Pod \
  endpoints -l 'app in (cert-manager,webhook)' \
  --timeout=180s -n cert-manager

# 확인
kubectl get pods -n cert-manager

주요 역할:

  • Admission webhook용 인증서 제공
  • 자동 인증서 갱신
  • Kubeflow 컴포넌트 간 보안 통신 지원

문제 해결:
만약 "webhook: Post ... connection refused" 에러가 발생하면, webhook이 준비될 때까지 몇 초 기다린 후 재시도하세요.

4.3 Istio 설치 (Service Mesh)

Istio는 마이크로서비스 간 트래픽 관리, 보안, 관찰성을 제공합니다.

# Istio CRD 및 네임스페이스
kustomize build common/istio/istio-crds/base | kubectl apply -f -
kustomize build common/istio/istio-namespace/base | kubectl apply -f -

# Istio 설치 (OAuth2-Proxy와 통합)
# 대부분의 플랫폼용 (Kind, Minikube, AKS, EKS)
kustomize build common/istio/istio-install/overlays/oauth2-proxy | kubectl apply -f -

# GKE 사용 시
# kustomize build common/istio/istio-install/overlays/gke | kubectl apply -f -

# Pod 준비 대기
echo "Waiting for all Istio Pods to become ready..."
kubectl wait --for=condition=Ready pods --all -n istio-system --timeout=300s

# 확인
kubectl get pods -n istio-system
kubectl get svc -n istio-system

주요 역할:

  • 서비스 메시 및 사이드카 인젝션
  • 트래픽 라우팅 및 로드 밸런싱
  • mTLS를 통한 서비스 간 보안 통신
  • 네트워크 정책 및 권한 부여

Istio CNI 사용 이유:

  • Privileged init container 불필요로 보안 강화
  • Pod Security Standards 호환성 향상
  • Kubernetes 1.28+ native sidecar 지원

4.4 OAuth2-Proxy 설치

OAuth2-Proxy는 인증 및 인가를 처리합니다.

echo "Installing oauth2-proxy..."

# 옵션 1: Dex만 사용 (기본, 대부분의 클러스터에서 작동)
kustomize build common/oauth2-proxy/overlays/m2m-dex-only/ | kubectl apply -f -
kubectl wait --for=condition=Ready pod -l 'app.kubernetes.io/name=oauth2-proxy' \
  --timeout=180s -n oauth2-proxy

# 옵션 2: Kubernetes 서비스 어카운트 토큰 지원 (Kind, GKE 등)
# kustomize build common/oauth2-proxy/overlays/m2m-dex-and-kind/ | kubectl apply -f -
# kubectl wait --for=condition=Ready pod -l 'app.kubernetes.io/name=oauth2-proxy' \
#   --timeout=180s -n oauth2-proxy
# kubectl wait --for=condition=Ready pod -l 'app.kubernetes.io/name=cluster-jwks-proxy' \
#   --timeout=180s -n istio-system

# 옵션 3: EKS 전용 (AWS_REGION과 CLUSTER_ID 먼저 수정 필요)
# kustomize build common/oauth2-proxy/overlays/m2m-dex-and-eks/ | kubectl apply -f -

# 확인
kubectl get pods -n oauth2-proxy
kubectl get svc -n oauth2-proxy

주요 역할:

  • OIDC 클라이언트로 작동
  • 사용자 세션 관리
  • 토큰 기반 머신 간 인증 (M2M) 지원
  • Istio Ingress Gateway와 통합

옵션 설명:

  • 옵션 1: 가장 간단, Dex를 통한 인증만 지원
  • 옵션 2: K8s 서비스 어카운트 토큰으로 외부 접근 가능 (CI/CD용)
  • 옵션 3: AWS EKS 환경에 최적화

4.5 Dex 설치 (Identity Provider)

Dex는 OIDC(OpenID Connect) 프로바이더로 다양한 인증 백엔드를 지원합니다.

echo "Installing Dex..."
kustomize build common/dex/overlays/oauth2-proxy | kubectl apply -f -
kubectl wait --for=condition=Ready pods --all --timeout=180s -n auth

# 확인
kubectl get pods -n auth
kubectl get configmap dex -n auth -o yaml

주요 역할:

  • OpenID Connect (OIDC) 프로바이더
  • 다중 인증 백엔드 지원 (LDAP, GitHub, Google, SAML 등)
  • 기본 정적 사용자 제공 (user@example.com / 12341234)

외부 IDP 연동 (선택사항):

Dex를 Azure AD, Google, GitHub 등과 연동하려면 common/dex/overlays/oauth2-proxy/config-map.yaml를 수정합니다:

apiVersion: v1
kind: ConfigMap
metadata:
  name: dex
data:
  config.yaml: |
    issuer: https://your-kubeflow-domain.com/dex
    storage:
      type: kubernetes
      config:
        inCluster: true
    web:
      http: 0.0.0.0:5556
    oauth2:
      skipApprovalScreen: true

    # 정적 사용자 (프로덕션에서는 제거 권장)
    staticPasswords:
    - email: user@example.com
      hashFromEnv: DEX_USER_PASSWORD
      username: user
      userID: "15841185641784"

    staticClients:
    - idEnv: OIDC_CLIENT_ID
      redirectURIs: ["/oauth2/callback"]
      name: 'Dex Login Application'
      secretEnv: OIDC_CLIENT_SECRET

    # 외부 IDP 커넥터 (예: Azure AD)
    connectors:
    - type: oidc
      id: azure
      name: Azure AD
      config:
        issuer: https://login.microsoftonline.com/$TENANT_ID/v2.0
        redirectURI: https://your-kubeflow-domain.com/dex/callback
        clientID: $AZURE_CLIENT_ID
        clientSecret: $AZURE_CLIENT_SECRET
        scopes:
        - openid
        - profile
        - email

4.6 Knative 설치 (Serverless Platform)

Knative는 KServe의 모델 서빙에 필요합니다.

# Knative Serving 설치
kustomize build common/knative/knative-serving/overlays/gateways | kubectl apply -f -
kustomize build common/istio/cluster-local-gateway/base | kubectl apply -f -

# Knative Eventing 설치 (선택사항, 추론 요청 로깅용)
kustomize build common/knative/knative-eventing/base | kubectl apply -f -

# 확인
kubectl get pods -n knative-serving
kubectl get pods -n knative-eventing  # eventing 설치한 경우

주요 역할:

  • 서버리스 컨테이너 플랫폼
  • KServe의 모델 서빙 백엔드
  • 자동 스케일링 (scale-to-zero 포함)
  • 트래픽 라우팅 및 리비전 관리

4.7 Network Policies 설치

# 네트워크 정책 적용
kustomize build common/networkpolicies/base | kubectl apply -f -

주요 역할: Pod 간 네트워크 트래픽 제어 및 보안 강화

4.8 Kubeflow Roles 생성

# Kubeflow ClusterRoles 생성
kustomize build common/kubeflow-roles/base | kubectl apply -f -

# 확인
kubectl get clusterroles | grep kubeflow

생성되는 Role:

  • kubeflow-view: 읽기 전용 권한
  • kubeflow-edit: 편집 권한
  • kubeflow-admin: 관리자 권한

4.9 Kubeflow Istio Resources

# Kubeflow Gateway 및 Istio 리소스 생성
kustomize build common/istio/kubeflow-istio-resources/base | kubectl apply -f -

# 확인
kubectl get gateway -n kubeflow
kubectl get virtualservice -n kubeflow

주요 리소스:

  • kubeflow-gateway: Istio Ingress Gateway 설정
  • kubeflow-istio-admin: Istio 관리 ClusterRole

5. Kubeflow 핵심 컴포넌트 설치

이제 기본 인프라가 준비되었으니 Kubeflow의 ML 워크플로우 컴포넌트들을 설치합니다.

5.1 Kubeflow Pipelines 설치

Kubeflow Pipelines는 ML 워크플로우를 정의, 실행, 관리하는 플랫폼입니다.

5.1.1 파이프라인 정의 저장 방식 선택

두 가지 배포 옵션이 있습니다:

옵션 A: 데이터베이스 기반 (전통적 방식)

# 멀티유저 Kubeflow Pipelines 설치
kustomize build applications/pipeline/upstream/env/cert-manager/platform-agnostic-multi-user | kubectl apply -f -

# Pod 상태 확인
kubectl get pods -n kubeflow | grep ml-pipeline

옵션 B: Kubernetes Native API 모드 (권장)

# K8s Custom Resource 기반 파이프라인
kustomize build applications/pipeline/upstream/env/cert-manager/platform-agnostic-multi-user-k8s-native | kubectl apply -f -

# Pod 상태 확인
kubectl get pods -n kubeflow | grep ml-pipeline

# CRD 확인
kubectl get crd | grep pipeline

주요 구성 요소:

  • ml-pipeline: API 서버 및 오케스트레이션
  • ml-pipeline-ui: 웹 UI
  • ml-pipeline-persistenceagent: 워크플로우 상태 저장
  • ml-pipeline-scheduledworkflow: 스케줄링 처리
  • minio (또는 SeaweedFS): 아티팩트 저장소
  • mysql: 메타데이터 저장 (데이터베이스 모드)
  • cache-server: 실행 캐싱

Kubernetes Native API 모드의 장점:

  • 파이프라인 정의를 Kubernetes Custom Resource로 저장
  • GitOps 워크플로우와 자연스럽게 통합
  • kubectl로 파이프라인 관리 가능
  • Kubernetes admission webhook을 통한 검증

아티팩트 저장소 선택:

기본적으로 MinIO가 사용되지만, SeaweedFS로 전환할 수 있습니다:

# SeaweedFS 설치 (MinIO 대체)
kustomize build experimental/seaweedfs/istio | kubectl apply -f -

# 확인
kubectl get pods -n kubeflow | grep seaweedfs

SeaweedFS 사용 이유:

  • 더 나은 성능
  • 낮은 메모리 사용량
  • 투명한 S3 호환성

5.1.2 파이프라인 SDK 사용

설치:

pip install kfp==2.15.2

기본 파이프라인 예제:

from kfp import dsl
import kfp

@dsl.component
def add_numbers(a: float, b: float) -> float:
    """두 숫자를 더합니다"""
    return a + b

@dsl.pipeline(
    name='Addition Pipeline',
    description='간단한 덧셈 파이프라인'
)
def addition_pipeline(a: float = 1.0, b: float = 2.0):
    add_task = add_numbers(a=a, b=b)

# 클라이언트 생성 및 파이프라인 실행
client = kfp.Client(host='http://localhost:8080/pipeline')
client.create_run_from_pipeline_func(
    addition_pipeline,
    arguments={'a': 5.0, 'b': 3.0}
)

Kubernetes Native API 모드 컴파일:

from kfp import compiler

# Kubernetes Native API용 컴파일
compiler.Compiler().compile(
    pipeline_func=addition_pipeline,
    package_path='pipeline.yaml',
    pipeline_parameters={'a': 5.0, 'b': 3.0}
)

5.2 KServe 설치 (모델 서빙)

KServe는 머신러닝 모델을 프로덕션 환경에 배포하고 서빙하는 플랫폼입니다.

# KServe 컴포넌트 설치
kustomize build applications/kserve/kserve | kubectl apply --server-side --force-conflicts -f -

# Models Web App 설치
kustomize build applications/kserve/models-web-app/overlays/kubeflow | kubectl apply -f -

# 확인
kubectl get pods -n kubeflow | grep kserve
kubectl get crd | grep serving.kserve.io

주요 기능:

  • 다양한 프레임워크 지원 (TensorFlow, PyTorch, SKLearn, XGBoost 등)
  • Auto-scaling (scale-to-zero 포함)
  • Canary rollout 및 A/B 테스팅
  • Explainability (모델 설명 가능성)
  • Transformer 및 전후처리

간단한 모델 배포 예제:

apiVersion: serving.kserve.io/v1beta1
kind: InferenceService
metadata:
  name: sklearn-iris
  namespace: kubeflow-user-example-com
spec:
  predictor:
    sklearn:
      storageUri: gs://kfserving-examples/models/sklearn/1.0/model
# 모델 배포
kubectl apply -f inference-service.yaml

# 상태 확인
kubectl get inferenceservice -n kubeflow-user-example-com
kubectl get pods -n kubeflow-user-example-com | grep sklearn-iris

# 추론 요청 테스트
curl -v -H "Content-Type: application/json" \
  -d '{"instances": [[6.8, 2.8, 4.8, 1.4]]}' \
  http://sklearn-iris.kubeflow-user-example-com.example.com/v1/models/sklearn-iris:predict

5.3 Katib 설치 (하이퍼파라미터 튜닝)

Katib는 하이퍼파라미터 튜닝 및 Neural Architecture Search (NAS)를 위한 시스템입니다.

# Katib 설치
kustomize build applications/katib/upstream/installs/katib-with-kubeflow | kubectl apply -f -

# 확인
kubectl get pods -n kubeflow | grep katib
kubectl get crd | grep katib

주요 기능:

  • 다양한 검색 알고리즘 (Random, Grid, Bayesian, Hyperband 등)
  • Early Stopping 지원
  • 병렬 실행
  • 다양한 ML 프레임워크 지원

Katib Experiment 예제:

apiVersion: kubeflow.org/v1beta1
kind: Experiment
metadata:
  name: random-example
  namespace: kubeflow-user-example-com
spec:
  objective:
    type: maximize
    goal: 0.99
    objectiveMetricName: Validation-accuracy
  algorithm:
    algorithmName: random
  parallelTrialCount: 3
  maxTrialCount: 12
  maxFailedTrialCount: 3
  parameters:
    - name: lr
      parameterType: double
      feasibleSpace:
        min: "0.01"
        max: "0.05"
    - name: num-layers
      parameterType: int
      feasibleSpace:
        min: "2"
        max: "5"
  trialTemplate:
    primaryContainerName: training-container
    trialSpec:
      apiVersion: batch/v1
      kind: Job
      spec:
        template:
          spec:
            containers:
              - name: training-container
                image: docker.io/kubeflowkatib/mxnet-mnist:latest
                command:
                  - "python3"
                  - "/opt/mxnet-mnist/mnist.py"
                  - "--batch-size=64"
                  - "--lr=${trialParameters.learningRate}"
                  - "--num-layers=${trialParameters.numLayers}"
            restartPolicy: Never

5.4 Central Dashboard 설치

Central Dashboard는 Kubeflow의 통합 웹 UI입니다.

# Central Dashboard 설치
kustomize build applications/centraldashboard/overlays/oauth2-proxy | kubectl apply -f -

# 확인
kubectl get pods -n kubeflow | grep centraldashboard
kubectl get svc -n kubeflow | grep centraldashboard

주요 기능:

  • 모든 Kubeflow 컴포넌트 통합 접근
  • 네임스페이스/프로파일 관리
  • 리소스 모니터링
  • 빠른 접근 링크

5.5 Notebooks 설치 (Jupyter 환경)

5.5.1 Notebook Controller

# Notebook Controller 설치
kustomize build applications/jupyter/notebook-controller/upstream/overlays/kubeflow | kubectl apply -f -

# 확인
kubectl get pods -n kubeflow | grep notebook-controller

5.5.2 Jupyter Web App

# Jupyter Web App 설치
kustomize build applications/jupyter/jupyter-web-app/upstream/overlays/istio | kubectl apply -f -

# 확인
kubectl get pods -n kubeflow | grep jupyter-web-app

주요 기능:

  • Jupyter Notebook 서버 생성 및 관리
  • 다양한 이미지 옵션 (TensorFlow, PyTorch, RStudio, VSCode 등)
  • 리소스 할당 및 GPU 지원
  • Volume 관리

사용 가능한 공식 이미지:

  • jupyter-tensorflow-full: TensorFlow + Jupyter
  • jupyter-pytorch-full: PyTorch + Jupyter
  • codeserver-python: VSCode Server
  • rstudio-tidyverse: RStudio

5.6 PVC Viewer Controller 설치

# PVC Viewer Controller 설치
kustomize build applications/pvcviewer-controller/upstream/base | kubectl apply -f -

# 확인
kubectl get pods -n kubeflow | grep pvcviewer

주요 기능: 웹 UI에서 PVC 내용 직접 확인 가능

5.7 Profiles + KFAM 설치 (멀티테넌시)

# Profiles 및 KFAM 설치
kustomize build applications/profiles/upstream/overlays/kubeflow | kubectl apply -f -

# 확인
kubectl get pods -n kubeflow | grep profiles
kubectl get crd profiles.kubeflow.org

주요 기능:

  • 사용자별 네임스페이스 격리
  • RBAC 권한 관리
  • 리소스 쿼터 관리
  • 네임스페이스별 기본 설정

5.8 Admission Webhook 설치

# Admission Webhook 설치 (PodDefaults용)
kustomize build applications/admission-webhook/upstream/overlays/cert-manager | kubectl apply -f -

# 확인
kubectl get pods -n kubeflow | grep admission-webhook

주요 기능: PodDefaults를 통한 공통 설정 자동 주입

5.9 Volumes Web Application 설치

# Volumes Web App 설치
kustomize build applications/volumes-web-app/upstream/overlays/istio | kubectl apply -f -

# 확인
kubectl get pods -n kubeflow | grep volumes-web-app

주요 기능: PVC(Persistent Volume Claim) 관리 UI

5.10 Tensorboard 설치

5.10.1 Tensorboard Controller

# Tensorboard Controller 설치
kustomize build applications/tensorboard/tensorboard-controller/upstream/overlays/kubeflow | kubectl apply -f -

# 확인
kubectl get pods -n kubeflow | grep tensorboard-controller

5.10.2 Tensorboards Web App

# Tensorboards Web App 설치
kustomize build applications/tensorboard/tensorboards-web-app/upstream/overlays/istio | kubectl apply -f -

# 확인
kubectl get pods -n kubeflow | grep tensorboards-web-app

주요 기능:

  • TensorBoard 인스턴스 생성 및 관리
  • 학습 진행 상황 시각화
  • 모델 그래프 및 메트릭 분석

5.11 Training Operators 설치

Training Operators는 분산 머신러닝 학습 작업을 관리합니다.

# Trainer v2 설치 (차세대 Training Operator)
kustomize build applications/trainer/upstream/overlays/kubeflow-platform | kubectl apply --server-side --force-conflicts -f -

# 또는 Training Operator v1 설치
# kustomize build applications/training-operator/upstream/overlays/kubeflow | kubectl apply --server-side --force-conflicts -f -

# 확인
kubectl get pods -n kubeflow | grep training
kubectl get crd | grep kubeflow.org

지원하는 Job 타입:

  • TFJob (TensorFlow)
  • PyTorchJob (PyTorch)
  • MPIJob (MPI 기반 분산 학습)
  • MXJob (MXNet)
  • XGBoostJob (XGBoost)
  • PaddleJob (PaddlePaddle)

PyTorchJob 예제:

apiVersion: kubeflow.org/v1
kind: PyTorchJob
metadata:
  name: pytorch-simple
  namespace: kubeflow-user-example-com
spec:
  pytorchReplicaSpecs:
    Master:
      replicas: 1
      restartPolicy: OnFailure
      template:
        spec:
          containers:
            - name: pytorch
              image: gcr.io/kubeflow-ci/pytorch-dist-mnist-test:v1.0
              args:
                - --backend
                - gloo
              resources:
                limits:
                  nvidia.com/gpu: 1
    Worker:
      replicas: 2
      restartPolicy: OnFailure
      template:
        spec:
          containers:
            - name: pytorch
              image: gcr.io/kubeflow-ci/pytorch-dist-mnist-test:v1.0
              args:
                - --backend
                - gloo
              resources:
                limits:
                  nvidia.com/gpu: 1

5.12 Model Registry 설치 (선택사항)

Model Registry는 모델 버전 관리 및 메타데이터 추적을 제공합니다.

# Model Registry 설치
kustomize build applications/model-registry/upstream | kubectl apply -f -

# 확인
kubectl get pods -n kubeflow | grep model-registry

주요 기능:

  • 모델 버전 관리
  • 모델 메타데이터 및 아티팩트 추적
  • 모델 스테이지 관리 (staging, production 등)

5.13 Spark Operator 설치 (선택사항)

# Spark Operator 설치
kustomize build applications/spark/spark-operator/overlays/kubeflow | kubectl apply -f -

# 확인
kubectl get pods -n kubeflow | grep spark

주요 기능: Kubernetes에서 Apache Spark 애플리케이션 실행

5.14 사용자 네임스페이스 생성

# 기본 사용자 네임스페이스 생성
kustomize build common/user-namespace/base | kubectl apply -f -

# 확인
kubectl get namespace kubeflow-user-example-com
kubectl get profile

생성되는 리소스:

  • Namespace: kubeflow-user-example-com
  • Profile: 사용자 프로파일 및 권한
  • 기본 Service Account
  • 네트워크 정책

6. 클러스터 접속 및 검증

6.1 모든 Pod 상태 확인

# 모든 네임스페이스의 Pod 확인
echo "=== Cert-Manager ==="
kubectl get pods -n cert-manager

echo "=== Istio System ==="
kubectl get pods -n istio-system

echo "=== Auth (Dex) ==="
kubectl get pods -n auth

echo "=== OAuth2-Proxy ==="
kubectl get pods -n oauth2-proxy

echo "=== Knative Serving ==="
kubectl get pods -n knative-serving

echo "=== Kubeflow ==="
kubectl get pods -n kubeflow

echo "=== User Namespace ==="
kubectl get pods -n kubeflow-user-example-com

# 모든 Pod가 Running 상태인지 확인
kubectl get pods --all-namespaces | grep -v "Running\|Completed"

6.2 Port-Forward로 접속

가장 간단한 접속 방법은 포트 포워딩입니다:

# Istio Ingress Gateway 포트 포워딩
kubectl port-forward svc/istio-ingressgateway -n istio-system 8080:80

# 브라우저에서 접속
# http://localhost:8080

기본 로그인 정보:

  • Email: user@example.com
  • Password: 12341234

⚠️ 보안 주의사항: 프로덕션 환경에서는 반드시 기본 비밀번호를 변경하세요!

6.3 기본 비밀번호 변경

# bcrypt로 새 비밀번호 해시 생성
python3 -c 'from passlib.hash import bcrypt; import getpass; print(bcrypt.using(rounds=12, ident="2y").hash(getpass.getpass()))'
# 비밀번호 입력 프롬프트가 나타남

# 기존 secret 삭제
kubectl delete secret dex-passwords -n auth

# 새 secret 생성 (HASH를 위에서 생성한 해시로 교체)
kubectl create secret generic dex-passwords \
  --from-literal=DEX_USER_PASSWORD='$2y$12$...' \
  -n auth

# Dex pod 재시작
kubectl delete pods --all -n auth

# 새 비밀번호로 로그인 테스트

6.4 NodePort/LoadBalancer/Ingress 설정 (프로덕션)

프로덕션 환경에서는 HTTPS를 사용해야 합니다:

# nginx-ingress 예제
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: kubeflow-ingress
  namespace: istio-system
  annotations:
    kubernetes.io/ingress.class: nginx
    cert-manager.io/cluster-issuer: letsencrypt-prod
    nginx.ingress.kubernetes.io/backend-protocol: "HTTP"
spec:
  tls:
  - hosts:
    - kubeflow.example.com
    secretName: kubeflow-tls
  rules:
  - host: kubeflow.example.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: istio-ingressgateway
            port:
              number: 80

7. 첫 워크플로우 실행

7.1 Jupyter Notebook 생성

  1. Kubeflow Dashboard에 로그인
  2. 왼쪽 메뉴에서 Notebooks 클릭
  3. + New Notebook 클릭
  4. 다음 설정 입력:
    • Name: my-first-notebook
    • Image: jupyter-tensorflow-full 선택
    • CPU: 1.0
    • Memory: 2.0Gi
    • 필요시 GPU 추가
  5. LAUNCH 클릭
  6. Notebook이 Running 상태가 되면 CONNECT 클릭

7.2 간단한 파이프라인 실행

Notebook에서 다음 코드를 실행:

# KFP SDK 설치 (필요한 경우)
!pip install kfp==2.15.2

from kfp import dsl, compiler
import kfp

# 컴포넌트 정의
@dsl.component(base_image='python:3.9')
def generate_data(n_samples: int) -> str:
    """랜덤 데이터 생성"""
    import json
    import numpy as np

    data = np.random.randn(n_samples, 4).tolist()
    return json.dumps(data)

@dsl.component(base_image='python:3.9')
def train_model(data: str) -> dict:
    """간단한 모델 학습"""
    import json
    import numpy as np
    from sklearn.linear_model import LinearRegression

    data_array = np.array(json.loads(data))
    X = data_array[:, :-1]
    y = data_array[:, -1]

    model = LinearRegression()
    model.fit(X, y)
    score = model.score(X, y)

    return {'score': float(score), 'n_samples': len(X)}

@dsl.component(base_image='python:3.9')
def evaluate_model(metrics: dict) -> str:
    """모델 평가"""
    score = metrics['score']
    n_samples = metrics['n_samples']

    result = f"Model trained on {n_samples} samples with R² score: {score:.4f}"
    print(result)
    return result

# 파이프라인 정의
@dsl.pipeline(
    name='Simple ML Pipeline',
    description='데이터 생성, 학습, 평가를 수행하는 간단한 파이프라인'
)
def simple_ml_pipeline(n_samples: int = 100):
    # 데이터 생성
    data_task = generate_data(n_samples=n_samples)

    # 모델 학습
    train_task = train_model(data=data_task.output)

    # 모델 평가
    evaluate_task = evaluate_model(metrics=train_task.output)

# 파이프라인 컴파일
compiler.Compiler().compile(
    pipeline_func=simple_ml_pipeline,
    package_path='simple_pipeline.yaml'
)

# 파이프라인 실행
client = kfp.Client()
run = client.create_run_from_pipeline_func(
    simple_ml_pipeline,
    arguments={'n_samples': 200},
    experiment_name='my-first-experiment'
)

print(f"파이프라인 실행 ID: {run.run_id}")
print(f"실행 링크: http://localhost:8080/_/pipeline/#/runs/details/{run.run_id}")

7.3 KServe로 모델 배포

# InferenceService 정의
inference_service_yaml = """
apiVersion: serving.kserve.io/v1beta1
kind: InferenceService
metadata:
  name: sklearn-iris
spec:
  predictor:
    sklearn:
      storageUri: gs://kfserving-examples/models/sklearn/1.0/model
"""

# 파일로 저장
with open('inference-service.yaml', 'w') as f:
    f.write(inference_service_yaml)

# 배포 (터미널에서)
# kubectl apply -f inference-service.yaml -n kubeflow-user-example-com

7.4 Katib Experiment 실행

katib_experiment = """
apiVersion: kubeflow.org/v1beta1
kind: Experiment
metadata:
  name: simple-random-search
spec:
  objective:
    type: maximize
    goal: 0.95
    objectiveMetricName: accuracy
  algorithm:
    algorithmName: random
  parallelTrialCount: 2
  maxTrialCount: 6
  parameters:
    - name: lr
      parameterType: double
      feasibleSpace:
        min: "0.001"
        max: "0.1"
  trialTemplate:
    primaryContainerName: training-container
    trialSpec:
      apiVersion: batch/v1
      kind: Job
      spec:
        template:
          spec:
            containers:
              - name: training-container
                image: docker.io/kubeflowkatib/mxnet-mnist:latest
                command:
                  - "python3"
                  - "/opt/mxnet-mnist/mnist.py"
                  - "--lr=${trialParameters.lr}"
            restartPolicy: Never
"""

with open('katib-experiment.yaml', 'w') as f:
    f.write(katib_experiment)

# 실행 (터미널에서)
# kubectl apply -f katib-experiment.yaml -n kubeflow-user-example-com

8. 모니터링 및 문제 해결

8.1 로그 확인

# 특정 Pod 로그 확인
kubectl logs <pod-name> -n kubeflow

# 이전 Pod 로그 확인 (재시작된 경우)
kubectl logs <pod-name> -n kubeflow --previous

# 실시간 로그 모니터링
kubectl logs -f <pod-name> -n kubeflow

# 모든 컨테이너 로그 (멀티 컨테이너 Pod)
kubectl logs <pod-name> -n kubeflow --all-containers

8.2 리소스 사용량 확인

# Metrics Server 설치 (아직 없는 경우)
kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml

# Node 리소스 사용량
kubectl top nodes

# Pod 리소스 사용량
kubectl top pods -n kubeflow
kubectl top pods -n kubeflow-user-example-com

# 특정 Pod의 상세 정보
kubectl describe pod <pod-name> -n kubeflow

8.3 일반적인 문제 해결

문제 1: Pod가 Pending 상태

# Pod 이벤트 확인
kubectl describe pod <pod-name> -n kubeflow

# 일반적인 원인:
# - 리소스 부족 (CPU/Memory)
# - PVC 바인딩 실패
# - Node selector 미스매치

해결책:

# 리소스 증가 또는 불필요한 Pod 삭제
kubectl delete pod <unused-pod> -n kubeflow

# PVC 상태 확인
kubectl get pvc -n kubeflow

문제 2: CrashLoopBackOff

# 로그 확인
kubectl logs <pod-name> -n kubeflow --previous

# 일반적인 원인:
# - 설정 오류
# - 의존성 문제
# - 리소스 제한 초과

문제 3: ImagePullBackOff

# 이미지 pull 실패 확인
kubectl describe pod <pod-name> -n kubeflow

# 해결책: 인증 정보 생성
kubectl create secret docker-registry regcred \
    --docker-server=<registry-server> \
    --docker-username=<username> \
    --docker-password=<password> \
    -n kubeflow

문제 4: Webhook Connection Refused

# Webhook이 준비될 때까지 대기
kubectl wait --for=condition=Ready pod -l app=webhook --timeout=180s -n cert-manager

# 또는 잠시 기다린 후 재시도
sleep 30
kubectl apply -f <manifest.yaml>

8.4 유용한 디버깅 명령어

# 모든 리소스 확인
kubectl get all -n kubeflow

# ConfigMap 확인
kubectl get configmap -n kubeflow
kubectl describe configmap <configmap-name> -n kubeflow

# Secret 확인 (데이터는 base64 인코딩됨)
kubectl get secrets -n kubeflow
kubectl get secret <secret-name> -n kubeflow -o yaml

# Service 및 Endpoint 확인
kubectl get svc -n kubeflow
kubectl get endpoints -n kubeflow

# CRD 목록
kubectl get crd | grep kubeflow

# 특정 CR 확인
kubectl get notebooks -n kubeflow-user-example-com
kubectl get inferenceservices -n kubeflow-user-example-com

9. 프로덕션 배포 고려사항

9.1 고가용성 (HA) 설정

# 여러 replica 설정 (예: Pipeline API 서버)
kubectl scale deployment ml-pipeline -n kubeflow --replicas=3

# PodDisruptionBudget 설정
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
  name: ml-pipeline-pdb
  namespace: kubeflow
spec:
  minAvailable: 2
  selector:
    matchLabels:
      app: ml-pipeline

9.2 백업 및 복구

# Velero를 사용한 백업 (권장)
velero install --provider aws --bucket kubeflow-backup --backup-location-config region=us-east-1

# 전체 네임스페이스 백업
velero backup create kubeflow-backup --include-namespaces kubeflow,kubeflow-user-example-com

# 복구
velero restore create --from-backup kubeflow-backup

9.3 리소스 쿼터 설정

apiVersion: v1
kind: ResourceQuota
metadata:
  name: kubeflow-user-quota
  namespace: kubeflow-user-example-com
spec:
  hard:
    requests.cpu: "10"
    requests.memory: 20Gi
    requests.nvidia.com/gpu: "2"
    persistentvolumeclaims: "10"

9.4 보안 강화

# Network Policy 적용
# RBAC 최소 권한 원칙
# Pod Security Standards 적용
# Istio mTLS 활성화 (기본적으로 활성화됨)

# Service Account 토큰 자동 마운트 비활성화
kubectl patch serviceaccount default -n kubeflow-user-example-com \
  -p '{"automountServiceAccountToken": false}'

9.5 모니터링 스택 설치 (Prometheus + Grafana)

# Helm으로 Prometheus Operator 설치
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm repo update

helm install prometheus prometheus-community/kube-prometheus-stack \
  --namespace monitoring \
  --create-namespace

# Kubeflow 메트릭 수집 설정
# ServiceMonitor 생성하여 Kubeflow 컴포넌트 모니터링

10. 성능 최적화

10.1 리소스 제한 설정

# Notebook 서버 리소스 제한 예제
apiVersion: kubeflow.org/v1
kind: Notebook
metadata:
  name: optimized-notebook
spec:
  template:
    spec:
      containers:
      - name: notebook
        resources:
          requests:
            cpu: "1"
            memory: "2Gi"
          limits:
            cpu: "2"
            memory: "4Gi"
            nvidia.com/gpu: "1"

10.2 파이프라인 캐싱 활성화

KFP 파이프라인에서 캐싱을 사용하면 동일한 입력으로 이전에 실행된 컴포넌트를 재사용합니다:

@dsl.pipeline(
    name='Cached Pipeline',
    description='캐싱이 활성화된 파이프라인'
)
def cached_pipeline():
    # 캐싱 활성화 (기본값)
    task1 = component1()

    # 특정 태스크 캐싱 비활성화
    task2 = component2().set_caching_options(False)

10.3 병렬 처리

# 병렬 실행 예제
@dsl.pipeline(
    name='Parallel Pipeline'
)
def parallel_pipeline():
    # 이 태스크들은 병렬로 실행됨
    task1 = train_model_1()
    task2 = train_model_2()
    task3 = train_model_3()

    # 모든 병렬 태스크 완료 후 실행
    final_task = ensemble_models(
        model1=task1.output,
        model2=task2.output,
        model3=task3.output
    )

11. 업그레이드 및 유지보수

11.1 Kubeflow 업그레이드

# 현재 버전 확인
kubectl get pods -n kubeflow -o yaml | grep "image:"

# 새 버전으로 업그레이드
git checkout v1.11.0  # 새 버전 태그
kustomize build example | kubectl apply -f -

# 롤링 업데이트 상태 확인
kubectl rollout status deployment/ml-pipeline -n kubeflow

11.2 Kustomize 오버레이로 커스터마이징

# custom-overlay/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

bases:
  - github.com/kubeflow/manifests/example?ref=v1.10.0

# 이미지 변경
images:
  - name: gcr.io/ml-pipeline/api-server
    newTag: 2.15.0

# 리소스 패치
patchesStrategicMerge:
  - pipeline-resources.yaml

# ConfigMap 수정
configMapGenerator:
  - name: pipeline-install-config
    behavior: merge
    literals:
      - DefaultPipelineRoot=s3://my-bucket/pipelines

11.3 주기적인 유지보수 작업

# 완료된 파이프라인 실행 정리 (30일 이상 된 것)
kubectl delete workflows -n kubeflow \
  --field-selector status.phase=Succeeded

# 사용하지 않는 PVC 정리
kubectl get pvc -n kubeflow-user-example-com | grep Released

# 로그 로테이션 확인
kubectl logs <pod-name> -n kubeflow --tail=100

12. 추가 컴포넌트 및 확장

12.1 Ray 설치 (분산 컴퓨팅)

# Ray Operator 설치 (experimental)
kustomize build experimental/ray | kubectl apply -f -

12.2 MLflow 통합

# MLflow 서버 배포 (별도)
# Kubeflow Pipelines과 연동하여 실험 추적

12.3 Feast 통합 (Feature Store)

# Feast를 사용한 피처 관리
pip install feast
feast init my_feature_repo

마치며

이 가이드에서는 Kubeflow의 각 컴포넌트를 상세히 설치하는 방법을 다루었습니다. Kubeflow는 복잡한 시스템이지만, 각 컴포넌트의 역할을 이해하면 ML 워크플로우를 효과적으로 관리할 수 있습니다.

학습 리소스

다음 단계

  1. Kubeflow Pipelines 심화: 복잡한 ML 워크플로우 구축
  2. 분산 학습: PyTorchJob, TFJob 활용
  3. 모델 서빙 최적화: KServe Transformer, Explainer 활용
  4. MLOps 파이프라인: CI/CD와 Kubeflow 통합