Create a GitHub Actions pipeline for a monorepo with Angular and NestJS. It should use a…
- User
Create a GitHub Actions pipeline for a monorepo with Angular and NestJS. It should use a matrix strategy to test on Node 18, 20, and 22, with path filtering so backend builds only trigger for /backend changes. Also build and push a Docker image to ECR on passing tags.
Assistant
This is a great question about setting up a comprehensive CI/CD pipeline for a monorepo using GitHub Actions. Let me create a detailed workflow that includes:
- Matrix strategy for multiple Node versions
- Path filtering for backend changes
- Testing for both Angular frontend and NestJS backend
- Build and push Docker image to ECR on tags
- Proper separation of concerns
I'll create multiple workflow files or a comprehensive single workflow. Actually, it's better to have separate workflows for clarity:
- One for testing/building frontend
- One for testing/building backend
- One for Docker image push
Or I could make one comprehensive workflow. Let me provide both options - a comprehensive approach might be cleaner.
Actually, the best practice for a monorepo is typically:
- A base workflow that runs on all commits (tests for affected packages)
- A build/deploy workflow that runs on tags
Let me create a comprehensive solution with:
- Main CI workflow for testing on multiple Node versions with path filtering
- Separate workflows or jobs for frontend/backend
- Docker build and push workflow for tags
I'll provide:
- A main CI workflow with matrix and path filtering
- A Docker push workflow for tags
- Scripts to help with the setup
Let me structure this properly:
# .github/workflows/ci.yml name: CI on: push: branches: - main - develop paths: - 'frontend/**' - 'backend/**' - 'package.json' - 'pnpm-lock.yaml' - '.github/workflows/ci.yml' pull_request: branches: - main - develop jobs: # Frontend build and test frontend: if: contains(github.event.pull_request.files.*.filename, 'frontend/') || github.event_name == 'push' runs-on: ubuntu-latest strategy: matrix: node-version: [18, 20, 22] steps: # ... # Backend build and test backend: if: contains(github.event.pull_request.files.*.filename, 'backend/') || github.event_name == 'push' runs-on: ubuntu-latest strategy: matrix: node-version: [18, 20, 22] steps: # ... docker: needs: [frontend, backend] if: startsWith(github.ref, 'refs/tags/') runs-on: ubuntu-latestThe Docker job depends on both frontend and backend jobs passing, and only triggers when a tag is pushed to the repository.
GitHub Actions Pipeline for Monorepo (Angular + NestJS)
Here's a complete CI/CD solution with path filtering, matrix testing, and ECR deployment:
Project Structure
monorepo/ ├── frontend/ # Angular app │ ├── src/ │ ├── package.json │ └── ... ├── backend/ # NestJS app │ ├── src/ │ ├── package.json │ └── ... ├── docker/ │ ├── Dockerfile.backend │ └── Dockerfile.frontend ├── .github/workflows/ │ ├── ci.yml │ ├── docker.yml │ └── lint.yml └── package.json # Root monorepo config1. Main CI Workflow (
ci.yml)# .github/workflows/ci.yml name: CI on: push: branches: - main - develop pull_request: branches: - main - develop jobs: # Determine which packages changed changes: runs-on: ubuntu-latest outputs: frontend: ${{ steps.changes.outputs.frontend }} backend: ${{ steps.changes.outputs.backend }} steps: - uses: actions/checkout@v4 with: fetch-depth: 0 - name: Check for changes id: changes run: | if git diff --name-only HEAD~1 HEAD | grep -q '^frontend/'; then echo "frontend=true" >> $GITHUB_OUTPUT else echo "frontend=false" >> $GITHUB_OUTPUT fi if git diff --name-only HEAD~1 HEAD | grep -q '^backend/'; then echo "backend=true" >> $GITHUB_OUTPUT else echo "backend=false" >> $GITHUB_OUTPUT fi - name: Summary run: | echo "Frontend changed: ${{ steps.changes.outputs.frontend }}" echo "Backend changed: ${{ steps.changes.outputs.backend }}" # Frontend testing frontend-test: needs: changes if: needs.changes.outputs.frontend == 'true' || github.event_name == 'pull_request' runs-on: ubuntu-latest strategy: matrix: node-version: [18, 20, 22] fail-fast: false steps: - uses: actions/checkout@v4 - name: Setup Node.js ${{ matrix.node-version }} uses: actions/setup-node@v4 with: node-version: ${{ matrix.node-version }} cache: 'npm' cache-dependency-path: 'frontend/package-lock.json' - name: Install dependencies working-directory: ./frontend run: npm ci - name: Lint working-directory: ./frontend run: npm run lint continue-on-error: true - name: Build working-directory: ./frontend run: npm run build - name: Test working-directory: ./frontend run: npm run test:ci env: CI: true - name: Upload coverage if: matrix.node-version == '20' uses: codecov/codecov-action@v3 with: files: ./frontend/coverage/lcov.info flags: frontend name: frontend-coverage # Backend testing backend-test: needs: changes if: needs.changes.outputs.backend == 'true' || github.event_name == 'pull_request' runs-on: ubuntu-latest strategy: matrix: node-version: [18, 20, 22] fail-fast: false services: postgres: image: postgres:15 env: POSTGRES_DB: test_db POSTGRES_USER: test_user POSTGRES_PASSWORD: test_pass options: >- --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 ports: - 5432:5432 redis: image: redis:7 options: >- --health-cmd "redis-cli ping" --health-interval 10s --health-timeout 5s --health-retries 5 ports: - 6379:6379 steps: - uses: actions/checkout@v4 - name: Setup Node.js ${{ matrix.node-version }} uses: actions/setup-node@v4 with: node-version: ${{ matrix.node-version }} cache: 'npm' cache-dependency-path: 'backend/package-lock.json' - name: Install dependencies working-directory: ./backend run: npm ci - name: Lint working-directory: ./backend run: npm run lint continue-on-error: true - name: Build working-directory: ./backend run: npm run build - name: Test working-directory: ./backend run: npm run test:ci env: CI: true DATABASE_URL: postgres://test_user:test_pass@localhost:5432/test_db REDIS_URL: redis://localhost:6379 NODE_ENV: test - name: Test e2e working-directory: ./backend run: npm run test:e2e env: DATABASE_URL: postgres://test_user:test_pass@localhost:5432/test_db REDIS_URL: redis://localhost:6379 NODE_ENV: test continue-on-error: true - name: Upload coverage if: matrix.node-version == '20' uses: codecov/codecov-action@v3 with: files: ./backend/coverage/lcov.info flags: backend name: backend-coverage # Aggregated status check ci-status: runs-on: ubuntu-latest needs: [frontend-test, backend-test] if: always() steps: - name: Check CI status run: | if [[ "${{ needs.frontend-test.result }}" == "failure" || "${{ needs.backend-test.result }}" == "failure" ]]; then echo "CI Pipeline failed" exit 1 fi continue-on-error: true2. Docker Build & Push to ECR (
docker.yml)# .github/workflows/docker.yml name: Build and Push to ECR on: push: tags: - 'v*.*.*' - 'backend-v*.*.*' - 'frontend-v*.*.*' permissions: id-token: write contents: read jobs: build-backend: if: startsWith(github.ref, 'refs/tags/backend-v') || startsWith(github.ref, 'refs/tags/v') runs-on: ubuntu-latest strategy: matrix: node-version: [20] steps: - uses: actions/checkout@v4 - name: Configure AWS credentials uses: aws-actions/configure-aws-credentials@v4 with: role-to-assume: ${{ secrets.AWS_ROLE_TO_ASSUME }} aws-region: ${{ secrets.AWS_REGION }} - name: Login to Amazon ECR id: login-ecr uses: aws-actions/amazon-ecr-login@v2 - name: Setup Node.js for build uses: actions/setup-node@v4 with: node-version: ${{ matrix.node-version }} cache: 'npm' cache-dependency-path: 'backend/package-lock.json' - name: Extract version from tag id: version run: | TAG=${{ github.ref_name }} VERSION=${TAG#backend-v} VERSION=${VERSION#v} echo "version=$VERSION" >> $GITHUB_OUTPUT echo "tag_short=$(git rev-parse --short HEAD)" >> $GITHUB_OUTPUT - name: Build and push backend image uses: docker/build-push-action@v5 with: context: ./backend file: ./docker/Dockerfile.backend push: true tags: | ${{ steps.login-ecr.outputs.registry }}/${{ secrets.ECR_REPOSITORY_BACKEND }}:${{ steps.version.outputs.version }} ${{ steps.login-ecr.outputs.registry }}/${{ secrets.ECR_REPOSITORY_BACKEND }}:latest ${{ steps.login-ecr.outputs.registry }}/${{ secrets.ECR_REPOSITORY_BACKEND }}:${{ steps.version.outputs.tag_short }} cache-from: type=gha cache-to: type=gha,mode=max build-frontend: if: startsWith(github.ref, 'refs/tags/frontend-v') || startsWith(github.ref, 'refs/tags/v') runs-on: ubuntu-latest strategy: matrix: node-version: [20] steps: - uses: actions/checkout@v4 - name: Configure AWS credentials uses: aws-actions/configure-aws-credentials@v4 with: role-to-assume: ${{ secrets.AWS_ROLE_TO_ASSUME }} aws-region: ${{ secrets.AWS_REGION }} - name: Login to Amazon ECR id: login-ecr uses: aws-actions/amazon-ecr-login@v2 - name: Setup Node.js for build uses: actions/setup-node@v4 with: node-version: ${{ matrix.node-version }} cache: 'npm' cache-dependency-path: 'frontend/package-lock.json' - name: Build Angular app working-directory: ./frontend run: | npm ci npm run build -- --configuration production - name: Extract version from tag id: version run: | TAG=${{ github.ref_name }} VERSION=${TAG#frontend-v} VERSION=${VERSION#v} echo "version=$VERSION" >> $GITHUB_OUTPUT echo "tag_short=$(git rev-parse --short HEAD)" >> $GITHUB_OUTPUT - name: Build and push frontend image uses: docker/build-push-action@v5 with: context: ./frontend file: ./docker/Dockerfile.frontend push: true tags: | ${{ steps.login-ecr.outputs.registry }}/${{ secrets.ECR_REPOSITORY_FRONTEND }}:${{ steps.version.outputs.version }} ${{ steps.login-ecr.outputs.registry }}/${{ secrets.ECR_REPOSITORY_FRONTEND }}:latest ${{ steps.login-ecr.outputs.registry }}/${{ secrets.ECR_REPOSITORY_FRONTEND }}:${{ steps.version.outputs.tag_short }} cache-from: type=gha cache-to: type=gha,mode=max post-deploy: needs: [build-backend, build-frontend] if: always() && (needs.build-backend.result == 'success' || needs.build-frontend.result == 'success') runs-on: ubuntu-latest steps: - name: Notify deployment run: | echo "✅ Images pushed successfully" echo "Backend: ${{ secrets.ECR_REPOSITORY_BACKEND }}:${{ github.ref_name }}" echo "Frontend: ${{ secrets.ECR_REPOSITORY_FRONTEND }}:${{ github.ref_name }}"3. Dockerfile Examples
Backend Dockerfile
# docker/Dockerfile.backend FROM node:20-alpine AS builder WORKDIR /app # Copy backend source COPY backend/package*.json ./ RUN npm ci COPY backend/src ./src RUN npm run build # Production image FROM node:20-alpine WORKDIR /app RUN apk add --no-cache dumb-init COPY backend/package*.json ./ RUN npm ci --only=production && npm cache clean --force COPY --from=builder /app/dist ./dist ENV NODE_ENV=production ENV PORT=3000 EXPOSE 3000 ENTRYPOINT ["dumb-init", "--"] CMD ["node", "dist/main.js"] HEALTHCHECK --interval=10s --timeout=5s --start-period=5s --retries=3 \ CMD node -e "require('http').get('http://localhost:3000/health', (r) => {if (r.statusCode !== 200) throw new Error(r.statusCode)})"Frontend Dockerfile
# docker/Dockerfile.frontend FROM node:20-alpine AS builder WORKDIR /app COPY frontend/package*.json ./ RUN npm ci COPY frontend . . RUN npm run build -- --configuration production # Nginx production image FROM nginx:alpine COPY docker/nginx.conf /etc/nginx/nginx.conf COPY --from=builder /app/dist/frontend /usr/share/nginx/html EXPOSE 80 HEALTHCHECK --interval=10s --timeout=5s --start-period=5s --retries=3 \ CMD wget --no-verbose --tries=1 --spider http://localhost/health || exit 1Nginx Config
# docker/nginx.conf worker_processes auto; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; gzip on; gzip_vary on; gzip_proxied any; gzip_comp_level 6; gzip_types text/plain text/css text/xml text/javascript application/json application/javascript application/xml+rss application/rss+xml font/truetype font/opentype application/vnd.ms-fontobject image/svg+xml; server { listen 80; server_name _; root /usr/share/nginx/html; index index.html; # SPA routing location / { try_files $uri $uri/ /index.html; } # Static assets with cache location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ { expires 1y; add_header Cache-Control "public, immutable"; } # API proxy (optional) location /api/ { proxy_pass http://backend:3000/; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } # Health check endpoint location /health { access_log off; return 200 "healthy\n"; add_header Content-Type text/plain; } } }4. GitHub Secrets Configuration
Add these secrets to your GitHub repository:
AWS_ROLE_TO_ASSUME # IAM role ARN for OIDC AWS_REGION # e.g., us-east-1 ECR_REPOSITORY_BACKEND # e.g., my-app/backend ECR_REPOSITORY_FRONTEND # e.g., my-app/frontend5. AWS IAM Role for OIDC
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Federated": "arn:aws:iam::ACCOUNT_ID:oidc-provider/token.actions.githubusercontent.com" }, "Action": "sts:AssumeRoleWithWebIdentity", "Condition": { "StringEquals": { "token.actions.githubusercontent.com:aud": "sts.amazonaws.com" }, "StringLike": { "token.actions.githubusercontent.com:sub": "repo:YOUR_ORG/YOUR_REPO:ref:refs/tags/*" } } } ] }6. ECR Permissions Policy
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "ecr:GetDownloadUrlForLayer", "ecr:BatchGetImage", "ecr:BatchCheckLayerAvailability", "ecr:PutImage", "ecr:InitiateLayerUpload", "ecr:UploadLayerPart", "ecr:CompleteLayerUpload" ], "Resource": [ "arn:aws:ecr:us-east-1:ACCOUNT_ID:repository/my-app/*" ] }, { "Effect": "Allow", "Action": [ "ecr:GetAuthorizationToken" ], "Resource": "*" } ] }7. Package Scripts Examples
Backend
package.json{ "scripts": { "build": "nest build", "lint": "eslint \"{src,apps,libs,test}/**/*.ts\"", "test": "jest", "test:ci": "jest --ci --coverage --maxWorkers=2", "test:e2e": "jest --config ./test/jest-e2e.json", "start": "nest start", "start:dev": "nest start --watch", "start:debug": "nest start --debug --watch" }, "devDependencies": { "@nestjs/cli": "^10.0.0", "@types/jest": "^29.5.0", "jest": "^29.5.0", "ts-jest": "^29.1.0", "@types/node": "^20.0.0", "typescript": "^5.0.0" } }Frontend
package.json{ "scripts": { "build": "ng build", "lint": "ng lint", "test": "ng test", "test:ci": "ng test --watch=false --code-coverage --browsers=ChromeHeadless", "start": "ng serve", "start:open": "ng serve --open" }, "devDependencies": { "@angular/cli": "^17.0.0", "@angular/compiler-cli": "^17.0.0", "typescript": "~5.2.0", "karma": "~6.4.0", "karma-chrome-launcher": "~3.2.0", "karma-coverage": "~2.2.0", "karma-jasmine": "~5.1.0", "jasmine-core": "~4.6.0" } }8. Usage Examples
Trigger CI on all commits:
git push origin mainTrigger backend Docker build:
git tag backend-v1.0.0 git push origin backend-v1.0.0Trigger frontend Docker build:
git tag frontend-v1.0.0 git push origin frontend-v1.0.0Trigger both:
git tag v1.0.0 git push origin v1.0.09. Key Features
✅ Matrix Testing: Node 18, 20, 22
✅ Path Filtering: Backend only runs on/backendchanges
✅ Service Integration: PostgreSQL & Redis for backend tests
✅ Coverage Reports: codecov integration
✅ Docker Multi-stage Build: Optimized images
✅ ECR Push: AWS OIDC authentication (no secrets!)
✅ Conditional Jobs: Smart tag-based triggers
✅ Health Checks: Built-in Docker health endpoints
✅ Cache Optimization: GitHub Actions cache for dependenciesThis setup provides a production-ready CI/CD pipeline for your monorepo!
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.