# Blog Admin Panel: AWS Deployment Guide

For the DevOps / AWS team. This covers everything needed to host the Second Phone Number blog admin panel on AWS, for staging first and then production.

The repository already contains tested scripts for this setup in `deploy/`. This guide explains what to provision, what to run and how to operate it.

---

## 1. Summary

| Item                | Value                                                                              |
| ------------------- | ---------------------------------------------------------------------------------- |
| What it is          | Internal web app where the content team writes and publishes blog articles         |
| Framework           | Next.js 16 (Node.js server app, not a static site), React 19, TypeScript           |
| Runtime             | Node.js 22 LTS (minimum 20.19)                                                     |
| Port                | 3200, bound to `127.0.0.1` only. Nginx is the public entry point                   |
| Database            | **None.** All data lives in the Laravel CMS, reached over its HTTPS API            |
| File storage        | **None.** Image uploads are forwarded to Laravel                                   |
| State on the server | Only the `.env` file. The app is stateless and can be rebuilt from git at any time |
| Users               | A small internal team (editors and admins). Low traffic                            |
| HTTPS               | **Required.** Sign-in does not work over plain HTTP (secure cookie)                |
| Recommended setup   | One EC2 instance, Nginx + Let's Encrypt, PM2 (Option A below)                      |

### Architecture

```
 Editors (browser)
      │  HTTPS 443
      ▼
 ┌──────────────── EC2 (Ubuntu 24.04) ─────────────────┐
 │  Nginx :80/:443  (Let's Encrypt certificate)        │
 │        │                                            │
 │        ▼                                            │
 │  Next.js admin panel on 127.0.0.1:3200 (PM2)        │
 └────────┬────────────────────────────────────────────┘
          │  HTTPS (outbound)
          ▼
 Laravel CMS API  https://secondphonenumber.worksqr.com/api
   stores articles and media, publishes scheduled posts,
   refreshes the public website
```

The public website (secondlinenumber.com) is hosted separately and is **not** part of this deployment.

---

## 2. Inputs needed before starting

| #   | Item                                     | Staging                                             | Production                                      | Owner        |
| --- | ---------------------------------------- | --------------------------------------------------- | ----------------------------------------------- | ------------ |
| 1   | Admin panel domain                       | `cms-staging.secondlinenumber.com`                  | `cms.secondlinenumber.com`                      | Dev team     |
| 2   | Laravel CMS (`CMS_ENV`)                  | `dev` → `https://secondphonenumber.worksqr.com/api` | `prod` → `https://api.secondlinenumber.com/api` | Backend team |
| 3   | Public website URL (`SITE_URL`)          | staging website URL                                 | `https://secondlinenumber.com`                  | Dev team     |
| 4   | Access to DNS for `secondlinenumber.com` | needed to add an A record                           | same                                            | DevOps       |
| 5   | Read access to the Git repository        | Azure DevOps (see §5.2)                             | same                                            | Dev team     |
| 6   | Email for Let's Encrypt expiry notices   | a team mailbox                                      | same                                            | DevOps       |
| 7   | Office/VPN IPs to allowlist (optional)   | if the team wants IP restriction                    | recommended                                     | Dev team     |

Repository: `https://dev.azure.com/BTS-MobileApps/1140_2nd_Phone_Number/_git/1140_2nd_phone_number_admin_panel`. The app is at the root of that repository.

---

## 3. AWS resources

### 3.1 EC2

| Setting       | Value                                                                                      |
| ------------- | ------------------------------------------------------------------------------------------ |
| AMI           | Ubuntu Server 24.04 LTS                                                                    |
| Instance type | `t4g.small` (2 vCPU, 2 GB, ARM) or `t3.small` (x86). Either works                          |
| Storage       | 20 GB gp3                                                                                  |
| Elastic IP    | Yes, attach one (DNS points at it)                                                         |
| IAM role      | `AmazonSSMManagedInstanceCore` (for Session Manager access), plus CloudWatch agent if used |
| Region        | Any; closest to the Laravel server is best (the admin calls it on every page)              |

The build (`next build`) needs more than 2 GB of memory. The setup script adds a 2 GB swap file so a `small` instance is enough. If builds are slow, use a `medium`.

