加入CI/CD工作流 #5
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: Deploy to VPS | |
| on: | |
| push: | |
| branches: [ "main" ] | |
| env: | |
| REGISTRY: ghcr.io | |
| IMAGE_NAME: ${{ github.repository }} | |
| jobs: | |
| build_and_deploy: | |
| runs-on: ubuntu-latest | |
| permissions: | |
| contents: read | |
| packages: write | |
| steps: | |
| - name: Checkout repository | |
| uses: actions/checkout@v4 | |
| - name: Set up Python | |
| uses: actions/setup-python@v5 | |
| with: | |
| python-version: '3.11' | |
| - name: Basic Syntax Check | |
| run: | | |
| python -m py_compile server.py | |
| python -m py_compile grade_fetcher.py | |
| - name: Log in to the Container registry | |
| uses: docker/login-action@v3 | |
| with: | |
| registry: ${{ env.REGISTRY }} | |
| username: ${{ github.actor }} | |
| password: ${{ secrets.GITHUB_TOKEN }} | |
| - name: Extract metadata (tags, labels) for Docker | |
| id: meta | |
| uses: docker/metadata-action@v5 | |
| with: | |
| images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} | |
| tags: | | |
| type=raw,value=latest | |
| type=sha,format=long | |
| - name: Build and push Docker image | |
| uses: docker/build-push-action@v5 | |
| with: | |
| context: . | |
| push: true | |
| tags: ${{ steps.meta.outputs.tags }} | |
| labels: ${{ steps.meta.outputs.labels }} | |
| - name: Deploy to VPS via SSH | |
| uses: appleboy/ssh-action@master | |
| with: | |
| host: ${{ secrets.VPS_HOST }} | |
| username: ${{ secrets.VPS_USERNAME }} | |
| key: ${{ secrets.VPS_SSH_KEY }} | |
| port: ${{ secrets.VPS_PORT }} | |
| script: | | |
| cd ${{ secrets.VPS_APP_PATH }} | |
| # 拉取最新的 docker-compose.yml | |
| git pull origin main | |
| # 登入 GHCR (避免 Pull 失敗) | |
| echo "${{ secrets.GHCR_PAT }}" | docker login ghcr.io -u ${{ github.actor }} --password-stdin | |
| # 設定自動更新的 Image 名稱變數並以 Swarm 發布 | |
| export GHCR_IMAGE=${{ github.repository }} | |
| docker stack deploy --with-registry-auth -c docker-compose.yml school_grades |