# Live VPS setup with LAMP (no Docker)

This guide deploys ABM SMS Gateway to Apache, PHP-FPM, and an existing MySQL/MariaDB server. Examples use Ubuntu 24.04, PHP 8.3, domain `sms.example.com`, project directory `/var/www/abmsms`, and web user `www-data`. Replace the domain and paths throughout. PHP 8.2+ is required; on an existing PHP 8.2 installation, replace `8.3` with `8.2` in package names, services, executables, and socket paths.

Run server commands over SSH with a sudo-capable deployment account. These are deployment instructions; creating this document does not change your live VPS.

## 1. Prepare the VPS and domain

Point the domain's DNS A record to the VPS public IP. If an AAAA record exists, it must also reach this server. Allow inbound TCP 80 and 443 in the VPS firewall and hosting provider's firewall, preserving SSH access. Keep MySQL private.

Check the existing stack before installing anything:

```bash
apache2 -v
php -v
mysql --version
sudo systemctl status apache2 mysql
```

For MariaDB, use service name `mariadb` instead of `mysql`. Keep the existing database service; do not install a second database engine over it. The application uses `SKIP LOCKED`: use MySQL 8.0+ or MariaDB 10.6+ with InnoDB.

Install the required PHP runtime and supporting tools if missing:

```bash
sudo apt update
sudo apt install apache2 php8.3-fpm php8.3-cli php8.3-mysql php8.3-intl php8.3-mbstring php8.3-xml php8.3-curl php8.3-zip php8.3-bcmath composer unzip acl supervisor cron certbot python3-certbot-apache
sudo systemctl enable --now apache2 php8.3-fpm supervisor cron
php8.3 -m
```

The package example assumes Ubuntu 24.04 repositories. On another distribution, use its supported package installation procedure. If LAMP already uses mod_php or serves other sites, preserve those sites' handlers and add the PHP-FPM handler only to this application's virtual host.

## 2. Transfer the application

Create the destination directory and give your deployment account ownership:

```bash
sudo mkdir -p /var/www/abmsms
sudo chown "$(id -un)":www-data /var/www/abmsms
```

Upload the project to that directory using SFTP, rsync, or your private repository. Include `app/`, `public/` (including `.htaccess`), `spark`, `composer.json`, `composer.lock`, and the other application files. Do not copy local sessions, logs, cache, or debug files into production. Transfer existing user uploads separately into `writable/uploads/`; preserve required exports if clients still need their links.

Install the locked production dependencies as the deployment account, not root:

```bash
cd /var/www/abmsms
php8.3 /usr/bin/composer install --no-dev --prefer-dist --optimize-autoloader
php8.3 /usr/bin/composer check-platform-reqs --no-dev
```

If Composer is installed elsewhere, replace `/usr/bin/composer` with the path shown by `command -v composer`.

## 3. Preserve and connect the existing database

**For your existing `abmsms` database, do not run demo seeders, `migrate:refresh`, database resets, or tests against production.** Do not import a dump over a database that already contains the clients you intend to keep.

Before moving an active installation, schedule a maintenance window: block new API/portal writes and stop the old installation's SMS, retry, export, webhook, and scheduled jobs. Keep them stopped during the final database copy so the old and new servers do not process the same work independently. Keep the old deployment and a verified database backup for recovery.

On the source database server, export a consistent InnoDB snapshot using a database account with backup permissions:

```bash
umask 077
mysqldump -u BACKUP_USER -p --single-transaction --routines --triggers --events --hex-blob abmsms > abmsms-backup.sql
```

Use `mariadb-dump` for MariaDB if appropriate. Transfer the dump privately; it contains client data. Avoid schema changes while this snapshot is running.

**Only when the target VPS does not already contain the intended database**, create an empty destination database, then import the dump once:

```bash
sudo mysql
```

```sql
CREATE DATABASE abmsms CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
EXIT;
```

```bash
mysql -u IMPORT_USER -p abmsms < abmsms-backup.sql
```

Use an appropriately privileged import account. If the target already has the correct database, skip database creation and import entirely.

