modify workflow #3
This file contains 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: Deploy Flask App to EC2 using Docker | |
on: | |
push: | |
branches: | |
- main | |
jobs: | |
build: | |
runs-on: ubuntu-latest | |
steps: | |
# 코드 체크아웃 | |
- name: Checkout code | |
uses: actions/checkout@v2 | |
# Docker Buildx 설정 (다중 아키텍처 빌드를 위해 사용) | |
- name: Set up Docker Buildx | |
uses: docker/setup-buildx-action@v1 | |
# Docker Hub 로그인 | |
- name: Log in to Docker Hub | |
uses: docker/login-action@v2 | |
with: | |
username: ${{ secrets.DOCKER_USERNAME }} | |
password: ${{ secrets.DOCKER_PASSWORD }} | |
# Docker 이미지 빌드 및 푸시 | |
- name: Build and push Docker image | |
run: | | |
echo "Building Docker image..." | |
docker build -t ${{ secrets.DOCKER_USERNAME }}/flask-app:latest . | |
echo "Pushing Docker image to Docker Hub..." | |
docker push ${{ secrets.DOCKER_USERNAME }}/flask-app:latest | |
echo "Docker image push completed." | |
deploy: | |
runs-on: ubuntu-latest | |
needs: build # deploy는 build가 완료되어야 실행됨 | |
steps: | |
# 코드 체크아웃 | |
- name: Checkout code | |
uses: actions/checkout@v2 | |
# EC2 서버로 배포 | |
- name: Deploy to EC2 via SSH | |
uses: appleboy/ssh-action@v0.1.6 | |
with: | |
host: ${{ secrets.HOST }} | |
username: ubuntu | |
port: 22 | |
key: ${{ secrets.PRIVATE_KEY }} | |
script: | | |
echo "Logging in to Docker Hub on EC2..." | |
echo ${{ secrets.DOCKER_PASSWORD }} | docker login -u ${{ secrets.DOCKER_USERNAME }} --password-stdin | |
# 기존 컨테이너 중지 및 삭제 | |
echo "Stopping and removing old containers..." | |
docker stop flask-app || true | |
docker rm flask-app || true | |
# 불필요한 Docker 이미지 및 시스템 정리 | |
echo "Cleaning up old Docker resources..." | |
docker system prune -f --volumes | |
# 최신 Docker 이미지 가져오기 및 실행 | |
echo "Pulling and running new Docker image..." | |
docker pull ${{ secrets.DOCKER_USERNAME }}/flask-app:latest | |
docker run -d -p 5001:5001 --name flask-app ${{ secrets.DOCKER_USERNAME }}/flask-app:latest | |
# 서버 리소스 정리 | |
echo "Cleaning up system caches and logs..." | |
sudo rm -rf /var/cache/apt/archives/* | |
sudo journalctl --vacuum-time=1d |