# Deployment Guide - Web Dolphin Japan

Complete guide for deploying Web Dolphin Japan to production servers.

> **Backend API-Only:** Deployment focuses on PHP/Laravel backend only. No frontend build steps needed.

## Pre-Deployment Checklist

Before deploying, ensure:

- [ ] All tests pass: `composer run test`
- [ ] Code is formatted: `./vendor/bin/pint`
- [ ] No `console.log()`, `var_dump()`, `dd()` in code
- [ ] `.env` file is updated with production values
- [ ] Database backups are available
- [ ] Team is notified of planned deployment
- [ ] Deployment plan is reviewed

---

## Deployment Environments

### Development
```env
APP_ENV=local
APP_DEBUG=true
LOG_LEVEL=debug
```

### Staging (Pre-production testing)
```env
APP_ENV=staging
APP_DEBUG=false
LOG_LEVEL=notice
```

### Production
```env
APP_ENV=production
APP_DEBUG=false
LOG_LEVEL=warning
```

---

## Step-by-Step Deployment

### Step 1: Prepare Release

```bash
# Create release tag
git tag -a v1.0.0 -m "Release version 1.0.0"
git push origin v1.0.0

# Or use branch for controlled rollout
git checkout -b release/v1.0.0
```

### Step 2: Deploy to Server

**Via Git (Recommended)**

```bash
# SSH into production server
ssh user@your-server.com

# Navigate to project directory (e.g., /var/www/web-dolphin-japan)
cd /var/www/web-dolphin-japan

# Pull latest code
git fetch origin
git checkout v1.0.0  # or main branch

# Or alternatively
git pull origin main
```

**Via Zip File**

```bash
# Create release package locally
git archive --format zip HEAD > web-dolphin-japan-v1.0.0.zip

# Upload to server
scp web-dolphin-japan-v1.0.0.zip user@your-server.com:/tmp/

# Extract on server
ssh user@your-server.com
cd /var/www/web-dolphin-japan
unzip /tmp/web-dolphin-japan-v1.0.0.zip
```

### Step 3: Install Dependencies

```bash
# Install PHP dependencies (production only)
composer install --no-dev --optimize-autoloader

# This installs only packages needed for production (faster)
```

### Step 4: Environment Configuration

```bash
# Copy production .env (should already be on server)
# OR create it with correct values:
cat > .env << EOF
APP_NAME="Web Dolphin Japan"
APP_ENV=production
APP_KEY=your-generated-key-here
APP_DEBUG=false
APP_URL=https://your-domain.com

DB_CONNECTION=pgsql
DB_HOST=your-db-host
DB_PORT=5432
DB_DATABASE=dolphinapp
DB_USERNAME=postgres
DB_PASSWORD=secure_password

QUEUE_CONNECTION=database
CACHE_STORE=database
SESSION_DRIVER=database

LOG_CHANNEL=daily
LOG_LEVEL=warning

# ... other production settings
EOF
```

### Step 5: Generate Application Key (if new)

```bash
# Only run once per server
php artisan key:generate --force
```

### Step 6: Database Migrations

```bash
# Run pending migrations (safe - doesn't delete data)
php artisan migrate --force

# If you need to rollback (dangerous!)
php artisan migrate:rollback --force
```

### Step 7: Optimize for Production

```bash
# Clear all caches
php artisan config:clear
php artisan view:clear
php artisan cache:clear

# Optimize configuration (recommended)
php artisan config:cache
php artisan route:cache
php artisan view:cache
```

### Step 8: Set File Permissions

```bash
# Make storage and bootstrap writable
chmod -R 775 storage bootstrap/cache

# For most hosting:
chmod -R 755 .

# Make storage specifically writable
chmod -R 775 storage bootstrap/cache

# If using web server user (Apache/Nginx):
chown -R www-data:www-data storage bootstrap/cache
chmod -R 775 storage bootstrap/cache
```

### Step 10: Configure Web Server

#### Apache (.htaccess)

```apache
<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Redirect to public folder
    RewriteCond %{REQUEST_URI} !^/public/
    RewriteRule ^(.*)$ /public/$1 [L]

    # Handle all requests through index.php
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^ index.php [L]
</IfModule>
```

#### Nginx

```nginx
server {
    listen 80;
    server_name your-domain.com;

    root /var/www/web-dolphin-japan/public;
    index index.php index.html;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        fastcgi_pass unix:/run/php/php8.2-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~ /\.env {
        deny all;
    }
}
```

### Step 10: SSL Certificate (HTTPS)

```bash
# Install Certbot (for Let's Encrypt)
sudo apt-get install certbot python3-certbot-nginx

# Generate certificate
sudo certbot certonly --nginx -d your-domain.com

# Or for manual installation, upload certificate files to server
```

### Step 11: Verify Deployment

```bash
# Check application is running
php artisan tinker
>>> config('app.debug')  # Should be false
>>> DB::connection()->getPdo()  # Should connect to DB

# Check logs
tail -f storage/logs/laravel.log

# Test API endpoint
curl https://your-domain.com/api/v1/brand/

# Should respond with:
# {"code":200,"hasError":false,"result":{...}}
```

### Step 12: Monitor Application

