Data Engineering/Airflow

[Airflow 가이드 ep.4] 1부 개념과 설정 #4 | Airflow 설치: 로컬, Docker, Kubernetes 기반 설치 비교

ygtoken 2025. 3. 25. 15:37
728x90

이 글에서는 Apache Airflow의 다양한 설치 방법에 대해 자세히 알아봅니다. 로컬 환경 설치부터 Docker 컨테이너 기반 설치, 그리고 Kubernetes 환경에서의 설치까지 각 방법의 특징과 장단점을 비교하고, 실제 설치 과정을 단계별로 살펴보겠습니다.


📌 Airflow 설치 개요

설치 전 고려사항

Airflow를 설치하기 전에 먼저 고려해야 할 몇 가지 중요한 사항들이 있습니다:

  1. 환경 요구사항:
    • Python 3.6 이상 (Python 3.8 이상 권장)
    • 운영체제: Linux(권장), macOS, Windows(WSL2 권장)
    • 충분한 CPU, 메모리, 디스크 공간
  2. 사용 목적:
    • 개발/학습용: 간단한 로컬 설치 적합
    • 소규모 프로덕션: Docker 기반 설치 적합
    • 대규모 프로덕션: Kubernetes 기반 설치 적합
  3. 관리 리소스:
    • 관리할 수 있는 인프라 리소스
    • 기술적 전문성 수준
    • 유지보수 부담

설치 방법 비교

특성 로컬 설치 Docker 기반 Kubernetes 기반
설치 난이도 쉬움~중간 중간 높음
확장성 낮음 중간 높음
격리성 낮음 높음 매우 높음
유지보수 복잡함 중간 자동화 가능
배포 용이성 낮음 높음 매우 높음
리소스 효율성 낮음 중간 높음
개발 환경 일치 어려움 쉬움 쉬움

 

설치 환경에 따른 권장 Executor

환경별 권장 Airflow Executor

 

설치 환경별로 권장되는 Executor 유형은 다음과 같습니다:

  1. 로컬 설치:
    • 개발/테스트: SequentialExecutor(SQLite 사용시) 또는 LocalExecutor
    • 소규모 프로덕션: LocalExecutor(PostgreSQL/MySQL 사용)
  2. Docker 기반 설치:
    • 단일 호스트: LocalExecutor
    • 다중 호스트: CeleryExecutor
  3. Kubernetes 기반 설치:
    • KubernetesExecutor 또는 CeleryKubernetesExecutor

Airflow 설치 방법별 구성 비교


📌 로컬 환경 설치

Python 기반 직접 설치

가장 기본적인 설치 방법으로, 직접 Python 환경에 Airflow를 설치합니다.

  1. Python 가상환경 설정:
# 가상환경 생성 및 활성화
# 가상환경을 사용하면 패키지 의존성 충돌을 방지하고 격리된 환경을 구성할 수 있음
python3 -m venv airflow_venv
source airflow_venv/bin/activate  # Linux/macOS
# 또는
airflow_venv\Scripts\activate      # Windows
  1. Airflow 설치:
# AIRFLOW_HOME 환경변수 설정 (선택사항)
# 이 변수는 Airflow가 설정 파일, 로그, DAG 파일 등을 저장할 디렉토리를 지정
export AIRFLOW_HOME=~/airflow  # Linux/macOS
# 또는
set AIRFLOW_HOME=C:\airflow   # Windows

# 의존성 충돌 방지를 위한 제약조건 파일 다운로드
# 이 파일은 특정 Airflow 버전과 호환되는 의존성 패키지 버전을 명시
AIRFLOW_VERSION=2.5.1
PYTHON_VERSION="$(python --version | cut -d " " -f 2 | cut -d "." -f 1-2)"
CONSTRAINT_URL="https://raw.githubusercontent.com/apache/airflow/constraints-${AIRFLOW_VERSION}/constraints-${PYTHON_VERSION}.txt"

# Airflow 설치 (제약조건 적용)
# 특정 버전의 Airflow와 해당 버전과 호환되는 의존성을 함께 설치
pip install "apache-airflow==${AIRFLOW_VERSION}" --constraint "${CONSTRAINT_URL}"