Create a dedicated runtime user, or use an existing application account with equivalent access. Run the following in an administrative MySQL session, replacing the password placeholder with a new strong password:

```sql
CREATE USER 'abmsms_app'@'127.0.0.1' IDENTIFIED BY 'REPLACE_WITH_STRONG_PASSWORD';
GRANT SELECT, INSERT, UPDATE, DELETE ON abmsms.* TO 'abmsms_app'@'127.0.0.1';
```

If the account already exists, inspect its grants instead of recreating it. MySQL account host matching varies with server configuration; verify the same TCP connection the app will use:

```bash
mysql -h 127.0.0.1 -u abmsms_app -p abmsms -e 'SHOW TABLES;'
```

## 4. Configure the production environment

Securely transfer the existing installation's `.env`, or start from `.env.example` only if there is no existing configuration. Never overwrite an existing production `.env` blindly.

**Preserve the exact original `encryption.key` associated with the database.** Existing API secrets and provider credentials depend on it. Do not run `spark key:generate` when migrating existing client data. Keep a private backup of this key with your database recovery materials.

Edit `/var/www/abmsms/.env`:

```ini
CI_ENVIRONMENT = production
app.baseURL = 'https://sms.example.com/'
app.forceGlobalSecureRequests = false
cookie.secure = false

database.default.hostname = 127.0.0.1
database.default.database = abmsms
database.default.username = abmsms_app
database.default.password = 'REPLACE_WITH_STRONG_PASSWORD'
database.default.DBDriver = MySQLi
database.default.DBPrefix = sms_
database.default.port = 3306

# Keep the original value here; this is only a placeholder.
encryption.key = 'EXACT_ORIGINAL_ENCRYPTION_KEY'
session.driver = 'CodeIgniter\Session\Handlers\FileHandler'
cache.handler = file
logger.threshold = 4
```

The two `false` values are temporary until the HTTPS certificate is working. After step 6, set both to `true`. Keep the `sms_` table prefix. Do not copy local database credentials into a published document or source control.

For direct Apache HTTPS, set `public array $proxyIPs = [];` in `app/Config/App.php` on the deployed copy: this repository contains proxy ranges for its former container deployment. If a real reverse proxy terminates TLS, trust only its actual peer addresses and configure its forwarded headers instead.

Set permissions so PHP can read configuration and write runtime files, while application code remains owned by the deployment account:

```bash
cd /var/www/abmsms
sudo chgrp -R www-data .
sudo chmod -R g+rX .
chmod 640 .env
sudo setfacl -R -m u:www-data:rwX writable
sudo find writable -type d -exec setfacl -m d:u:www-data:rwx {} +
```

Do not use `chmod 777`. Code, vendor packages, backups, and `.env` must remain outside the web document root.

## 5. Configure Apache

Create `/etc/apache2/sites-available/abmsms.conf`:

```apache
<VirtualHost *:80>
    ServerName sms.example.com
    DocumentRoot /var/www/abmsms/public

    <Directory /var/www/abmsms/public>
        Options -Indexes +FollowSymLinks
        AllowOverride All
        Require all granted
        DirectoryIndex index.php
    </Directory>

    <FilesMatch "\.php$">
        SetHandler "proxy:unix:/run/php/php8.3-fpm.sock|fcgi://localhost/"
    </FilesMatch>

    ErrorLog ${APACHE_LOG_DIR}/abmsms-error.log
    CustomLog ${APACHE_LOG_DIR}/abmsms-access.log combined
</VirtualHost>
```

Enable the site and required modules, validate, then reload:

```bash
sudo a2enmod rewrite proxy_fcgi setenvif ssl
sudo a2ensite abmsms.conf
sudo apache2ctl configtest
sudo systemctl reload apache2
curl -I http://sms.example.com/admin/login
```

Do not disable other sites on a shared VPS. The document root must end in `/public`, not the project directory.

## 6. Enable HTTPS

After DNS resolves correctly and HTTP is reachable:

```bash
sudo certbot --apache -d sms.example.com --redirect
sudo certbot renew --dry-run
```

