DDevArchive
Đăng nhập

Dự án Giai đoạn 3: refactor, Docker, test, CI/CD, deploy

Đây là lúc dự án CRUD của bạn ở Giai đoạn 2 "trưởng thành": tách code theo SOLID, viết test, đóng Docker, thêm cache, tự deploy bằng CI/CD. Bạn sẽ có một dự án production-ready để tự hào giới thiệu.

Kế hoạch 5 bước

BướcViệc làmKết quả
1Refactor theo SOLID + tách service/repoCode test được
2Viết unit + integration testTest xanh cục bộ
3Docker + docker-composeChạy bằng một lệnh
4CI/CD với GitHub ActionsMỗi push tự test, tự deploy
5Redis cache cho danh sáchEndpoint nhanh hơn, README số liệu

Bước 3: Docker hoá

// File: compose.prod.yaml
services:
  web:
    build: .
    restart: always
    environment:
      NODE_ENV: production
      DATABASE_URL: postgres://app:${DB_PASSWORD}@db:5432/app
      REDIS_URL: redis://redis:6379
    depends_on: [db, redis]

  nginx:
    image: nginx:alpine
    ports: ["80:80", "443:443"]
    volumes:
      - ./nginx.conf:/etc/nginx/conf.d/default.conf:ro
      - certbot-www:/var/www/certbot
    depends_on: [web]

  db:
    image: postgres:16-alpine
    volumes: ["pgdata:/var/lib/postgresql/data"]

  redis:
    image: redis:7-alpine
    restart: always

volumes:
  pgdata:
  certbot-www:

Bước 4: pipeline đầy đủ

// File: pipeline.yml
name: Ship it
on:
  push: { branches: [main] }
  pull_request:

jobs:
  ci:
    runs-on: ubuntu-latest
    services: { postgres: { image: postgres:16-alpine,
      env: { POSTGRES_PASSWORD: postgres },
      ports: ["5432:5432"] } }
    steps:
      - uses: actions/checkout@v4
      - run: npm ci
      - run: npm run lint
      - run: npm test
        env: { DATABASE_URL: postgres://postgres:postgres@localhost:5432/postgres }

  deploy:
    needs: ci
    if: github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Deploy qua SSH
        uses: appleboy/ssh-action@v1
        with: {
          host: ${{ secrets.VPS_HOST }},
          key: ${{ secrets.VPS_KEY }},
          script: |
            cd /var/www/my-app
            git pull origin main
            docker compose up -d --build
            docker compose exec web node src/migrate.js
        }

Bước 5: đo trước và sau

Trước khi cache: ghi lại latency. Sau khi cache: đo lại và đưa số vào README. “Endpoint /api/jobs giảm từ 180ms xuống 12ms với Redis cache” là dòng mà nhà tuyển dụng sẽ đọc kỹ.

💡 Rollback cũng là một tính năng

Nếu bản deploy mới hỏng, bạn cần quay lại bản cũ nhanh. Git tag + docker tag phiên bản là cách rẻ và hiệu quả nhất: git tag v1.2.0 trước mỗi release.

❓ Thứ tự đúng để dựng pipeline an toàn?

  • Refactor code để test được
  • Viết test và Docker hoá
  • Thiết lập CI + CD với gate test
  • Ghi số liệu hiệu năng trước/sau vào README