# 추가 프로바이더 설치 (선택사항)
# 프로바이더는 특정 서비스나 플랫폼과의 연동을 위한 추가 패키지
pip install apache-airflow-providers-amazon  # AWS 연동
pip install apache-airflow-providers-google  # GCP 연동
pip install apache-airflow-providers-mysql   # MySQL 연동
  1. 데이터베이스 초기화:
# 기본 SQLite 데이터베이스 초기화
# 이 명령은 Airflow에 필요한 테이블 구조를 생성
airflow db init

# 관리자 계정 생성
# Airflow 웹 인터페이스에 로그인할 때 사용할 계정 정보
airflow users create \
    --username admin \
    --firstname Admin \
    --lastname User \
    --role Admin \
    --email admin@example.com \
    --password admin
  1. Airflow 서비스 시작:
# Webserver 시작 (UI 제공)
# 기본적으로 8080 포트에서 실행됨
airflow webserver --port 8080

# 별도의 터미널에서 Scheduler 시작
# DAG 스케줄링과 태스크 실행을 담당
airflow scheduler

PostgreSQL 데이터베이스 연동

프로덕션 환경에서는 SQLite 대신 PostgreSQL이나 MySQL과 같은 데이터베이스를 사용하는 것이 권장됩니다.

  1. PostgreSQL 설치 및 설정:
# PostgreSQL 설치 (Ubuntu 기준)
sudo apt update
sudo apt install postgresql postgresql-contrib

# PostgreSQL 서비스 시작
sudo systemctl start postgresql
sudo systemctl enable postgresql

# PostgreSQL 사용자 및 데이터베이스 생성
sudo -u postgres psql

postgres=# CREATE USER airflow WITH PASSWORD 'airflow';
postgres=# CREATE DATABASE airflow;
postgres=# GRANT ALL PRIVILEGES ON DATABASE airflow TO airflow;
postgres=# \q
  1. Airflow 데이터베이스 연결 설정:
# PostgreSQL 관련 패키지 설치
pip install apache-airflow[postgres]

# airflow.cfg 파일에서 SQL Alchemy 연결 문자열 수정
# AIRFLOW_HOME 디렉토리 내의 airflow.cfg 파일 편집
# sql_alchemy_conn 항목을 찾아 다음과 같이 수정:
sql_alchemy_conn = postgresql+psycopg2://airflow:airflow@localhost/airflow

# 데이터베이스 초기화
airflow db init
  1. LocalExecutor 설정:
# airflow.cfg 파일에서 executor 설정 변경
# executor 항목을 찾아 다음과 같이 수정:
executor = LocalExecutor

로컬 설치의 장단점

장점:

  • 설치가 비교적 간단함
  • 리소스 요구사항이 낮음
  • 개발 및 학습 환경에 적합
  • 직접적인 파일 시스템 접근이 용이함

단점:

  • 확장성이 제한적임
  • 환경 의존성 문제 발생 가능
  • 버전 관리 및 유지보수가 복잡함
  • 여러 환경 간 일관성 유지가 어려움

📌 Docker 기반 설치

Docker Compose를 이용한 설치

Docker를 사용하면 환경 독립적으로 Airflow를 빠르게 설치하고 실행할 수 있습니다.

  1. 필수 요구사항:
    • Docker Engine
    • Docker Compose (v1.29.1 이상)
    • 최소 4GB 메모리
  2. 디렉토리 구조 설정:
# 프로젝트 디렉토리 생성
mkdir -p ./airflow/dags ./airflow/logs ./airflow/plugins ./airflow/config

# 파일 권한 설정
# Linux/macOS에서는 파일 권한 설정이 중요
echo -e "AIRFLOW_UID=$(id -u)" > .env
  1. docker-compose.yaml 파일 다운로드:
# 공식 docker-compose 파일 다운로드
curl -LfO 'https://airflow.apache.org/docs/apache-airflow/2.5.1/docker-compose.yaml'
  1. docker-compose.yaml 파일 커스터마이징:
# docker-compose.yaml 파일 내용 일부
version: '3'

