Alembic은 데이터베이스 변경 이력을 코드로 관리할 수 있게 해주는 툴입니다.

  • DB 스키마(테이블 구조)가 바뀔 때마다,
    직접 SQL 쓰지 않고,
    Python 코드로 변경 내용을 버전 관리합니다.
    마치 Git이 코드 이력을 관리하듯, Alembic은 DB 구조 변경 이력을 관리합니다.
User 테이블에 is_active 컬럼을 추가했을 때:

Alembic으로 이렇게 처리:
alembic revision --autogenerate -m "Add is_active to User"
alembic upgrade head

자동으로 변경사항을 감지해서 마이그레이션 파일 생성
upgrade() / downgrade()로 쉽게 적용/되돌리기 가능

alembic upgrade <revision_id>
alembic upgrade 1234abcd5678
alembic downgrade -1
alembic downgrade <revision_id>

1. 설치

pip install alembic

 

2. 초기화 및 설정 파일

# alembic init {directory_name}
alembic init migration

# ./alembic.ini 파일
sqlalchemy.url = {driver}://{root}:{pwd}@{host}:{port}/{database}

# for 'autogenerate' support (migration/env.py 파일)
# 기본값은 None
# SQLAlchemy + Pydantic 하이브리드 조합인 경우 SQLModel.metadata로 수정
target_metadata = SQLModel.metadata

 

3. 모델 선언 (./models.py)

SQLAlchemy + Pydantic 하이브리드 조합

SQLAlchemy의 ORM 기능 + Pydantic의 타입 검증 기능을 한 클래스로 통합

import uuid

from pydantic import EmailStr
from sqlalchemy.ext.declarative import declarative_base
from sqlmodel import Field, Relationship, SQLModel

# Shared properties
class UserBase(SQLModel):
    email: EmailStr = Field(unique=True, index=True, max_length=255)
    is_active: bool = True
    is_superuser: bool = False
    full_name: str | None = Field(default=None, max_length=255)

# Database model, database table inferred from class name
class User(UserBase, table=True):
    # sqlmodel을 쓰고 있고, table=True가 붙어 있어 SQLAlchemy ORM 테이블로 인식
    # sqlmodel은 SQLAlchemy + Pydantic의 하이브리드 프레임워크입니다.
    id: uuid.UUID = Field(default_factory=uuid.uuid4, primary_key=True)
    hashed_password: str
    items: list["Item"] = Relationship(back_populates="owner", cascade_delete=True)

 

4. 모델 타겟 import (migration/env.py 파일 수정)

model을 import해야 대상 테이블을 생성할 수 있다.

import models  # 모델 import
또는 
from models import User, Item  # 특정 타겟 import

 

5. alembic commit

# 자동 생성
alembic revision --autogenerate -m "first commit"

# 수동 생성
alembic revision -m "first commit"

 

6. DB 적용

alembic upgrade head

 

'Dev > Python' 카테고리의 다른 글

SQLAlchemy 관계 종류  (0) 2025.04.17
SQLAlchemy DB 처리 방식  (0) 2025.04.17
Flask 프레임워크 thread  (0) 2024.04.12
파이썬 flask - redis - celery 구조  (0) 2024.03.14

출처: https://cafe.naver.com/kubeops/36

Object

Kubernetes Another-Class Object

 

Label / Selector / Naming (1)

Kubernetes Another-Class Labels, Selector, Naming

Label / Selector / Naming (2)

Kubernetes Another-Class Labels, Selector, Naming
 

 

 

※ 해당 설치는 Storage 연동을 따로 할당하지 않았기 때문에 VM이 재기동 될때, 기존 저장된 로그 데이터는 사라집니다.

[1] Github(k8s-1pro)에서 Prometheus(with Grafana), Loki-Stack yaml 다운로드

▶ [k8s-master] Console 접속 후 아래 명령 실행

 
[root@k8s-master ~]# yum -y install git

# 로컬 저장소 생성
git init monitoring
git config --global init.defaultBranch main
cd monitoring

# remote 추가 ([root@k8s-master monitoring]#)
git remote add -f origin https://github.com/k8s-1pro/install.git

# sparse checkout 설정
git config core.sparseCheckout true
echo "ground/k8s-1.27/prometheus-2.44.0" >> .git/info/sparse-checkout
echo "ground/k8s-1.27/loki-stack-2.6.1" >> .git/info/sparse-checkout

# 다운로드 
git pull origin main

[2] Prometheus(with Grafana) 설치

# 설치 ([root@k8s-master monitoring]#)
kubectl apply --server-side -f ground/k8s-1.27/prometheus-2.44.0/manifests/setup
kubectl wait --for condition=Established --all CustomResourceDefinition --namespace=monitoring
kubectl apply -f ground/k8s-1.27/prometheus-2.44.0/manifests

# 설치 확인 ([root@k8s-master]#) 
kubectl get pods -n monitoring

확인 결과

[3] Loki-Stack 설치

# 설치 ([root@k8s-master monitoring]#)
kubectl apply -f ground/k8s-1.27/loki-stack-2.6.1

# 설치 확인
kubectl get pods -n loki-stack

확인 결과

[4] Grafana 접속

▶ 접속 URL : http://192.168.56.30:30001

▶ 로그인 : id: admin, pw: admin

확인 결과

[5] Grafana에서 Loki-Stack 연결

▶ Connect data : Home > Connections > Connect data

▶ 검색에 [loki] 입력 후 항목 클릭

▶ URL에 내용 입력 : http://loki-stack.loki-stack:3100

▶ 하단 Save & Test


※ 설치를 삭제해야 할 경우, 아래 명령을 이용하면 됩니다.

- Prometheus(with Grafana), Loki-stack 삭제

▶ [k8s-master] Console 접속 후 아래 명령 실행

 
[root@k8s-master ~]# cd monitoring

# Prometheus 삭제
kubectl delete --ignore-not-found=true -f ground/k8s-1.27/prometheus-2.44.0/manifests -f ground/k8s-1.27/prometheus-2.44.0/manifests/setup

# Loki-stack 삭제
kubectl delete -f ground/k8s-1.27/loki-stack-2.6.1

+ Recent posts