DEV Community

Naved Hussain
Naved Hussain

Posted on

πŸš€ Deploy a Node.js App to AWS EC2 with GitHub Actions in 15 Minutes

πŸš€ Deploy a Node.js App to AWS EC2 with GitHub Actions in 15 Minutes

CI/CD pipelines make development faster, safer, and more consistent. In this guide, we’ll automate the deployment of a Node.js app to an EC2 instance using GitHub Actions.

🧱 Prerequisites

  • Basic AWS account with EC2 access
  • A running EC2 instance (Amazon Linux 2 or Ubuntu)
  • SSH key pair configured
  • A simple Node.js app in a GitHub repo
  • GitHub Actions enabled in your repo

☁️ Step 1: Launch and Configure EC2

  • Go to EC2 β†’ Launch instance
  • Use Amazon Linux 2 or Ubuntu
  • Open port 22 (SSH) and port 3000 (app port) in the security group
  • SSH into the server:
    ssh -i your-key.pem ec2-user@<EC2_PUBLIC_IP>

  • Install Node.js:
    sudo yum update -y
    curl -sL https://rpm.nodesource.com/setup_16.x | sudo bash -
    sudo yum install -y nodejs git

πŸ”§ Step 2: Set Up the Node.js App

SSH into the server and clone your repo:
git clone https://github.com/<your-username>/<your-repo>.git
cd <your-repo>
npm install
node app.js # or your startup script

Ensure it runs on port 3000.

πŸ” Step 3: Configure SSH Key as a GitHub Secret

  1. Convert your private key to a single line:
    cat your-key.pem | base64

  2. Go to your GitHub repo β†’ Settings β†’ Secrets and variables β†’ Actions β†’ Add new secret:

  • EC2_KEY β†’ Paste base64 key
  • EC2_USER β†’ ec2-user
  • EC2_HOST β†’

πŸ§ͺ Step 4: GitHub Actions Workflow

Create a file in your repo: .github/workflows/deploy.yml

name: Deploy to EC2

on:
  push:
    branches:
      - main

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v3

      - name: Decode private key
        run: |
          echo "${{ secrets.EC2_KEY }}" | base64 -d > key.pem
          chmod 600 key.pem

      - name: Deploy over SSH
        run: |
          ssh -o StrictHostKeyChecking=no -i key.pem ${{ secrets.EC2_USER }}@${{ secrets.EC2_HOST }} << EOF
            cd <your-app-folder>
            git pull origin main
            npm install
            pkill node || true
            nohup node app.js > app.log 2>&1 &
          EOF
Enter fullscreen mode Exit fullscreen mode

βœ… Done!
Now, every time you git push, GitHub Actions will automatically deploy your app to your EC2 instance.

πŸ“Œ Final Tips

  • Replace node app.js with pm2 start if using process managers.
  • Secure your instance! Rotate keys, use .env files, etc.

Let me know in the comments if you'd like a version with PM2, Docker, or Elastic Beanstalk.

🟒 Tags:

aws #ec2 #githubactions #devops #cicd

Top comments (0)