Confirm that Certbot's renewal timer or cron job is installed and active. Now update `.env`:

```ini
app.baseURL = 'https://sms.example.com/'
app.forceGlobalSecureRequests = true
cookie.secure = true
```

Verify both login pages and confirm sensitive files are not exposed:

```bash
curl -I https://sms.example.com/admin/login
curl -I https://sms.example.com/portal/login
curl -I https://sms.example.com/.env
curl -I https://sms.example.com/composer.json
```

Login pages should return 200. Sensitive paths should return 403 or 404, with no file contents.

## 7. Verify the imported application before enabling workers

```bash
cd /var/www/abmsms
sudo -u www-data /usr/bin/php8.3 spark migrate:status
sudo -u www-data /usr/bin/php8.3 spark sms:audit-balances
```

`migrate:status` only checks migration status. If every migration is already applied, leave the schema alone. If there are pending migrations, review them against a restored backup first; after a verified backup and maintenance window, use a separate migration account with the required DDL privileges to run `php8.3 spark migrate --all -n`, then restore the restricted runtime credentials.

Sign in with your existing admin and tenant accounts. Check client records, balances, message history, sender IDs, API credentials, and provider settings. Investigate balance drift before reopening traffic; do not manually edit the ledger or cached balances.

**Do not seed `DatabaseSeeder`, `AdminUserSeeder`, or `TestTenantSeeder` into this existing live database.** Preserve existing accounts and credentials.

## 8. Configure background workers

Workers send queued SMS and outbound webhooks. Review imported pending queues and provider settings first. Start workers only when ready for those existing jobs to execute, and keep the old server's workers stopped after cutover.

Create `/etc/supervisor/conf.d/abmsms.conf`:

```ini
[program:abmsms-dispatch]
command=/bin/sh -c '/usr/bin/php8.3 spark sms:dispatch --limit 500; sleep 2'
directory=/var/www/abmsms
user=www-data
autostart=false
autorestart=true
startsecs=0
stopasgroup=true
killasgroup=true
stopwaitsecs=120
redirect_stderr=true
stdout_logfile=/var/www/abmsms/writable/logs/supervisor-dispatch.log
stdout_logfile_maxbytes=10MB
stdout_logfile_backups=5

[program:abmsms-retry]
command=/bin/sh -c '/usr/bin/php8.3 spark sms:retry --limit 500; sleep 30'
directory=/var/www/abmsms
user=www-data
autostart=false
autorestart=true
startsecs=0
stopasgroup=true
killasgroup=true
stopwaitsecs=120
redirect_stderr=true
stdout_logfile=/var/www/abmsms/writable/logs/supervisor-retry.log
stdout_logfile_maxbytes=10MB
stdout_logfile_backups=5

[program:abmsms-export]
command=/bin/sh -c '/usr/bin/php8.3 spark sms:export --limit 10; sleep 15'
directory=/var/www/abmsms
user=www-data
autostart=false
autorestart=true
startsecs=0
stopasgroup=true
killasgroup=true
stopwaitsecs=120
redirect_stderr=true
stdout_logfile=/var/www/abmsms/writable/logs/supervisor-export.log
stdout_logfile_maxbytes=10MB
stdout_logfile_backups=5

[program:abmsms-webhooks]
command=/bin/sh -c '/usr/bin/php8.3 spark sms:webhooks --limit 200; sleep 10'
directory=/var/www/abmsms
user=www-data
autostart=false
autorestart=true
startsecs=0
stopasgroup=true
killasgroup=true
stopwaitsecs=120
redirect_stderr=true
stdout_logfile=/var/www/abmsms/writable/logs/supervisor-webhooks.log
stdout_logfile_maxbytes=10MB
stdout_logfile_backups=5
```

These application commands process one batch and exit; Supervisor restarts them after the shell's sleep interval. Adjust shutdown timeouts for observed batch duration. Always use `--limit 500`, not `--limit=500`.

Load the configuration while the jobs remain stopped:

```bash
sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl status
```

