# 多环境部署示例 name: Multi-Environment Deploy on: push: branches: [ main ] tags: [ 'v*' ] jobs: build: runs-on: ubuntu-latest outputs: image-tag: ${{ steps.meta.outputs.tags }} steps: - name: 检出代码 uses: actions/checkout@v4 - name: 配置构建环境 uses: actions/xgj/setup-env@v1 with: docker-password: ${{ secrets.DOCKER_PASSWORD }} cache-key: 'multi-env-build' - name: 生成镜像标签 id: meta run: | if [[ $GITHUB_REF == refs/tags/* ]]; then VERSION=${GITHUB_REF#refs/tags/} else VERSION=${GITHUB_SHA::7} fi IMAGE_TAG="docker-registry.bjxgj.com/my-app:$VERSION" echo "tags=$IMAGE_TAG" >> $GITHUB_OUTPUT echo "version=$VERSION" >> $GITHUB_OUTPUT - name: 构建并推送 run: | docker build -t ${{ steps.meta.outputs.tags }} . docker push ${{ steps.meta.outputs.tags }} deploy-dev: needs: build runs-on: ubuntu-latest if: github.ref == 'refs/heads/main' environment: development steps: - name: 检出代码 uses: actions/checkout@v4 - name: 配置开发环境 uses: actions/xgj/setup-env@v1 with: docker-password: ${{ secrets.DOCKER_PASSWORD }} kube-config: ${{ secrets.KUBE_CONFIG_DEV }} cache-key: 'deploy-dev' - name: 部署到开发环境 run: | sed -i "s|{{IMAGE_TAG}}|${{ needs.build.outputs.image-tag }}|g" k8s/dev/deployment.yaml kubectl apply -f k8s/dev/ -n development kubectl rollout status deployment/my-app -n development deploy-staging: needs: build runs-on: ubuntu-latest if: startsWith(github.ref, 'refs/tags/') environment: staging steps: - name: 检出代码 uses: actions/checkout@v4 - name: 配置预发布环境 uses: actions/xgj/setup-env@v1 with: docker-password: ${{ secrets.DOCKER_PASSWORD }} kube-config: ${{ secrets.KUBE_CONFIG_STAGING }} cache-key: 'deploy-staging' - name: 部署到预发布环境 run: | sed -i "s|{{IMAGE_TAG}}|${{ needs.build.outputs.image-tag }}|g" k8s/staging/deployment.yaml kubectl apply -f k8s/staging/ -n staging kubectl rollout status deployment/my-app -n staging deploy-production: needs: [build, deploy-staging] runs-on: ubuntu-latest if: startsWith(github.ref, 'refs/tags/') environment: production steps: - name: 检出代码 uses: actions/checkout@v4 - name: 配置生产环境 uses: actions/xgj/setup-env@v1 with: docker-password: ${{ secrets.DOCKER_PASSWORD }} kube-config: ${{ secrets.KUBE_CONFIG_PROD }} cache-key: 'deploy-production' use-aliyun-mirror: 'false' # 生产环境使用官方源 - name: 部署到生产环境 run: | sed -i "s|{{IMAGE_TAG}}|${{ needs.build.outputs.image-tag }}|g" k8s/prod/deployment.yaml kubectl apply -f k8s/prod/ -n production kubectl rollout status deployment/my-app -n production - name: 健康检查 run: | kubectl get pods -n production -l app=my-app # 可以添加更多健康检查逻辑