x-airflow-common: &airflow-common
  image: apache/airflow:2.5.1  # Airflow 이미지 버전
  environment: &airflow-common-env
    AIRFLOW__CORE__EXECUTOR: CeleryExecutor  # 실행자 유형 설정
    AIRFLOW__DATABASE__SQL_ALCHEMY_CONN: postgresql+psycopg2://airflow:airflow@postgres/airflow  # DB 연결
    AIRFLOW__CELERY__RESULT_BACKEND: db+postgresql://airflow:airflow@postgres/airflow  # Celery 결과 저장소
    AIRFLOW__CELERY__BROKER_URL: redis://:@redis:6379/0  # Celery 브로커 URL
    AIRFLOW__CORE__FERNET_KEY: ''  # 보안 키, 프로덕션에서는 반드시 설정해야 함
    AIRFLOW__CORE__DAGS_ARE_PAUSED_AT_CREATION: 'true'  # 새 DAG 기본 일시정지 여부
    AIRFLOW__CORE__LOAD_EXAMPLES: 'true'  # 예제 DAG 로드 여부
    AIRFLOW__API__AUTH_BACKENDS: 'airflow.api.auth.backend.basic_auth'  # 인증 백엔드
  volumes:  # 볼륨 마운트 설정
    - ./airflow/dags:/opt/airflow/dags
    - ./airflow/logs:/opt/airflow/logs
    - ./airflow/plugins:/opt/airflow/plugins
    - ./airflow/config:/opt/airflow/config
  user: "${AIRFLOW_UID:-50000}:0"  # 컨테이너 내 사용자 ID
  depends_on: &airflow-common-depends-on
    redis:
      condition: service_healthy
    postgres:
      condition: service_healthy

