Skip to content

initial commit

initial commit #1

Workflow file for this run

name: Deploy Node.js to EC2
on:
push:
branches: [ "main" ] # change to your deploy branch if needed
workflow_dispatch:
env:
APP_NAME: node-app
NODE_VERSION: "20"
jobs:
deploy:
runs-on: [ self-hosted, node ] # target your EC2 runner labels if any
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: ""
- name: Install dependencies
run: npm install
# Install PM2 globally and capture its absolute path
- name: Install PM2 globally (capture absolute path)
id: pm2
run: |
# Install PM2 globally if missing
if ! command -v pm2 >/dev/null 2>&1; then
sudo npm install -g pm2
fi
# Get absolute path to PM2 and expose to later steps
PM2_BIN="$(npm prefix -g)/bin/pm2"
echo "pm2_bin=${PM2_BIN}" >> "$GITHUB_OUTPUT"
# Sanity check
"${PM2_BIN}" -v
- name: Start or restart app with PM2 (name required)
run: |
PM2_BIN=""
APP_NAME=""
if [ -z "$APP_NAME" ]; then
echo "ERROR: APP_NAME is empty. Set env.APP_NAME in the workflow." >&2
exit 1
fi
# Prefer ecosystem.config.js if present (production-friendly)
if [ -f ecosystem.config.js ]; then
if "${PM2_BIN}" describe "$APP_NAME" >/dev/null 2>&1; then
echo "Process $APP_NAME exists, restarting..."
"${PM2_BIN}" restart "$APP_NAME" --update-env
else
echo "Process $APP_NAME not found, starting from ecosystem.config.js..."
"${PM2_BIN}" start ecosystem.config.js --name "$APP_NAME" --env production
fi
else
# Fallback to npm start (ensure package.json has "start")
if "${PM2_BIN}" describe "$APP_NAME" >/dev/null 2>&1; then
echo "Process $APP_NAME exists, restarting..."
"${PM2_BIN}" restart "$APP_NAME" --update-env
else
echo "Process $APP_NAME not found, starting with npm start..."
"${PM2_BIN}" start "npm start" --name "$APP_NAME"
fi
fi
# Persist PM2 across reboots
sudo env PATH="$PATH" "${PM2_BIN}" startup systemd -u "$USER" --hp "$HOME" || true
"${PM2_BIN}" save
- name: Show PM2 status
run: |
PM2_BIN=""
"${PM2_BIN}" status