다양한 환경에서 Alembic 마이그레이션 관리
카테고리
프로그래밍/소프트웨어 개발
서브카테고리
DevOps
대상자
- 소프트웨어 개발자 및 DevOps 엔지니어
- 중간 이상의 난이도 (Alembic 기초 지식 필요)
핵심 요약
- Alembic.ini 파일을 사용해
local
,staging
,production
환경별 설정 분리 (sqlalchemy.url
,script_location
등) -n
플래그로 환경 구분하여 마이그레이션 폴더(예:alembic/local
,alembic/staging
) 생성env.py
파일에서 SQLAlchemy 메타데이터 로드 여부가 마이그레이션 자동 생성에 직접 영향
섹션별 세부 요약
1. 환경 설정 및 alembic.ini 구성
alembic.ini
파일에[local]
,[staging]
,[production]
섹션 추가- 각 환경별
sqlalchemy.url
과script_location
을 구분하여 설정 (예:script_location = alembic/local
) prepend_sys_path
와version_path_separator
설정으로 경로 관리 최적화
2. 환경별 마이그레이션 폴더 생성
alembic init alembic/local
명령어로local
환경 폴더 생성alembic -n staging init alembic/staging
명령어로staging
환경 폴더 생성- 각 환경별
env.py
와versions/
폴더가 독립적으로 생성됨
3. 마이그레이션 스크립트 생성 및 적용
alembic revision --autogenerate -m "add users table"
명령어로 자동 생성alembic -n staging revision --autogenerate -m "add users table"
명령어로staging
환경에만 적용alembic upgrade head
명령어로 각 환경의 마이그레이션 적용 (예:alembic -n production upgrade head
)
4. 환경 상태 확인 및 주의사항
alembic current
명령어로 현재 마이그레이션 버전 확인env.py
파일에서 SQLAlchemy 모델 메타데이터 로드 여부가 자동 생성에 영향 (미로드 시 오류 발생)-n
플래그 사용 필수 (환경 혼동 방지)
결론
- 환경별
alembic.ini
설정과-n
플래그 사용으로 환경 분리 local
및staging
환경에서 테스트 후production
에 적용env.py
에서 SQLAlchemy 메타데이터 로드를 반드시 확인 (예:from myapp.models import Base
)