### 3.2 Security group

| Direction | Port | Source              | Why                                                                      |
| --------- | ---- | ------------------- | ------------------------------------------------------------------------ |
| Inbound   | 443  | `0.0.0.0/0`, `::/0` | HTTPS (or office/VPN IPs only, see §7)                                   |
| Inbound   | 80   | `0.0.0.0/0`, `::/0` | Let's Encrypt validation and redirect to HTTPS                           |
| Inbound   | 22   | Admin IPs only      | SSH. Not needed at all if you use SSM Session Manager                    |
| Outbound  | 443  | `0.0.0.0/0`         | Laravel API, npm registry, NodeSource, Let's Encrypt, Cloudflare IP list |
| Outbound  | 22   | `0.0.0.0/0`         | `git` over SSH to `ssh.dev.azure.com`                                    |

Port 3200 must **not** be opened. Next.js listens on localhost only.

If the Laravel server has a firewall or WAF, it must accept HTTPS requests from this instance's Elastic IP.

### 3.3 DNS

Create an **A record**: `cms-staging.secondlinenumber.com` → Elastic IP.

If DNS is on Cloudflare, set it to **DNS only (grey cloud)** until the certificate is issued in §5.3. It can be switched to proxied (orange cloud) afterwards.

---

## 4. Environment variables

The file lives on the server at `/srv/secondline-cms/shared/.env` (permissions `600`, owner `cms`). Templates: `deploy/staging.env.example` and `production.env.example`.

| Variable                             | Required              | Example                                         | Notes                                                                                                                                                                              |
| ------------------------------------ | --------------------- | ----------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `CMS_ENV`                            | Yes                   | `prod` or `dev`                                 | Which Laravel CMS: `prod` = `https://api.secondlinenumber.com/api`, `dev` = staging `https://secondphonenumber.worksqr.com/api` (the default). **Read at build time and runtime.** |
| `LARAVEL_API_URL`                    | No                    | `https://api.secondlinenumber.com/api`          | Overrides the API `CMS_ENV` picks. No trailing slash. Leave unset normally.                                                                                                        |
| `SITE_URL`                           | Yes                   | `https://secondlinenumber.com`                  | Public website, no trailing slash. Used for "View live" links and article previews. **Read at build time and runtime.**                                                            |
| `MEDIA_MAX_UPLOAD_MB`                | No (default `10`)     | `10`                                            | Largest image upload. Must be ≤ Laravel's limit and below Nginx's `client_max_body_size` (12 MB).                                                                                  |
| `IMPORT_IMAGE_HOSTS`                 | No                    | `secondlinenumber.com,www.secondlinenumber.com` | Hosts the JSON import may download images from. That is the default value.                                                                                                         |
| `NEXT_SERVER_ACTIONS_ENCRYPTION_KEY` | Only for 2+ instances | 32-byte base64 key                              | Same value on every instance. Generate with `openssl rand -base64 32`. Not needed on a single server.                                                                              |

`NODE_ENV=production` is set by PM2; do not put it in `.env`.

The app holds **no secrets of its own**: there are no database passwords or API keys. Each editor signs in with their own Laravel account, and the token is kept in an HTTP-only cookie.

**Changing a variable:** because `CMS_ENV` (or `LARAVEL_API_URL`) and `SITE_URL` are also baked in at build time (security headers and image proxy rules), run a full deploy (`deploy.sh`) after changing them, not just a restart.

---

## 5. Option A (recommended): single EC2 with Nginx and PM2

All scripts are in `deploy/`:

| File                        | Purpose                                                                                                      |
| --------------------------- | ------------------------------------------------------------------------------------------------------------ |
| `setup-server.sh`           | One-time: installs Node.js 22, Nginx, certbot, PM2 (+ log rotation), 2 GB swap, `cms` user, folders, SSH key |
| `setup-nginx.sh`            | One-time: installs the Nginx site for the domain and gets the HTTPS certificate                              |
| `deploy.sh`                 | Every release: pull, build in a new folder, switch, reload, health check, auto-rollback on failure           |
| `ecosystem.config.cjs`      | PM2 process definition (`secondline-cms`, `127.0.0.1:3200`, restarts above 800 MB)                           |
| `nginx/secondline-cms.conf` | Nginx reverse-proxy template                                                                                 |
| `staging.env.example`       | Template for `/srv/secondline-cms/shared/.env`                                                               |
| `production.env.example`    | The same for production (`CMS_ENV="prod"`)                                                                   |

