Deploy Astro Blog #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 Astro Blog | |
| on: | |
| push: | |
| tags: | |
| - "v*" | |
| workflow_dispatch: | |
| env: | |
| REGISTRY: ghcr.io | |
| # Nombre del contenedor en el servidor | |
| CONTAINER_NAME: aidventure | |
| jobs: | |
| build-and-deploy: | |
| runs-on: ubuntu-latest | |
| permissions: | |
| contents: read | |
| packages: write | |
| steps: | |
| - name: Checkout repo | |
| uses: actions/checkout@v4 | |
| - name: Set up Docker Buildx | |
| uses: docker/setup-buildx-action@v3 | |
| - 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 }}/${{ github.repository }} | |
| tags: | | |
| type=ref,event=branch | |
| type=ref,event=tag | |
| type=raw,value=latest,enable=${{ github.ref == 'refs/heads/main' }} | |
| - 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 on server via SSH | |
| uses: appleboy/ssh-action@v1.0.3 | |
| env: | |
| GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} | |
| GITHUB_ACTOR: ${{ github.actor }} | |
| with: | |
| host: ${{ secrets.SERVER_HOST }} | |
| username: ${{ secrets.SERVER_USER }} | |
| key: ${{ secrets.SERVER_SSH_KEY }} | |
| envs: CONTAINER_NAME,REGISTRY,GITHUB_TOKEN,GITHUB_ACTOR | |
| script: | | |
| # 1. Login en GHCR en el servidor remoto | |
| echo $GITHUB_TOKEN | docker login $REGISTRY -u $GITHUB_ACTOR --password-stdin | |
| # Convertir repo a minúsculas para docker | |
| REPO_LOWER=$(echo "${{ github.repository }}" | tr '[:upper:]' '[:lower:]') | |
| TAG_NAME="${{ github.ref_name }}" | |
| FULL_IMAGE="$REGISTRY/$REPO_LOWER:$TAG_NAME" | |
| echo "Deploying image: $FULL_IMAGE as container: $CONTAINER_NAME" | |
| # Descargar imagen | |
| docker pull $FULL_IMAGE | |
| # Detener el contenedor (sea la versión vieja o nueva, al llamarse igual simplificamos) | |
| docker stop $CONTAINER_NAME || true | |
| docker rm $CONTAINER_NAME || true | |
| # Correr el nuevo contenedor en el puerto 8321 | |
| docker run -d \ | |
| --name $CONTAINER_NAME \ | |
| --restart unless-stopped \ | |
| -p 8321:80 \ | |
| $FULL_IMAGE | |
| # Limpieza opcional | |
| docker image prune -f | |
| # Logout por seguridad | |
| docker logout $REGISTRY |