[add]增加main分支自动部署文件,并增加pull request触发 #1
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 DRF Application | |
| on: | |
| push: | |
| branches: | |
| - main | |
| paths-ignore: | |
| - 'readme.md' | |
| pull_request: | |
| branches: | |
| - main | |
| paths-ignore: | |
| - 'readme.md' | |
| jobs: | |
| build_and_deploy: | |
| runs-on: ubuntu-latest | |
| steps: | |
| # 检出代码 | |
| - name: Checkout code | |
| uses: actions/checkout@v4 | |
| # 安装 docker-compose | |
| - name: Install Docker Compose | |
| run: | | |
| sudo apt-get update | |
| sudo apt-get install -y docker-compose | |
| # 构建 Docker 镜像 | |
| - name: Build Docker image | |
| run: docker-compose -f docker-compose-prod.yml build | |
| # 检查镜像是否能成功启动一个容器 | |
| - name: Run Docker container | |
| run: docker-compose -f docker-compose-prod.yml up -d | |
| # 检查容器状态 | |
| - name: Check container status | |
| id: container_status | |
| run: | | |
| CONTAINER_NAME=$(docker-compose -f docker-compose-prod.yml ps -q | head -n 1) | |
| if [ -z "$CONTAINER_NAME" ]; then | |
| echo "No containers found, failing the step." | |
| exit 1 | |
| fi | |
| STATUS=$(docker inspect -f '{{.State.Running}}' "$CONTAINER_NAME") | |
| if [ "$STATUS" != "true" ]; then | |
| echo "Container is not running, failing the step." | |
| exit 1 | |
| fi | |
| echo "Container is running successfully." | |
| # 推送镜像到 kworlds's Docker Hub | |
| - name: Push Docker image to Kworlds's Docker Hub | |
| if: success() | |
| run: docker push dockerhub.kworlds.cn/pure-drf-api:latest | |
| # 更新开发环境镜像并重启容器 | |
| - name: Deploy to remote server | |
| if: success() | |
| run: sshpass -p ${{ secrets.HOST_USER_PASSWORD_PROD }} ssh -o StrictHostKeyChecking=no ${{ vars.HOST_USER_NAME_PROD }}@${{ vars.HOST_PROD}} "cd ${{ vars.COMPOSE_FILE_PATH }} && docker-compose pull && docker-compose down && docker-compose up -d" |