Folder layout on the server:

```
/srv/secondline-cms/
  repo/          git clone of the repository
  releases/      one folder per deploy (last 3 kept)
  current  ->    symlink to the live release
  shared/.env    environment file, linked into every release
  logs/          cms.out.log, cms.error.log (rotated at 20 MB, 14 kept)
```

### 5.1 Prepare the server (once)

```bash
scp deploy/setup-server.sh ubuntu@<elastic-ip>:
ssh ubuntu@<elastic-ip>
sudo bash setup-server.sh
```

The script is safe to run again. At the end it prints an **SSH public key** for the `cms` user.

### 5.2 Give the server read access to the repository (once)

Add the printed public key to Azure DevOps: **User settings → SSH public keys** (ideally on a service account with read-only access to this repository). Then clone:

```bash
sudo -u cms -H git clone \
  git@ssh.dev.azure.com:v3/BTS-MobileApps/1140_2nd_Phone_Number/1140_2nd_phone_number_admin_panel \
  /srv/secondline-cms/repo
sudo -u cms -H git -C /srv/secondline-cms/repo checkout <branch>
```

Use the branch the dev team names for the environment (for production, `main`).

### 5.3 Nginx and HTTPS (once)

DNS from §3.3 must already resolve to the Elastic IP.

```bash
sudo bash /srv/secondline-cms/repo/deploy/setup-nginx.sh \
  cms-staging.secondlinenumber.com devops@<your-domain>
```

This installs the site, requests a Let's Encrypt certificate and enables the HTTP → HTTPS redirect. Renewal is automatic (`systemctl list-timers | grep certbot`).

### 5.4 Environment file (once)

```bash
sudo -u cms cp /srv/secondline-cms/repo/deploy/staging.env.example /srv/secondline-cms/shared/.env
sudo -u cms chmod 600 /srv/secondline-cms/shared/.env
sudo -u cms nano /srv/secondline-cms/shared/.env
```

Set `CMS_ENV` and `SITE_URL` (see §4); for production start from `production.env.example`. Replace every `<…>` placeholder.

### 5.5 First deploy

```bash
sudo -u cms -H bash /srv/secondline-cms/repo/deploy/deploy.sh
```

Takes a few minutes (`npm ci` + `next build`). It ends with `Live: <release> (<branch> @ <commit>)`.

### 5.6 Verify

| Check                                                         | Expected                                       |
| ------------------------------------------------------------- | ---------------------------------------------- |
| `curl -I http://cms-staging.secondlinenumber.com`             | `301` to `https://…`                           |
| `curl -I https://cms-staging.secondlinenumber.com/login`      | `200`, with `Strict-Transport-Security` header |
| `curl -I https://cms-staging.secondlinenumber.com/admin`      | `307` to `/login?next=%2Fadmin`                |
| `sudo -u cms -H pm2 status`                                   | `secondline-cms` is `online`                   |
| Sign in through the browser with a Laravel blog admin account | Dashboard loads with the article list          |
| Upload an image under **Media**                               | Upload succeeds and the image displays         |

---

## 6. Day-to-day operations

| Task                          | Command                                                         |
| ----------------------------- | --------------------------------------------------------------- |
| Deploy latest code            | `sudo -u cms -H bash /srv/secondline-cms/repo/deploy/deploy.sh` |
| Deploy a specific branch      | `… deploy.sh --branch main`                                     |
| Roll back to previous release | `… deploy.sh --rollback`                                        |
| Process status / memory       | `sudo -u cms -H pm2 status`                                     |
| Live logs                     | `sudo -u cms -H pm2 logs secondline-cms`                        |
| Restart (after `.env` edit)   | `sudo -u cms -H pm2 reload secondline-cms --update-env`         |
| Which commit is live          | `cat /srv/secondline-cms/current/REVISION`                      |
| Nginx logs                    | `/var/log/nginx/access.log`, `/var/log/nginx/error.log`         |

