Skip to content

Merge branch 'main' of https://github.com/llleeco/SWIntership_flask #9

Merge branch 'main' of https://github.com/llleeco/SWIntership_flask

Merge branch 'main' of https://github.com/llleeco/SWIntership_flask #9

Workflow file for this run

name: Deploy Python App with Docker
on:
push:
branches:
- main # main 브랜치에 푸시될 때 워크플로우 실행
jobs:
build-and-deploy:
runs-on: ubuntu-latest
steps:
# 1. 코드 체크아웃
- name: Checkout code
uses: actions/checkout@v4
# 2. Python 설치
- name: Set up Python 3.11
uses: actions/setup-python@v4
with:
python-version: '3.11'
# 3. Python 의존성 설치
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt
# 4. Docker Hub 로그인
- name: Log in to Docker Hub
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
# 5. Docker 이미지 빌드 및 푸시
- name: Build and Push Docker Image
uses: docker/build-push-action@v4
with:
context: .
push: true
tags: ${{ secrets.DOCKER_USERNAME }}/python-app:latest
# 6. EC2로 배포
- name: Deploy to EC2
env:
HOST: ${{ secrets.DEPLOY_HOST }} # EC2 퍼블릭 IP 또는 도메인
USER: ${{ secrets.DEPLOY_USER }} # EC2 SSH 사용자 이름
KEY: ${{ secrets.DEPLOY_KEY }} # SSH 개인 키
IMAGE_NAME: ${{ secrets.DOCKER_USERNAME }}/python-app:latest # Docker 이미지 이름
run: |
# SSH 설정
mkdir -p ~/.ssh
echo "$KEY" > deploy_key.pem
chmod 400 deploy_key.pem
echo "Adding $HOST to known_hosts"
if [ -z "$HOST" ]; then echo "HOST is not set"; exit 1; fi
ssh-keyscan -H $HOST >> ~/.ssh/known_hosts || exit 1
# EC2 접속 및 Docker 관련 작업 실행
ssh -i deploy_key.pem $USER@$HOST <<EOF
# Docker 설치 확인 및 설치
if ! [ -x "$(command -v docker)" ]; then
sudo yum update -y
sudo yum install -y docker
sudo service docker start
fi
# Docker 그룹에 사용자 추가 및 권한 적용
sudo usermod -aG docker $USER
newgrp docker || true
# 기존 컨테이너 중지 및 삭제
if docker ps -q --filter "name=flask-app"; then
docker stop python-app
docker rm python-app
fi
# 최신 이미지 가져오기 및 컨테이너 실행
docker pull $IMAGE_NAME
docker run -d --name flask-app -p 5000:5000 $IMAGE_NAME
EOF