Daily Work Log

What I Built Today: Staging Pipeline Upgrades and a Faster Deploy Loop

By Nikhil Bhangale··8 min read

Notes from today's sprint: pre-flight disk and inode gates, atomic release directories, local loopback smoke tests, OPcache reload fixes, and 10-second symlink rollbacks that cut staging deploys from 7 minutes to 2.5 minutes.

What I Built Today: Staging Pipeline Upgrades and a Faster Deploy Loop

At 4:40 PM yesterday, a client's backend developer merged a small checkout fix to the staging branch. Two minutes later, three frontend engineers were blocked on Slack because staging was returning HTTP 500 errors. When I SSHed into the staging VM, the culprit was immediately obvious: the CI runner had connected over SSH, started git pull and npm ci directly inside the live /var/www/app directory, hit 100% inode exhaustion on /dev/vda1 halfway through unpacking node_modules, and died leaving a half-compiled tree serving live requests.

Today's sprint was pure infrastructure plumbing: tearing out that fragile flat bash script and replacing it with a deterministic, atomic staging pipeline. It is the kind of afternoon engineering work nobody notices when it succeeds, yet it saves hours of lost developer momentum every single month.

Why Flat git pull Deploy Scripts Break Mid-Build

Many small teams treat staging like a disposable sandbox and wire GitHub Actions to execute ssh deploy@staging "cd /var/www/app && git pull && composer install && npm run build". That shortcut fails in three predictable ways:

  1. In-place mutation during active requests: While composer install or Vite is rewriting files on disk, PHP-FPM and Node workers read mismatched autoloader maps and missing asset chunks, producing transient fatal errors that QA mistakes for application bugs.
  2. Dirty working trees and orphaned artifacts: One quick diagnostic edit or generated cache file on the server makes git pull abort unless someone forces git reset --hard, wiping useful debugging state.
  3. Zero fast recovery when builds fail: If a migration check fails or npm run build runs out of memory six minutes into the job, the previous working release has already been overwritten in place.

Even on staging, deployments should follow the same atomic symlink model I use for zero-downtime Laravel and Node.js production deployments, streamlined so every feature merge lands quickly and predictably.

1. Pre-Flight Health Gate (pre-deploy.sh)

Before transferring artifacts or touching application state, the pipeline now runs a strict pre-deploy.sh verification script on the target VM. Checking free gigabytes alone is a classic trap on build-heavy staging hosts; hundreds of thousands of tiny files inside leftover vendor/ and node_modules/ directories routinely exhaust ext4 inodes while df -h still reports 30% free disk space.

bash · terminal
#!/usr/bin/env bash
set -euo pipefail

echo "[pre-flight] Verifying staging host readiness..."

# 1. Check block storage usage on /var/www
DISK_PCT=$(df -P /var/www | awk 'NR==2 {gsub("%","",$5); print $5}')
if [ "$DISK_PCT" -gt 85 ]; then
  echo "ERROR: Block storage on /var/www is at ${DISK_PCT}% (limit 85%). Aborting." >&2
  exit 1
fi

# 2. Check filesystem inode exhaustion (critical for Composer and npm trees)
INODE_PCT=$(df -iP /var/www | awk 'NR==2 {gsub("%","",$5); print $5}')
if [ "$INODE_PCT" -gt 80 ]; then
  echo "ERROR: Inode usage on /var/www is at ${INODE_PCT}% (limit 80%). Aborting." >&2
  exit 1
fi

# 3. Confirm Nginx is running and configuration syntax is clean
if ! systemctl is-active --quiet nginx; then
  echo "ERROR: nginx.service is not active. Aborting deploy." >&2
  exit 1
fi
sudo /usr/sbin/nginx -t >/dev/null 2>&1 || {
  echo "ERROR: nginx configuration test (nginx -t) failed. Aborting." >&2
  exit 1
}

# 4. Verify database reachability before unpacking a new release
mysql --defaults-extra-file=/var/www/shared/.my-health.cnf -e "SELECT 1;" >/dev/null 2>&1 || {
  echo "ERROR: Staging MariaDB connectivity check failed. Aborting." >&2
  exit 1
}

