Skip to content

Instantly share code, notes, and snippets.

@jonahgeek
Created March 26, 2024 11:16
Show Gist options
  • Save jonahgeek/10738b75d88c29e5f5b6d03e4e44e4f1 to your computer and use it in GitHub Desktop.
Save jonahgeek/10738b75d88c29e5f5b6d03e4e44e4f1 to your computer and use it in GitHub Desktop.
  1. Setting up GitHub Actions:

    • In your GitHub repository, navigate to the "Actions" tab and set up a new workflow.
    • Create a YAML file (e.g., .github/workflows/deploy.yml) to define your workflow.
  2. Configure Workflow:

    • Define triggers for the workflow. In your case, it could be triggered on push events to the master branch.
  3. Define Workflow Steps:

    • Use actions to SSH into your AWS EC2 instance. You can use an action like appleboy/ssh-action.
    • Within the SSH session, execute commands to pull the latest changes from the GitHub repository on your EC2 instance.
    • Run npm install to install any new dependencies.
    • Run npm run restart to restart your Node.js application using PM2.

Here's a basic example of what your workflow YAML file might look like:

name: Deploy to EC2

on:
  push:
    branches:
      - master

jobs:
  deploy:
    runs-on: ubuntu-latest

    steps:
    - name: Checkout Repository
      uses: actions/checkout@v2

    - name: SSH into EC2 Instance
      uses: appleboy/ssh-action@master
      with:
        host: ${{ secrets.EC2_HOST }}
        username: ${{ secrets.EC2_USERNAME }}
        key: ${{ secrets.SSH_PRIVATE_KEY }}
        script: |
          cd /path/to/your/app
          git pull origin master
          npm install
          npm run restart

Make sure to replace placeholders like /path/to/your/app, EC2_HOST, EC2_USERNAME, and SSH_PRIVATE_KEY with your actual values. Also, ensure that your EC2 instance is configured to accept SSH connections from GitHub Actions.

Finally, set up secrets in your GitHub repository for sensitive information like SSH private keys and EC2 credentials.

This setup will automatically deploy your Node.js application to your EC2 instance whenever changes are pushed to the master branch on GitHub.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment