This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| name: CD with FastAPI | |
| on: | |
| push: | |
| branches: [ "main" ] | |
| pull_request: | |
| branches: [ "main" ] | |
| permissions: | |
| contents: read | |
| jobs: | |
| build: | |
| runs-on: ubuntu-latest | |
| steps: | |
| - uses: actions/checkout@v3 | |
| # Python 3.11.7 환경 설정 | |
| - name: Set up Python 3.11.7 | |
| uses: actions/setup-python@v4 | |
| with: | |
| python-version: "3.11.7" | |
| # 의존성 캐싱 (빌드 속도 최적화) | |
| - name: Cache dependencies | |
| uses: actions/cache@v3 | |
| with: | |
| path: ~/.cache/pip | |
| key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements.txt') }} | |
| restore-keys: | | |
| ${{ runner.os }}-pip- | |
| # 필요한 패키지 설치 | |
| - name: Install dependencies | |
| run: | | |
| python -m pip install --upgrade pip | |
| pip install -r requirements.txt | |
| # Docker 이미지 빌드 & Docker Hub에 푸시 | |
| - name: Docker build & push | |
| run: | | |
| echo "${{ secrets.DOCKER_PASSWORD }}" | docker login -u "${{ secrets.DOCKER_USERNAME }}" --password-stdin | |
| docker build -t ${{ secrets.DOCKER_REPO }} . | |
| docker push ${{ secrets.DOCKER_REPO }} | |
| # 서버에 배포 | |
| - name: Deploy to server | |
| uses: appleboy/ssh-action@master | |
| with: | |
| host: ${{ secrets.EC2_HOST }} | |
| username: ubuntu | |
| key: ${{ secrets.EC2_SSH_PORT }} | |
| script: | | |
| cd /home/ubuntu/app # 프로젝트 디렉토리로 이동 | |
| # 기존 컨테이너 종료 및 삭제 (주의!) | |
| RUNNING_CONTAINER=$(sudo docker ps -q) | |
| if [ ! -z "$RUNNING_CONTAINER" ]; then | |
| sudo docker stop $RUNNING_CONTAINER | |
| sudo docker rm $RUNNING_CONTAINER | |
| fi | |
| # 최신 이미지 가져오기 | |
| sudo docker pull ${{ secrets.DOCKER_REPO }} | |
| # Docker Compose 실행 | |
| sudo docker-compose up -d --force-recreate | |
| # 불필요한 이미지 정리 | |
| sudo docker image prune -f |