CD #70
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 | |
| on: | |
| workflow_run: | |
| workflows: ["CI with Gradle"] | |
| types: [completed] | |
| branches: [main] | |
| permissions: | |
| contents: read | |
| env: | |
| IMAGE: ${{ secrets.DOCKER_USERNAME }}/tokbaro | |
| DOMAIN: tokbaro.com | |
| EMAIL: [email protected] | |
| jobs: | |
| deploy: | |
| name: Deploy to Server | |
| runs-on: ubuntu-latest | |
| steps: | |
| - name: Deploy to Server | |
| uses: appleboy/[email protected] | |
| with: | |
| host: ${{ secrets.SERVER_HOST }} | |
| username: ${{ secrets.SERVER_USER }} | |
| key: ${{ secrets.SERVER_SSH_KEY }} | |
| port: 22 | |
| script: | | |
| # 1. 서버에 있는 프로젝트 디렉토리로 이동합니다. | |
| cd /home/${{ secrets.SERVER_USER }}/BackEnd | |
| # 2. 이전 배포에서 실행 중이던 컨테이너가 있다면 모두 종료하여 포트 충돌을 방지합니다. | |
| echo "Stopping all running containers..." | |
| docker-compose down | |
| # 3. docker-compose.yml 같은 설정 파일 변경을 반영하기 위해 git pull을 실행합니다. | |
| echo "Pulling latest configuration files..." | |
| git pull origin main | |
| # 4. GitHub Secret으로부터 .env 파일을 생성합니다. | |
| echo "Creating .env file..." | |
| echo "${{ secrets.ENV_FILE }}" > .env | |
| echo "DOCKER_IMAGE=${{ env.IMAGE }}:latest" >> .env | |
| # 5. ci.yml에서 빌드한 최신 Docker 이미지를 pull 받습니다. | |
| echo "Pulling latest docker image from registry..." | |
| docker-compose pull | |
| # 6. 인증서 존재 여부 확인 및 발급/갱신 처리 | |
| CERT_DIR="/home/${{ secrets.SERVER_USER }}/BackEnd/nginx/letsencrypt/live/${{ env.DOMAIN }}" | |
| if [ -d "$CERT_DIR" ]; then | |
| # --- 인증서가 이미 있는 경우 --- | |
| echo "Certificate found. Starting services and renewing..." | |
| docker-compose up -d | |
| docker-compose exec certbot renew --quiet | |
| else | |
| # --- 인증서가 없는 경우 (최초 배포) --- | |
| echo "Certificate not found. Issuing a new one..." | |
| # --standalone 모드를 위해 -p 80:80 옵션으로 포트를 직접 열어줍니다. | |
| docker-compose run --rm -p 80:80 certbot certonly --standalone \ | |
| --email ${{ env.EMAIL }} -d ${{ env.DOMAIN }} \ | |
| --rsa-key-size 4096 --agree-tos --non-interactive | |
| # 인증서 발급 후 모든 서비스를 시작합니다. | |
| docker-compose up -d | |
| fi | |
| # 7. 불필요한 Docker 이미지를 정리합니다. | |
| echo "Pruning unused docker images..." | |
| docker image prune -f |