```bash
# Set up monitoring
# Check error logs regularly
tail -f storage/logs/laravel.log

# Monitor disk space
df -h

# Check file permissions
ls -la storage/

# Monitor database
# Check for slow queries:
psql -U postgres -d dolphinapp
dolphinapp=# SELECT query, mean_time FROM pg_stat_statements;
dolphinapp=# \q
```

### Step 13: Database Backup & Migration

### Backup Before Deployment

```bash
# PostgreSQL backup
pg_dump -U postgres dolphinapp > backup.sql

# Full directory backup
tar -czf backup-$(date +%Y%m%d).tar.gz /var/www/web-dolphin-japan
```

### Restore from Backup

```bash
# Restore PostgreSQL
psql -U postgres dolphinapp < backup.sql

# Run migrations to latest version
php artisan migrate
```

---

## Queue Processing

For background job processing in production:

### Setup Supervisor (Recommended)

Create `/etc/supervisor/conf.d/web-dolphin-queue.conf`:

```ini
[program:web-dolphin-queue]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/web-dolphin-japan/artisan queue:work database --sleep=3 --tries=3 --timeout=90
autostart=true
autorestart=true
stdout_logfile=/var/www/web-dolphin-japan/storage/logs/queue.log
stderr_logfile=/var/www/web-dolphin-japan/storage/logs/queue-error.log
numprocs=4
redirect_stderr=true
stopasgroup=true
```

Start supervisor:
```bash
sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start web-dolphin-queue:*
```

### Or Use Cron

Add to crontab:
```bash
crontab -e

# Add this line:
* * * * * cd /var/www/web-dolphin-japan && php artisan schedule:run >> /dev/null 2>&1
```

---

## Rollback Procedure

If deployment fails, rollback to previous version:

```bash
# Revert code
git checkout previous-version
git pull

# Clear caches
php artisan config:clear
php artisan cache:clear

# Run migrations (if schema changed)
php artisan migrate --force

# Restart queue (if needed)
sudo supervisorctl restart web-dolphin-queue:*

# Restart web server
sudo systemctl restart nginx  # or apache2
```

---

## Monitoring & Maintenance

### Daily

```bash
# Check error logs
tail storage/logs/laravel.log

# Check disk space
df -h

# Check memory usage
free -h
```

### Weekly

```bash
# Clean up old logs
php artisan log:clear

# Check database size
psql -U postgres -d dolphinapp -c "SELECT pg_database.datname, pg_size_pretty(pg_database_size(pg_database.datname)) FROM pg_database ORDER BY pg_database_size(pg_database.datname) DESC;"
```

### Monthly

```bash
# Update dependencies securely
composer update --no-dev

# Scan for security vulnerabilities
composer audit

# Backup database
pg_dump -U postgres dolphinapp > backup-$(date +%Y%m%d).sql
```

---

## Performance Optimization

### Enable Caching

```bash
# Configuration cache
php artisan config:cache

# Route cache
php artisan route:cache

# View cache (already cached by Laravel)
php artisan view:cache
```

### Enable Query Logging (for debugging only)

```env
# In .env (temporary, for debugging)
APP_DEBUG=true
LOG_CHANNEL=single
```

### Optimize Composer Autoloader

```bash
composer install --optimize-autoloader --no-dev
```

### Use Content Delivery Network (CDN)

Configure in `.env` or `config/filesystems.php`:
```php
'public' => [
    'driver' => 's3',
    'key' => env('AWS_ACCESS_KEY_ID'),
    'secret' => env('AWS_SECRET_ACCESS_KEY'),
    'region' => env('AWS_DEFAULT_REGION'),
    'bucket' => env('AWS_BUCKET'),
    'url' => env('AWS_URL'),
]
```

---

## Troubleshooting Deployment

| Issue | Solution |
|-------|----------|
| Blank page on production | Check `APP_DEBUG=false`, clear cache, check logs |
| Database connection error | Verify DB credentials in `.env`, ensure PostgreSQL running |
| 403 Forbidden | Fix file permissions: `chmod -R 755 .` then `chmod -R 775 storage` |
| 500 Internal Server Error | Check `storage/logs/laravel.log` for details |
| Queue jobs not processing | Start Supervisor: `supervisorctl start web-dolphin-queue:*` |

---

## Post-Deployment Verification

```bash
# ✅ Test database connection
php artisan tinker
>>> DB::connection()->getPdo()

# ✅ Test API endpoints
curl https://your-domain.com/api/v1/brand/

# ✅ Check application status
php artisan about

# ✅ View configured environment
php artisan config:show

# ✅ Check error logs
tail -20 storage/logs/laravel.log
```

---

## Emergency Contacts & Runbook

Create a deployment runbook with:

1. **Deployment Lead**: Who is responsible
2. **Rollback Contact**: Who to contact if something goes wrong
3. **Critical Commands**: Pre-tested rollback commands
4. **Monitoring**: Where to check system health
5. **Escalation**: Who to notify if serious issues occur

---

## References

- [Laravel Production Deployment](https://laravel.com/docs/12/deployment)
- [Web Server Configuration](https://laravel.com/docs/12/installation)
- [Database Backups](https://laravel.com/docs/12/database#introduction)
- [Queue Configuration](https://laravel.com/docs/12/queues)

---

**Questions?** Refer to [README.md](README.md), [SETUP.md](SETUP.md), or contact the DevOps team.

Last Updated: May 5, 2026