At the agreed cutover, change all four `autostart=false` entries to `autostart=true`, then run:

```bash
sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start abmsms-dispatch abmsms-retry abmsms-export abmsms-webhooks
sudo supervisorctl status
```

An “already started” message is harmless if the configuration update started a worker. Verify logs for repeated errors. Avoid a real test SMS until ready for a billed provider request.

## 9. Add scheduled maintenance

Create `/etc/cron.d/abmsms`, owned by root with mode 644 and a final newline:

```cron
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
0 2 * * * www-data cd /var/www/abmsms && /usr/bin/flock -n writable/audit.lock /usr/bin/php8.3 spark sms:audit-balances >> writable/logs/cron-audit-balances.log 2>&1
15 * * * * www-data cd /var/www/abmsms && /usr/bin/flock -n writable/stats.lock /usr/bin/php8.3 spark sms:aggregate-stats >> writable/logs/cron-aggregate-stats.log 2>&1
30 2 * * * www-data cd /var/www/abmsms && /usr/bin/flock -n writable/prune.lock /usr/bin/php8.3 spark sms:prune-logs >> writable/logs/cron-prune-logs.log 2>&1
45 2 * * * www-data cd /var/www/abmsms && /usr/bin/flock -n writable/archive.lock /usr/bin/php8.3 spark sms:archive >> writable/logs/cron-archive.log 2>&1
```

Schedules use the VPS system timezone; check `timedatectl` and choose the intended maintenance hours. Database timestamps remain UTC and the application renders Asia/Dhaka. Defaults prune API logs after 30 days and archive messages after 180 days; review these policies before enabling the jobs. Monitor audit output and errors, and arrange log rotation for application/cron logs.

## 10. Cutover, backups, and future updates

Once database checks, HTTPS, accounts, and workers are healthy, point clients/API integrations to the new hostname or finish the DNS cutover and reopen traffic. Provider delivery callbacks use `POST https://sms.example.com/webhook/dlr/{provider_slug}`; configure the provider's confirmed callback mechanism and update any external IP allowlists for the new VPS.

Back up the database regularly together with the original encryption key, private configuration, and user uploads. Store encrypted copies off the VPS and test a restore. Keep database dumps outside `public/`. Never run both old and new installations as active writers after the final copy.

For later releases: back up first, restrict new traffic, stop this application's Supervisor workers and pause its cron entries, deploy code, install locked dependencies, review/apply any pending migrations, verify permissions, then restart workers and restore cron/traffic. Review schema compatibility before rolling code back. A database restore after reopening traffic can lose newly created messages and ledger entries; reconcile those writes before recovery.

## Troubleshooting

| Symptom | Check |
| --- | --- |
| HTTP 500 | `/var/log/apache2/abmsms-error.log`, PHP-FPM logs, and `writable/logs/`; ensure PHP can read `.env` and write `writable/`. |
| Database access denied | Match `.env` username/password/host with the tested MySQL TCP account and its grants. |
| Routes return 404 | Apache document root ends in `public/`, `mod_rewrite` is enabled, `.htaccess` was uploaded, and `AllowOverride All` applies. |
| Login redirects to localhost or the old domain | Correct `app.baseURL`; check secure cookies and use HTTPS. |
| Infinite HTTPS redirects | Check actual TLS termination and trusted proxy addresses/headers. |
| API/provider decryption fails after import | Restore the original `encryption.key`; do not generate another key. |
| SMS remains queued | Check Supervisor status, worker logs, tenant balance, provider status, and external network access. |
| Wrong PHP runtime | Check the virtual host socket, CLI executable, cron entries, and Supervisor commands all use the intended version. |

## References

- [CodeIgniter production deployment](https://codeigniter.com/user_guide/installation/deployment.html)
- [CodeIgniter application structure and public web root](https://codeigniter.com/user_guide/concepts/structure.html)
- [Certbot Apache setup instructions](https://certbot.eff.org/instructions?ws=apache)
- [Supervisor configuration reference](https://docs.supervisord.org/configuration.html)
- [Project deployment reference](deployment.md)
