eletrotupi / tcc / .github/workflows/deploy.yml master
2.3 KB Raw
name: Deploy

on:
  push:
    branches:
      - master # goes for production now, will become staging later on
      - production
    paths:
      - 'api/**'
      - '.github/workflows/deploy.yml'

env:
  REGISTRY: ghcr.io
  IMAGE_NAME: ${{ github.repository }}

jobs:
  build-and-push:
    name: Build & push image
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write

    outputs:
      image_tag: ${{ steps.meta.outputs.version }}

    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Log in to GHCR
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GHCR_TOKEN }}

      - name: Docker metadata
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
          tags: |
            # main branch => tag "latest"
            type=raw,value=latest,enable=${{ github.ref == 'refs/heads/master' }}
            # production branch => tag "production"
            # type=raw,value=production,enable=${{ github.ref == 'refs/heads/production' }}
            # always tag with short SHA for traceability
            type=sha,prefix=,format=short

      - name: Build and push
        uses: docker/build-push-action@v5
        with:
          context: ./api
          file: ./api/Dockerfile.production
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}


  deploy-production:
    name: Deploy to production
    needs: build-and-push
    runs-on: ubuntu-latest
    if: github.ref == 'refs/heads/master'
    environment: production

    steps:
      - name: Deploy via SSH
        uses: appleboy/ssh-action@v1
        with:
          host: ${{ secrets.VPS_HOST }}
          username: ${{ secrets.VPS_USER }}
          key: ${{ secrets.VPS_SSH_KEY }}
          script: |
            set -e
            cd /srv/app/production

            docker pull ghcr.io/${{ github.repository }}:latest

            sed -i "s/^IMAGE_TAG=.*/IMAGE_TAG=latest/" .env

            docker compose up -d --no-deps --force-recreate api

            sleep 5
            # Dump the logs for a while
            docker compose logs --tail=50 api