Step-by-Step Guide to Setting Up CI/CD with GitHub Actions
January 16, 2025Why Use GitHub Actions for CI/CD?
- Ease of Integration: Built directly into GitHub, eliminating the need for third-party CI/CD tools.
- Extensive Marketplace: Leverage prebuilt actions for testing, building, and deploying.
- Custom Workflows: Define tailored workflows to suit your project’s needs.
- Cost-Effective: Free for public repositories and reasonable for private repositories.
Prerequisites
Before starting, ensure you have:
- A GitHub repository (public or private).
- Basic knowledge of YAML syntax.
- Access to a cloud platform (e.g., AWS, Azure, or GCP) or server for deployments.
Step 1: Create a GitHub Repository
- Log in to GitHub and create a new repository.
- Clone the repository to your local machine and add your project files.
git clone https://github.com/<your-username>/<your-repo>.git
Step 2: Set Up a Workflow File
- Inside your project directory, create a folder named .github/workflows.
- Add a new YAML file, e.g., ci-cd.yml.
mkdir -p .github/workflows
touch .github/workflows/ci-cd.yml
## Step 3: Define Your Workflow
Open the ci-cd.yml file and add the following configuration:
```yaml
name: CI/CD Pipeline
on:
push:
branches:
- main
pull_request:
branches:
- main
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout Code
uses: actions/checkout@v3
- name: Set Up Node.js
uses: actions/setup-node@v3
with:
node-version: 16
- name: Install Dependencies
run: npm install
- name: Run Tests
run: npm test
deploy:
needs: build
runs-on: ubuntu-latest
steps:
- name: Deploy to Server
run: |
ssh user@your-server 'bash -s' < ./deploy.sh
Step 4: Add Secrets for Deployment
- Go to your repository settings in GitHub.
- Navigate to Secrets and variables > Actions.
- Add secrets for sensitive information (e.g., SSH keys, API tokens).
Step 5: Test Your Pipeline
- Push your code to the main branch:
git add .
git commit -m "Set up CI/CD pipeline"
git push origin main
- Check the Actions tab in GitHub to monitor the pipeline’s progress.
Step 6: Automate Deployment (Optional)
To automate deployment:
- Write a deploy.sh script with deployment commands (e.g., copying files, restarting services).
- Ensure the script is executable:
chmod +x deploy.sh
Best Practices for GitHub Actions
1. Use Cache:
- Speed up builds by caching dependencies using actions/cache.
- name: Cache Node Modules
uses: actions/cache@v3
with:
path: node_modules
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node-
2. Secure Secrets:
- Use GitHub Secrets to store sensitive credentials securely.
3. Monitor Workflows:
- Enable notifications for workflow failures to address issues quickly.