echo "[pre-flight] Passed (disk: ${DISK_PCT}%, inodes: ${INODE_PCT}%)."

Moving frontend and Composer builds onto the GitHub Actions runner (backed by dependency caching) and running pre-deploy.sh in parallel with artifact packaging cut over four minutes off the deploy loop right away.

2. Atomic /var/www/releases Layout and Shared State

Instead of mutating a single folder, the staging server now uses a strict immutable release layout under /var/www:

  • /var/www/releases/<timestamp>: Self-contained application code and compiled assets for one specific build, such as 20261114153012.
  • /var/www/shared/.env: Persistent staging environment secrets managed outside Git.
  • /var/www/shared/storage: Persistent user uploads, framework logs, and local cache directories.
  • /var/www/current: Symbolic link pointing to the active release folder served by Nginx.

During deployment, CI uploads a compressed build tarball, extracts it into a fresh timestamped directory, and links shared state while the previous release continues serving live staging requests undisturbed:

bash · terminal
RELEASE_ID="$(date -u +%Y%m%d%H%M%S)"
RELEASE_DIR="/var/www/releases/${RELEASE_ID}"
SHARED_DIR="/var/www/shared"

mkdir -p "$RELEASE_DIR"
tar -xzf "/tmp/build-${RELEASE_ID}.tar.gz" -C "$RELEASE_DIR"
rm -f "/tmp/build-${RELEASE_ID}.tar.gz"

# Wire persistent environment file and writable storage directory
ln -sfn "${SHARED_DIR}/.env" "${RELEASE_DIR}/.env"
rm -rf "${RELEASE_DIR}/storage"
ln -sfn "${SHARED_DIR}/storage" "${RELEASE_DIR}/storage"

# Warm framework caches inside the isolated candidate directory
php "${RELEASE_DIR}/artisan" config:cache
php "${RELEASE_DIR}/artisan" route:cache
php "${RELEASE_DIR}/artisan" migrate --force

3. Local 127.0.0.1 Smoke Test Before Flipping /var/www/current

Previously, a missing staging .env variable or broken service provider only surfaced when QA clicked around in the browser. To catch boot failures before switching public traffic, I added an internal Nginx vhost bound strictly to 127.0.0.1:8081 with its document root pointed at /var/www/staging-canary:

bash · terminal
# Point internal loopback canary symlink at the candidate build
ln -sfn "$RELEASE_DIR" /var/www/staging-canary
sudo systemctl reload php8.3-fpm