How `deploy.sh` stays safe:

- It builds in a new release folder beside the live one, so the site keeps serving during the build.
- After switching, it polls `http://127.0.0.1:3200/login` for up to 60 seconds. If the new release does not respond, it switches back to the previous one automatically.
- PM2 reloads with a 10-second grace period for requests in flight.
- PM2 is registered with systemd, so the app comes back after a reboot.

**CI/CD (optional):** an Azure DevOps pipeline can run the deploy over SSM instead of someone logging in:

```bash
aws ssm send-command --instance-ids <id> --document-name AWS-RunShellScript \
  --parameters 'commands=["sudo -u cms -H bash /srv/secondline-cms/repo/deploy/deploy.sh --branch main"]'
```

---

## 7. Security

- **HTTPS only.** The session cookie uses the `__Host-` prefix and `Secure` flag; browsers refuse it over HTTP, so sign-in fails without HTTPS.
- **Restrict who can reach it (recommended for production).** This is an internal tool; the public website does not depend on it. Choose one:
  - Security group: allow 443 only from office/VPN IPs (keep 80 open for certificate renewal, or switch certbot to DNS validation).
  - Nginx allowlist: uncomment the `allow … / deny all` block in `nginx/secondline-cms.conf`.
  - Cloudflare Access (Zero Trust) in front of the domain.
- **No SSH from the internet.** Prefer SSM Session Manager; otherwise limit port 22 to admin IPs.
- **App user.** The app runs as the unprivileged `cms` user. `.env` is `chmod 600`.
- **Security headers** are set by the app: Content-Security-Policy, HSTS, `X-Frame-Options: DENY`, `nosniff`, and `noindex` on every page.
- **Patching:** enable `unattended-upgrades` for Ubuntu security updates.
- **Behind Cloudflare (orange cloud):** uncomment `include /etc/nginx/snippets/cloudflare-real-ip.conf;` in the Nginx site so logs show real visitor IPs, and set Cloudflare SSL mode to **Full (strict)**.

---

## 8. Monitoring and backups

- **Uptime check:** `GET https://<domain>/login` should return `200`. It does not depend on the Laravel API, so it measures this server only.
- **End-to-end check (optional):** sign in and load `/admin`; this also confirms the Laravel API is reachable.
- **Logs:** `/srv/secondline-cms/logs/cms.*.log` (rotated by `pm2-logrotate`). Ship them to CloudWatch Logs with the CloudWatch agent if central logging is wanted.
- **Alarms (suggested):** EC2 status check failed, CPU > 80% for 10 min, disk > 80%, memory (via CloudWatch agent).
- **Backups:** nothing on this server needs regular backup. Content is in the Laravel CMS. The only file to keep a copy of is `/srv/secondline-cms/shared/.env` (contains no secrets, only URLs). An occasional AMI snapshot speeds up rebuilding but is optional.

---

## 9. Option B: Load balancer or containers (only if required)

Option A is enough for this app's traffic. If company policy needs an ALB, Auto Scaling or ECS/Fargate, these are the requirements:

| Topic              | Requirement                                                                                                                                                  |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| TLS                | Terminate at the ALB with an ACM certificate. Redirect HTTP → HTTPS on the listener.                                                                         |
| Forwarded headers  | Pass `Host` unchanged and set `X-Forwarded-Proto: https` (ALB does this). Server Actions compare the request origin with `Host` and fail if it is rewritten. |
| Health check       | `GET /login`, expect `200`.                                                                                                                                  |
| Request body size  | Allow at least 12 MB (image uploads).                                                                                                                        |
| Idle timeout       | 60 seconds or more.                                                                                                                                          |
| Sticky sessions    | Not needed. The session is a cookie validated by Laravel on each request.                                                                                    |
| Multiple instances | Set the same `NEXT_SERVER_ACTIONS_ENCRYPTION_KEY` on all of them, and run **the same build** everywhere (build once, deploy the artifact or image).          |
| Build              | `npm ci && npm run build`, with `CMS_ENV` and `SITE_URL` set **during the build** as well as at runtime.                                                     |
| Start command      | `NODE_ENV=production node_modules/next/dist/bin/next start --hostname 0.0.0.0 --port 3200`                                                                   |
| Memory             | ~300–500 MB at runtime; 1 GB per task is comfortable. The build needs about 2.5 GB.                                                                          |
| Writable disk      | Only Next.js's cache in `.next/cache`. Nothing needs to persist.                                                                                             |