services:
  postgres:  # PostgreSQL 데이터베이스 서비스
    image: postgres:13
    environment:
      POSTGRES_USER: airflow
      POSTGRES_PASSWORD: airflow
      POSTGRES_DB: airflow
    volumes:
      - postgres-db-volume:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD", "pg_isready", "-U", "airflow"]
      interval: 5s
      retries: 5
    restart: always

  redis:  # Redis 서비스 (Celery 브로커로 사용)
    image: redis:latest
    expose:
      - 6379
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 5s
      timeout: 30s
      retries: 50
    restart: always

  airflow-webserver:  # Airflow 웹서버 서비스
    <<: *airflow-common
    command: webserver
    ports:
      - 8080:8080
    healthcheck:
      test: ["CMD", "curl", "--fail", "http://localhost:8080/health"]
      interval: 10s
      timeout: 10s
      retries: 5
    restart: always
    depends_on:
      <<: *airflow-common-depends-on
      airflow-init:
        condition: service_completed_successfully

  airflow-scheduler:  # Airflow 스케줄러 서비스
    <<: *airflow-common
    command: scheduler
    healthcheck:
      test: ["CMD-SHELL", 'airflow jobs check --job-type SchedulerJob --hostname "$${HOSTNAME}"']
      interval: 10s
      timeout: 10s
      retries: 5
    restart: always
    depends_on:
      <<: *airflow-common-depends-on
      airflow-init:
        condition: service_completed_successfully

  airflow-worker:  # Airflow 워커 서비스 (Celery 워커)
    <<: *airflow-common
    command: celery worker
    healthcheck:
      test:
        - "CMD-SHELL"
        - 'celery --app airflow.executors.celery_executor.app inspect ping -d "celery@$${HOSTNAME}"'
      interval: 10s
      timeout: 10s
      retries: 5
    restart: always
    depends_on:
      <<: *airflow-common-depends-on
      airflow-init:
        condition: service_completed_successfully

  airflow-init:  # Airflow 초기화 서비스
    <<: *airflow-common
    entrypoint: /bin/bash
    command:
      - -c
      - |
        function ver() {
          printf "%04d%04d%04d%04d" $${1//./ }
        }
        airflow_version=$$(PYTHONPATH=. python -c "import airflow; print(airflow.__version__)")
        airflow_version_comparable=$$(ver $${airflow_version})
        min_airflow_version=2.2.0
        min_airflow_version_comparable=$$(ver $${min_airflow_version})
        if (( airflow_version_comparable < min_airflow_version_comparable )); then
          echo
          echo -e "\033[1;31mERROR!!!: Too old Airflow version $${airflow_version}!\e[0m"
          echo "The minimum Airflow version supported: $${min_airflow_version}. Only use this or higher!"
          echo
          exit 1
        fi
        if [[ -z "${AIRFLOW_UID}" ]]; then
          echo
          echo -e "\033[1;33mWARNING!!!: AIRFLOW_UID not set!\e[0m"
          echo "If you are on Linux, you SHOULD follow the instructions below to set "
          echo "AIRFLOW_UID environment variable, otherwise files will be owned by root."
          echo "For other operating systems you can get rid of the warning with manually created .env file:"
          echo "    See: https://airflow.apache.org/docs/apache-airflow/stable/howto/docker-compose/index.html#setting-the-right-airflow-user"
          echo
        fi
        one_meg=1048576
        mem_available=$$(($$(getconf _PHYS_PAGES) * $$(getconf PAGE_SIZE) / one_meg))
        cpus_available=$$(grep -cE 'cpu[0-9]+' /proc/stat)
        disk_available=$$(df / | tail -1 | awk '{print $$4}')
        warning_resources="false"
        if (( mem_available < 4000 )) ; then
          echo
          echo -e "\033[1;33mWARNING!!!: Not enough memory available for Docker.\e[0m"
          echo "At least 4GB of memory required. You have $$(numfmt --to iec $$((mem_available * one_meg)))"
          echo
          warning_resources="true"
        fi
        if (( cpus_available < 2 )); then
          echo
          echo -e "\033[1;33mWARNING!!!: Not enough CPUS available for Docker.\e[0m"
          echo "At least 2 CPUs recommended. You have $${cpus_available}"
          echo
          warning_resources="true"
        fi
        if (( disk_available < one_meg * 10 )); then
          echo
          echo -e "\033[1;33mWARNING!!!: Not enough Disk space available for Docker.\e[0m"
          echo "At least 10 GBs recommended. You have $$(numfmt --to iec $$((disk_available * 1024 )))"
          echo
          warning_resources="true"
        fi
        if [[ $${warning_resources} == "true" ]]; then
          echo
          echo -e "\033[1;33mWARNING!!!: You have not enough resources to run Airflow (see above)!\e[0m"
          echo "Please follow the instructions to increase amount of resources available:"
          echo "   https://airflow.apache.org/docs/apache-airflow/stable/howto/docker-compose/index.html#before-you-begin"
          echo
        fi
        mkdir -p /sources/logs /sources/dags /sources/plugins
        chown -R "${AIRFLOW_UID}:0" /sources/{logs,dags,plugins}
        exec airflow db init

volumes:
  postgres-db-volume:
  1. LocalExecutor로 변경 (선택사항):

CeleryExecutor가 기본으로 설정되어 있지만, 단일 호스트에서 실행하는 경우 더 간단한 LocalExecutor로 변경할 수 있습니다.

# docker-compose.yaml 파일에서 다음 부분 수정
environment: &airflow-common-env
  AIRFLOW__CORE__EXECUTOR: LocalExecutor  # CeleryExecutor에서 LocalExecutor로 변경

# 그리고 redis 및 airflow-worker 서비스를 제거
# Redis 서비스와 워커 서비스는 Celery 기반 실행에서만 필요
  1. Docker Compose로 Airflow 실행:
# 먼저 권한 초기화
docker-compose up airflow-init

# 전체 서비스 실행
docker-compose up -d

# 서비스 상태 확인
docker-compose ps
  1. Airflow 웹 UI 접속:
    • 브라우저에서 http://localhost:8080 접속
    • 기본 사용자 이름: airflow
    • 기본 비밀번호: airflow

프로덕션 환경을 위한 추가 설정

실제 프로덕션 환경에서는 보안 및 성능을 위한 추가 설정이 필요합니다:

  1. 보안 키 설정:
# docker-compose.yaml 파일에서 FERNET_KEY 설정
# Python으로 키 생성 후 환경 변수에 설정:
# python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"
environment:
  AIRFLOW__CORE__FERNET_KEY: 'your-generated-fernet-key'
  1. 예제 DAG 비활성화:
# docker-compose.yaml 파일에서 예제 로드 비활성화
AIRFLOW__CORE__LOAD_EXAMPLES: 'false'
  1. 성능 튜닝:
# docker-compose.yaml 파일에서 성능 관련 설정 추가
AIRFLOW__WEBSERVER__WORKERS: 4  # 웹서버 워커 수
AIRFLOW__SCHEDULER__MAX_THREADS: 2  # 스케줄러 스레드 수
  1. 로그 볼륨 설정:
# 영구 로그 저장을 위한 볼륨 설정 추가
volumes:
  airflow-logs:

services:
  airflow-webserver:
    volumes:
      - airflow-logs:/opt/airflow/logs

 

Docker 기반 설치의 장단점

장점:

  • 환경 독립적인 일관된 실행
  • 간편한 버전 관리 및 업그레이드
  • 구성 요소 간 격리
  • 개발 및 프로덕션 환경의 일치성

단점:

  • Docker 및 Docker Compose에 대한 이해 필요
  • 로컬 설치보다 높은 리소스 요구사항
  • 호스트 시스템과의 통합 작업이 복잡할 수 있음
  • 대규모 환경에서는 확장성 제한

📌 Kubernetes 기반 설치

Helm을 사용한 Airflow 설치

Kubernetes 환경에서는 Helm 차트를 사용하여 Airflow를 쉽게 배포할 수 있습니다.

  1. 필수 요구사항:
    • Kubernetes 클러스터 (1.20 이상)
    • Helm 3.0 이상
    • kubectl 구성
  2. Helm 저장소 추가 및 업데이트:
# Airflow Helm 저장소 추가
# 이 저장소는 공식 Airflow Helm 차트를 제공
helm repo add apache-airflow https://airflow.apache.org/

# Helm 저장소 업데이트
helm repo update
  1. values.yaml 파일 생성:

먼저 기본 설정 파일을 추출하여 커스터마이징할 기준을 마련합니다:

# 기본 values.yaml 파일 추출
helm show values apache-airflow/airflow > values.yaml

그리고 필요에 따라 values.yaml 파일을 수정합니다:

# values.yaml 주요 설정 예시
images:
  airflow:
    repository: apache/airflow  # Airflow 이미지 저장소
    tag: 2.5.1  # Airflow 버전

executor: "KubernetesExecutor"  # 실행자 설정: KubernetesExecutor, CeleryExecutor, LocalExecutor 등

# 데이터베이스 설정
data:
  metadataConnection:
    user: airflow
    pass: airflow
    host: airflow-postgresql.default.svc.cluster.local
    port: 5432
    db: airflow

# Webserver 설정
webserver:
  replicas: 2  # 웹서버 Pod 수
  resources:  # 리소스 제한
    limits:
      cpu: "1"
      memory: 1Gi
    requests:
      cpu: "0.5"
      memory: 500Mi
  service:
    type: ClusterIP  # 서비스 타입 (ClusterIP, NodePort, LoadBalancer)
  
# Scheduler 설정
scheduler:
  replicas: 1  # 스케줄러 Pod 수
  resources:
    limits:
      cpu: "1"
      memory: 1Gi
    requests:
      cpu: "0.5"
      memory: 500Mi

# DAG 설정
dags:
  persistence:
    enabled: true  # DAG 영구 저장소 활성화
    size: 1Gi
    storageClassName: standard
  gitSync:  # Git 동기화 설정
    enabled: true  # Git 동기화 활성화
    repo: https://github.com/your-username/airflow-dags.git
    branch: main
    rev: HEAD
    depth: 1
    maxFailures: 0
    subPath: "dags"
    wait: 60

# 로그 설정
logs:
  persistence:
    enabled: true  # 로그 영구 저장소 활성화
    size: 5Gi
    storageClassName: standard

# 인증 및 권한 설정
webserverConfig:
  webserverConfig: |
    from airflow.www.security import AirflowSecurityManager
    from flask_appbuilder.security.manager import AUTH_DB
    
    AUTHENTICATE = True
    AUTH_TYPE = AUTH_DB
    AUTH_USER_REGISTRATION = False
    AUTH_USER_REGISTRATION_ROLE = "Public"
    
ingress:
  enabled: true  # 인그레스 활성화
  web:
    annotations:
      kubernetes.io/ingress.class: nginx
    host: airflow.example.com
    path: "/"
  1. Helm으로 Airflow 배포:
# Namespace 생성 (선택사항)
kubectl create namespace airflow

# Helm 차트 배포
helm install airflow apache-airflow/airflow \
  --namespace airflow \
  --values values.yaml
  1. 배포 상태 확인:
# Pod 상태 확인
kubectl get pods -n airflow

# 서비스 확인
kubectl get svc -n airflow

# Ingress 확인 (활성화한 경우)
kubectl get ingress -n airflow

 

 ✅ GitOps 기반 DAG 관리

Kubernetes 환경에서는 GitOps 방식으로 DAG를 관리하는 것이 효율적입니다:

  1. Git 저장소 구성:
    • DAG 파일을 위한 전용 Git 저장소 생성
    • 브랜치 전략 수립 (예: dev, staging, prod)
  2. GitSync 설정:
# values.yaml 파일의 GitSync 설정
dags:
  gitSync:
    enabled: true
    repo: https://github.com/your-username/airflow-dags.git
    branch: main
    rev: HEAD
    depth: 1
    maxFailures: 0
    subPath: "dags"
    wait: 60
    sshKeySecret: airflow-ssh-secret  # SSH 인증 사용 시
  1. SSH 인증 설정 (선택사항):
# SSH 키 생성
ssh-keygen -t rsa -b 4096 -C "airflow@example.com" -f airflow-key

# Kubernetes Secret 생성
kubectl create secret generic airflow-ssh-secret \
  --namespace airflow \
  --from-file=gitSshKey=airflow-key \
  --from-file=known_hosts=~/.ssh/known_hosts

 

프로덕션 환경을 위한 고급 설정

  1. 고가용성 구성:
# values.yaml 파일에서 고가용성 설정
scheduler:
  replicas: 2  # 다중 스케줄러 (HA 모드용)

webserver:
  replicas: 3  # 다중 웹서버

redis:  # CeleryExecutor 사용시
  cluster:
    enabled: true
    slaveCount: 2

postgresql:
  primary:
    replicaCount: 1  # Read replica 사용
  readReplicas:
    replicaCount: 1
  1. 메트릭 모니터링 설정:
# values.yaml 파일에서 Prometheus 메트릭 설정
metrics:
  enabled: true
  serviceMonitor:
    enabled: true
  1. 리소스 요청 및 제한 설정:
# values.yaml 파일에서 리소스 설정
scheduler:
  resources:
    limits:
      cpu: "2"
      memory: 2Gi
    requests:
      cpu: "1"
      memory: 1Gi

webserver:
  resources:
    limits:
      cpu: "1"
      memory: 1Gi
    requests:
      cpu: "0.5"
      memory: 500Mi
  1. 외부 데이터베이스 연결:
# values.yaml 파일에서 외부 데이터베이스 설정
postgresql:
  enabled: false  # 내장 PostgreSQL 비활성화

data:
  metadataConnection:
    user: airflow
    pass: airflow
    host: your-external-postgresql.example.com
    port: 5432
    db: airflow
    sslmode: require  # SSL 모드 설정

 

Kubernetes 기반 설치의 장단점

장점:

  • 높은 확장성과 고가용성
  • 자원 사용 최적화
  • 자동화된 롤링 업데이트 및 롤백
  • 선언적 구성 관리
  • GitOps 기반 CI/CD 통합

단점:

  • 복잡한 설정 및 유지 관리
  • Kubernetes 전문 지식 필요
  • 소규모 환경에서는 오버헤드가 클 수 있음
  • 초기 설정 시간이 오래 걸림
  • 문제 진단이 더 복잡할 수 있음

📌 설치 후 필수 구성 및 확인 사항

보안 설정

모든 설치 환경에서 중요한 보안 설정 사항들:

  1. Fernet 키 설정:

Fernet 키는 연결 비밀번호 등의 민감한 정보를 암호화하는 데 사용됩니다.

# Python으로 Fernet 키 생성
python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"

# airflow.cfg 파일에서 설정
[core]
fernet_key = YOUR_GENERATED_KEY
  1. 웹 서버 인증 설정:
# airflow.cfg 파일에서 설정
[webserver]
authenticate = True
auth_backend = airflow.auth.backends.password_auth

# 또는 LDAP 인증 사용
auth_backend = airflow.auth.backends.ldap_auth
  1. API 인증 구성:
# airflow.cfg 파일에서 설정
[api]
auth_backend = airflow.api.auth.backend.basic_auth
  1. RBAC(역할 기반 접근 제어) 활성화:
# airflow.cfg 파일에서 설정
[webserver]
rbac = True

네트워킹 설정

  1. 웹 서버 설정:
# airflow.cfg 파일에서 설정
[webserver]
web_server_host = 0.0.0.0  # 모든 인터페이스에서 접근 가능
web_server_port = 8080     # 웹 서버 포트
base_url = http://my-airflow.example.com  # 외부 접근 URL
  1. SSL/TLS 구성(프로덕션 필수):
# airflow.cfg 파일에서 설정
[webserver]
web_server_ssl_cert = /path/to/cert.pem
web_server_ssl_key = /path/to/key.pem

 

DAG 설정

  1. DAG 폴더 설정:
# airflow.cfg 파일에서 설정
[core]
dags_folder = /path/to/dags
  1. DAG 파싱 설정:
# airflow.cfg 파일에서 설정
[scheduler]
dag_dir_list_interval = 300  # DAG 폴더 스캔 주기(초)
min_file_process_interval = 30  # 동일 파일 최소 재처리 간격
  1. 기본 DAG 옵션 설정:
# airflow.cfg 파일에서 설정
[core]
default_timezone = UTC  # 기본 시간대
dags_are_paused_at_creation = True  # 생성 시 DAG 일시 중지 여부
load_examples = False  # 예제 DAG 로딩 여부

 

성능 최적화 설정

  1. 스케줄러 설정:
# airflow.cfg 파일에서 설정
[scheduler]
max_threads = 4  # 스케줄러 스레드 수
scheduler_heartbeat_sec = 5  # 스케줄러 하트비트 간격
max_tis_per_query = 512  # 쿼리당 최대 태스크 인스턴스 수
  1. 웹 서버 설정:
# airflow.cfg 파일에서 설정
[webserver]
workers = 4  # 웹 서버 워커 수
worker_refresh_batch_size = 1  # 한 번에 재시작할 워커 수
worker_refresh_interval = 30  # 워커 갱신 간격(초)
  1. 데이터베이스 설정:
# airflow.cfg 파일에서 설정
[core]
sql_alchemy_pool_size = 5  # 데이터베이스 연결 풀 크기
sql_alchemy_pool_recycle = 1800  # 연결 재활용 시간(초)
sql_alchemy_max_overflow = 10  # 최대 초과 연결 수

 

로깅 설정

  1. 로그 경로 설정:
# airflow.cfg 파일에서 설정
[logging]
base_log_folder = /path/to/logs
dag_processor_manager_log_location = /path/to/logs/dag_processor_manager.log
  1. 원격 로깅 설정(선택사항):
# airflow.cfg 파일에서 설정
[logging]
remote_logging = True
remote_base_log_folder = s3://my-bucket/airflow/logs  # S3 사용 예시
remote_log_conn_id = my_aws_conn  # 원격 저장소 연결 ID

 

설치 검증 및 테스트

  1. 시스템 상태 확인:
# 서비스 상태 확인
systemctl status airflow-webserver
systemctl status airflow-scheduler

# 또는 Docker 환경에서
docker-compose ps

# 또는 Kubernetes 환경에서
kubectl get pods -n airflow
  1. 웹 UI 접속 테스트:
    • 브라우저에서 Airflow 웹 UI 접속 (http://localhost:8080)
    • 로그인 및 기본 내비게이션 테스트
  2. 샘플 DAG 실행:
# 테스트용 간단한 DAG 파일 생성
cat << EOF > $AIRFLOW_HOME/dags/test_dag.py
from datetime import datetime, timedelta
from airflow import DAG
from airflow.operators.bash import BashOperator

default_args = {
    'owner': 'airflow',
    'depends_on_past': False,
    'start_date': datetime(2023, 1, 1),
    'email_on_failure': False,
    'email_on_retry': False,
    'retries': 1,
    'retry_delay': timedelta(minutes=5),
}

with DAG(
    'test_dag',
    default_args=default_args,
    description='A simple test DAG',
    schedule_interval=timedelta(days=1),
) as dag:
    t1 = BashOperator(
        task_id='print_date',
        bash_command='date',
    )

    t2 = BashOperator(
        task_id='print_hello',
        bash_command='echo "Hello World!"',
    )

    t1 >> t2
EOF

# DAG 구문 검사
python $AIRFLOW_HOME/dags/test_dag.py

# 웹 UI에서 해당 DAG 활성화 후 실행 결과 확인
  1. 로그 확인:
# 로그 파일 확인
tail -f $AIRFLOW_HOME/logs/scheduler/latest/*.log
tail -f $AIRFLOW_HOME/logs/dag_processor_manager/latest/*.log

📌 설치 방법 선택 가이드

사용 시나리오별 권장 설치 방법

각 환경과 요구사항에 따른 최적의 설치 방법을 선택하기 위한 가이드입니다:

  1. 개발 및 학습 환경:
    • 권장 방법: 로컬 설치 또는 Docker Compose
    • 이유: 간단한 설정, 빠른 시작, 낮은 오버헤드
    • Executor: SequentialExecutor(SQLite) 또는 LocalExecutor(PostgreSQL)
  2. 소규모 프로덕션 환경:
    • 권장 방법: Docker Compose
    • 이유: 격리된 환경, 쉬운 유지 관리, 중간 수준의 확장성
    • Executor: LocalExecutor 또는 CeleryExecutor
  3. 중대규모 프로덕션 환경:
    • 권장 방법: Kubernetes 기반 설치
    • 이유: 높은 확장성, 고가용성, 자원 최적화
    • Executor: KubernetesExecutor 또는 CeleryKubernetesExecutor
  4. 클라우드 환경:
    • 권장 방법: 관리형 서비스 또는 Kubernetes
    • 이유: 인프라 관리 부담 감소, 확장성, 통합 서비스
    • 옵션: AWS MWAA, Google Cloud Composer, 또는 자체 관리 Kubernetes

제약 조건에 따른 선택

특정 제약 조건이 있는 경우의 권장 선택:

  1. 제한된 리소스:
    • 권장 방법: 로컬 설치(최소 설정)
    • Executor: SequentialExecutor
  2. 네트워크 격리 환경:
    • 권장 방법: 로컬 설치 또는 Docker(내부 네트워크)
    • 고려사항: 외부 의존성 최소화
  3. 엄격한 보안 요구사항:
    • 권장 방법: 자체 관리 Kubernetes 또는 격리된 Docker 환경
    • 고려사항: 네트워크 정책, 암호화, 접근 제어
  4. 기존 CI/CD 파이프라인 통합:
    • 권장 방법: GitOps가 적용된 Kubernetes 설치
    • 고려사항: 버전 관리, 배포 자동화

마이그레이션 고려사항

기존 설치에서 다른 방식으로 마이그레이션할 때 고려해야 할 사항:

  1. 로컬 → Docker:
    • 데이터베이스 백업 및 복원
    • 연결 정보 및 변수 마이그레이션
    • DAG 코드 이식성 확인
  2. Docker → Kubernetes:
    • 환경 변수 및 시크릿 관리 방식 변경
    • 볼륨 마운트에서 영구 볼륨으로 전환
    • GitSync 등의 DAG 배포 메커니즘 도입
  3. 일반적인 마이그레이션 단계:
    • 데이터베이스 백업
    • DAG 및 플러그인 마이그레이션
    • 연결 및 변수 설정 이전
    • 점진적인 전환을 위한 병렬 운영
    • 철저한 테스트 후 전환

Summary

  • Airflow 설치 방법은 로컬 환경 설치, Docker 기반 설치, Kubernetes 기반 설치로 크게 구분됩니다.
  • 로컬 환경 설치는 가장 간단하며 개발 및 학습 환경에 적합하지만, 확장성이 제한적이고 환경 의존성 문제가 발생할 수 있습니다.
  • Docker 기반 설치는 환경 독립적인 실행과 간편한 버전 관리가 가능하여 개발부터 중소규모 프로덕션까지 적합합니다.
  • Kubernetes 기반 설치는 높은 확장성과 고가용성을 제공하며 대규모 프로덕션 환경에 적합하지만, 설정이 복잡하고 Kubernetes 전문 지식이 필요합니다.
  • 환경에 따른 권장 Executor로는 개발 환경에는 SequentialExecutor, 소규모 프로덕션에는 LocalExecutor, 대규모 환경에는 CeleryExecutor 또는 KubernetesExecutor가 있습니다.
  • 설치 후 필수 구성사항으로는 보안 설정(Fernet 키, 인증), 네트워킹 설정, DAG 설정, 성능 최적화 설정, 로깅 설정 등이 있습니다.
  • 설치 방법 선택은 사용 시나리오, 리소스 제약 조건, 보안 요구사항, 통합 요구사항 등을 고려하여 결정해야 합니다.

 

728x90