# Probe loopback health endpoint that verifies DB, Redis, and route boot
HTTP_STATUS=$(curl --silent --show-error \
  --max-time 5 \
  --output /tmp/canary-health.json \
  --write-out "%{http_code}" \
  -H "Host: staging-internal.local" \
  http://127.0.0.1:8081/api/healthz || true)

if [ "$HTTP_STATUS" != "200" ]; then
  echo "ERROR: Loopback smoke check returned HTTP ${HTTP_STATUS}. Aborting cutover." >&2
  cat /tmp/canary-health.json >&2 || true
  rm -rf "$RELEASE_DIR"
  exit 1
fi

# Atomic symlink swap for live staging traffic
ln -sfn "$RELEASE_DIR" /var/www/current

Under Linux, ln -sfn creates a temporary link and performs an atomic rename() over /var/www/current, so concurrent HTTP requests never encounter a missing document root.

4. PHP-FPM OPcache and PM2 Reload Gotchas

Swapping a symlink takes microseconds, yet two runtime caching behaviors will quietly serve old code if you ignore them:

  • PHP realpath_cache and Zend OPcache: PHP caches resolved symlink paths (realpath_cache_ttl = 120 seconds by default), and OPcache keys compiled bytecode by file path. If your Nginx FastCGI config passes $document_root, PHP-FPM workers keep executing the previous release until the cache expires. Set fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name; and fastcgi_param DOCUMENT_ROOT $realpath_root; inside Nginx, then run sudo systemctl reload php8.3-fpm immediately after flipping /var/www/current.
  • PM2 working directory resolution: For the Node.js SSR and queue daemon paired with this app, running a naive pm2 restart can retain the old resolved directory path. Executing pm2 reload ecosystem.config.cjs --update-env gracefully cycles cluster workers from the new symlink target with zero dropped sockets.

At the end of every successful run, the deploy script prunes older builds while keeping the five most recent directories (ls -1dt /var/www/releases/* | tail -n +6 | xargs -r rm -rf). That keeps disk and inode usage flat and powers /usr/local/bin/staging-rollback, a helper that lets any developer revert a broken merge in under 10 seconds:

bash · terminal
#!/usr/bin/env bash
set -euo pipefail

PREV_RELEASE=$(ls -1dt /var/www/releases/* | sed -n '2p')
if [ -z "$PREV_RELEASE" ]; then
  echo "ERROR: No previous release found in /var/www/releases." >&2
  exit 1
fi

ln -sfn "$PREV_RELEASE" /var/www/current
sudo systemctl reload php8.3-fpm
pm2 reload ecosystem.config.cjs --update-env

curl -fsS -X POST "$SLACK_WEBHOOK_URL" \
  -H "Content-Type: application/json" \
  -d "{\"text\":\"Staging rolled back to $(basename "$PREV_RELEASE") by $(whoami).\"}" >/dev/null

echo "Rollback complete: /var/www/current -> ${PREV_RELEASE}"

Every CI run also posts a compact webhook payload to the engineering Slack channel listing the branch, commit SHA, author, deploy duration, and smoke-test result.

Pipeline CapabilityLegacy Flat SSH ScriptUpgraded Atomic Staging Pipeline
End-to-end deploy time~7 min 10 sec (in-place VM build)2 min 28 sec (cached CI build + tarball)
Disk and inode protectionNone (crashed mid-unpack)pre-deploy.sh halts above 85% disk or 80% inodes
Failed build blast radiusLeaves /var/www/app brokenCandidate folder discarded before symlink swap
Bytecode & worker freshnessStale OPcache files up to 120s$realpath_root + graceful FPM and PM2 reload
Rollback recovery time7+ min manual Git revert and rebuildUnder 10 seconds via staging-rollback

What Improved and What Is Next

Four consecutive staging deploys shipped cleanly before the end of the workday, average pipeline wall time dropped from 7 minutes to 2.5 minutes, and QA stopped losing half an hour whenever a frontend build failed. As I shared in lessons from a late-night incident response, investing an afternoon in deterministic deployment guardrails beats debugging avoidable outages every time. Tomorrow's follow-up is hooking up a 60-second log-rate alert on Nginx 5xx responses so post-deploy runtime regressions page Slack automatically.

#devops#ci-cd#deploy#ansible#git
← Back to all posts

Related Articles

Browse all articles →
Daily Work Log13 min read

SolusVM 2 Migration Guide: Fix Agents, License & WHMCS

Today's hands-on work log: migrating a live SolusVM 2 Management Server to a new VPS without touching running Compute Resource VMs, fixing the license IP lock, debugging RabbitMQ and solus-agent start/stop/create failures, and restoring WHMCS automation.

Read article →
Daily Work Log11 min read

Zero-Downtime Node.js & Firebase to cPanel Migration

A real client migration log: escaping steep hosting renewal charges when a non-technical bridal jewelry store owner bought a WordPress cPanel plan for a live Node.js and Firebase ecommerce store, and how I converted and migrated everything with zero downtime.

Read article →
Security11 min read

PHP Nov 2026 Critical RCEs: Patch 8.5.13 & 8.4.28 Now

The PHP Foundation released 8.5.13, 8.4.28, 8.3.37, and 8.2.36 on November 19, 2026 fixing 18 security flaws including CVSS 9.2 PHP-FPM smuggling and session upload RCEs. Here is my Linux sysadmin audit, hot mitigation, and multi-PHP patch playbook.

Read article →
Chat on WhatsApp