There is no Dockerfile in the repository yet. The dev team can add one (Next.js `output: "standalone"`) if containers are chosen.

---

## 10. Troubleshooting

| Symptom                                                | Likely cause and fix                                                                                                                                                                                                    |
| ------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Sign-in form does nothing or returns to the login page | Site opened over HTTP, or a proxy strips cookies. Use HTTPS end to end.                                                                                                                                                 |
| "Couldn't reach the CMS"                               | `CMS_ENV` / `LARAVEL_API_URL` wrong, or outbound 443 to the Laravel host is blocked (security group, NACL, Laravel firewall). Test: `curl -I https://api.secondlinenumber.com/api/health` (production) from the server. |
| `Invalid environment variables` in `cms.error.log`     | A value in `shared/.env` is not a valid URL or number.                                                                                                                                                                  |
| `npm run build` ends with `Killed`                     | Out of memory. Check `swapon --show`; use a larger instance.                                                                                                                                                            |
| Image upload fails with `413`                          | File is larger than Nginx's 12 MB, `MEDIA_MAX_UPLOAD_MB` or Laravel's limit.                                                                                                                                            |
| A page shows "Not available yet"                       | Expected: the Laravel CMS doesn't provide that feature's API yet. Not a hosting problem.                                                                                                                                |
| `deploy.sh` says "The new release isn't answering"     | Check `/srv/secondline-cms/logs/cms.error.log`. The previous release is kept live automatically.                                                                                                                        |
| `git fetch` asks for a password or fails               | The `cms` user's SSH key isn't added in Azure DevOps (§5.2), or outbound port 22 is blocked.                                                                                                                            |
| `502 Bad Gateway` from Nginx                           | App not running: `sudo -u cms -H pm2 status`, then check the logs.                                                                                                                                                      |

---

## 11. Production rollout

Repeat §3–§5 with:

- Domain `cms.secondlinenumber.com`
- `CMS_ENV=prod` (`https://api.secondlinenumber.com/api`), from `production.env.example`
- `SITE_URL=https://secondlinenumber.com`
- Branch `main`
- Access restriction from §7 turned on

---

## 12. Open items for the dev team

1. **Article preview framing.** The admin panel shows article previews by framing `SITE_URL/blog/preview/<token>/`. The website currently allows framing only from the Laravel host, so previews will be blocked once the admin panel runs on its own domain. The website repository (`next.config.ts` and `astro/src/middleware.ts`) needs the admin domain added to `frame-ancestors`. Everything else works without this.
2. **Production Laravel API**: `https://api.secondlinenumber.com/api` (`CMS_ENV=prod`). Deployed: rechecked later on 2026-11-03, `/api/health`, `/api/v1/posts` and `/api/v1/sitemap` return 200 and `/api/admin/auth/login` validates sign-ins. Production admin accounts must exist on this server (staging accounts don't carry over).
3. **Staging website URL** for `SITE_URL` on staging.

---

## 13. Handover checklist

- [ ] EC2 instance, Elastic IP, security group and IAM role created (§3)
- [ ] DNS A record added (§3.3)
- [ ] `setup-server.sh` run; SSH key added to Azure DevOps; repository cloned (§5.1–5.2)
- [ ] `setup-nginx.sh` run; HTTPS certificate issued (§5.3)
- [ ] `shared/.env` filled in, `chmod 600` (§5.4)
- [ ] First deploy succeeded (§5.5)
- [ ] All checks in §5.6 pass, including sign-in and an image upload
- [ ] Access restriction applied (production) (§7)
- [ ] Uptime check and alarms configured (§8)
- [ ] Domain, Elastic IP, instance ID and deploy command shared with the dev team
