> ## Documentation Index
> Fetch the complete documentation index at: https://docs.sagozen.digital/llms.txt
> Use this file to discover all available pages before exploring further.

# Deployment Guide

> Deploy Pet Service Management System using Docker, Railway, or cloud platforms

# Deployment Guide

This guide covers multiple deployment strategies for the Pet Service Management System.

<CardGroup cols={3}>
  <Card title="Docker" icon="docker">
    Containerized deployment
  </Card>

  <Card title="Railway" icon="train">
    One-click deployment with Railway MCP
  </Card>

  <Card title="Cloud Platforms" icon="cloud">
    AWS, GCP, Vercel
  </Card>
</CardGroup>

***

## Docker Deployment

### Prerequisites

* Docker 20.10+
* Docker Compose 2.0+

### Step 1: Build Docker Images

Create a `Dockerfile` in the root directory:

<CodeGroup>
  ```dockerfile Backend Dockerfile theme={null}
  # backend/Dockerfile
  FROM node:18-alpine AS builder

  WORKDIR /app

  # Copy package files
  COPY package*.json ./
  COPY prisma ./prisma/

  # Install dependencies
  RUN npm ci

  # Copy source code
  COPY . .

  # Generate Prisma client
  RUN npx prisma generate

  # Build application
  RUN npm run build

  # Production stage
  FROM node:18-alpine

  WORKDIR /app

  # Copy built files
  COPY --from=builder /app/node_modules ./node_modules
  COPY --from=builder /app/dist ./dist
  COPY --from=builder /app/prisma ./prisma
  COPY --from=builder /app/package*.json ./

  # Expose port
  EXPOSE 3001

  # Start application
  CMD ["npm", "run", "start:prod"]
  ```

  ```dockerfile Frontend Dockerfile theme={null}
  # frontend/Dockerfile
  FROM node:18-alpine AS builder

  WORKDIR /app

  # Copy package files
  COPY package*.json ./

  # Install dependencies
  RUN npm ci

  # Copy source code
  COPY . .

  # Build application
  RUN npm run build

  # Production stage
  FROM node:18-alpine

  WORKDIR /app

  # Install production dependencies only
  COPY package*.json ./
  RUN npm ci --only=production

  # Copy built files
  COPY --from=builder /app/.next ./.next
  COPY --from=builder /app/public ./public
  COPY --from=builder /app/next.config.ts ./

  # Expose port
  EXPOSE 3000

  # Start application
  CMD ["npm", "start"]
  ```
</CodeGroup>

### Step 2: Docker Compose Configuration

Create `docker-compose.yml` in the root directory:

```yaml docker-compose.yml theme={null}
version: '3.8'

services:
  postgres:
    image: postgres:15-alpine
    container_name: petservice-db
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: postgres
      POSTGRES_DB: petservice
    volumes:
      - postgres_data:/var/lib/postgresql/data
    ports:
      - "5432:5432"
    networks:
      - petservice-network
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 10s
      timeout: 5s
      retries: 5

  backend:
    build:
      context: ./backend
      dockerfile: Dockerfile
    container_name: petservice-backend
    environment:
      NODE_ENV: production
      PORT: 3001
      DATABASE_URL: postgresql://postgres:postgres@postgres:5432/petservice
      BETTER_AUTH_URL: http://backend:3001/api/auth
      BETTER_AUTH_SECRET: ${BETTER_AUTH_SECRET}
      SESSION_SECRET: ${SESSION_SECRET}
      JWT_SECRET: ${JWT_SECRET}
      FRONTEND_URL: http://frontend:3000
    ports:
      - "3001:3001"
    depends_on:
      postgres:
        condition: service_healthy
    networks:
      - petservice-network
    command: >
      sh -c "npx prisma migrate deploy &&
             npm run start:prod"

  frontend:
    build:
      context: ./frontend
      dockerfile: Dockerfile
    container_name: petservice-frontend
    environment:
      NEXT_PUBLIC_API_URL: http://localhost:3001
      NEXT_PUBLIC_APP_URL: http://localhost:3000
    ports:
      - "3000:3000"
    depends_on:
      - backend
    networks:
      - petservice-network

volumes:
  postgres_data:

networks:
  petservice-network:
    driver: bridge
```

### Step 3: Environment Configuration

Create `.env` file in the root directory:

```bash .env theme={null}
# Secrets (Generate with: openssl rand -base64 32)
BETTER_AUTH_SECRET=your-32-char-secret-here
SESSION_SECRET=your-32-char-secret-here
JWT_SECRET=your-32-char-secret-here

# Database
POSTGRES_USER=postgres
POSTGRES_PASSWORD=postgres
POSTGRES_DB=petservice
```

<Warning>
  **Security:** Never commit `.env` to version control. Use `.env.example` as template.
</Warning>

### Step 4: Build and Run

<Steps>
  <Step title="Build Images">
    ```bash theme={null}
    docker-compose build
    ```
  </Step>

  <Step title="Start Services">
    ```bash theme={null}
    docker-compose up -d
    ```
  </Step>

  <Step title="Verify Services">
    ```bash theme={null}
    # Check running containers
    docker-compose ps

    # View logs
    docker-compose logs -f backend
    docker-compose logs -f frontend
    ```
  </Step>

  <Step title="Access Application">
    * Frontend: `http://localhost:3000`
    * Backend API: `http://localhost:3001`
    * Prisma Studio: `docker-compose exec backend npx prisma studio`
  </Step>
</Steps>

### Docker Management Commands

<CodeGroup>
  ```bash Start Services theme={null}
  docker-compose up -d
  ```

  ```bash Stop Services theme={null}
  docker-compose down
  ```

  ```bash View Logs theme={null}
  docker-compose logs -f [service_name]
  ```

  ```bash Restart Service theme={null}
  docker-compose restart backend
  ```

  ```bash Rebuild Images theme={null}
  docker-compose build --no-cache
  ```

  ```bash Execute Commands theme={null}
  docker-compose exec backend npm run prisma:migrate
  ```

  ```bash Clean Up theme={null}
  docker-compose down -v  # Remove volumes
  docker system prune -a  # Remove unused images
  ```
</CodeGroup>

***

## Railway Deployment

<Note>
  Railway provides automatic deployments with built-in PostgreSQL and zero-config setup.
</Note>

### Option 1: Deploy via Railway CLI

<Steps>
  <Step title="Install Railway CLI">
    ```bash theme={null}
    npm install -g @railway/cli
    ```
  </Step>

  <Step title="Login to Railway">
    ```bash theme={null}
    railway login
    ```
  </Step>

  <Step title="Initialize Project">
    ```bash theme={null}
    railway init
    ```
  </Step>

  <Step title="Add PostgreSQL Database">
    ```bash theme={null}
    railway add postgresql
    ```

    Railway automatically sets `DATABASE_URL` environment variable.
  </Step>

  <Step title="Set Environment Variables">
    ```bash theme={null}
    railway variables set BETTER_AUTH_SECRET=$(openssl rand -base64 32)
    railway variables set SESSION_SECRET=$(openssl rand -base64 32)
    railway variables set JWT_SECRET=$(openssl rand -base64 32)
    railway variables set NODE_ENV=production
    railway variables set FRONTEND_URL=https://your-app.railway.app
    ```
  </Step>

  <Step title="Deploy Backend">
    ```bash theme={null}
    cd backend
    railway up
    ```
  </Step>

  <Step title="Deploy Frontend">
    ```bash theme={null}
    cd frontend
    railway up
    ```
  </Step>

  <Step title="Run Migrations">
    ```bash theme={null}
    railway run npx prisma migrate deploy
    ```
  </Step>
</Steps>

### Option 2: Deploy via Railway Button

<Card title="Deploy to Railway" icon="train" href="https://railway.app/new">
  Click to deploy with one button
</Card>

1. Click "Deploy on Railway" button
2. Connect your GitHub repository
3. Railway auto-detects backend/frontend
4. Add PostgreSQL database from Railway marketplace
5. Set environment variables in Railway dashboard
6. Deploy automatically on git push

### Railway Environment Variables

Set these in Railway dashboard or CLI:

| Variable             | Value                          | Notes                 |
| -------------------- | ------------------------------ | --------------------- |
| `NODE_ENV`           | `production`                   | Environment mode      |
| `DATABASE_URL`       | Auto-set by Railway            | PostgreSQL connection |
| `BETTER_AUTH_SECRET` | Generate 32+ chars             | Auth secret           |
| `SESSION_SECRET`     | Generate 32+ chars             | Session encryption    |
| `JWT_SECRET`         | Generate 32+ chars             | JWT signing           |
| `FRONTEND_URL`       | `https://your-app.railway.app` | Frontend URL          |
| `PORT`               | `3001` (backend)               | Service port          |

### Railway MCP Integration

<Info>
  Railway MCP (Model Context Protocol) enables AI assistants to manage your deployments.
</Info>

**Configure Railway MCP:**

1. Install Railway MCP server:

```bash theme={null}
npm install -g @railway/mcp
```

2. Configure in your Claude Code settings:

```json theme={null}
{
  "mcpServers": {
    "railway": {
      "command": "railway-mcp",
      "env": {
        "RAILWAY_TOKEN": "your-railway-token"
      }
    }
  }
}
```

3. Use AI commands:

```
Claude: "Deploy backend to Railway"
Claude: "Check Railway deployment status"
Claude: "View Railway logs for backend service"
Claude: "Add PostgreSQL to Railway project"
```

***

## Cloud Platform Deployment

### Vercel (Frontend)

<Steps>
  <Step title="Install Vercel CLI">
    ```bash theme={null}
    npm install -g vercel
    ```
  </Step>

  <Step title="Deploy Frontend">
    ```bash theme={null}
    cd frontend
    vercel
    ```
  </Step>

  <Step title="Set Environment Variables">
    ```bash theme={null}
    vercel env add NEXT_PUBLIC_API_URL
    vercel env add NEXT_PUBLIC_APP_URL
    ```
  </Step>

  <Step title="Production Deployment">
    ```bash theme={null}
    vercel --prod
    ```
  </Step>
</Steps>

### Heroku (Backend)

<Steps>
  <Step title="Install Heroku CLI">
    ```bash theme={null}
    brew install heroku/brew/heroku
    ```
  </Step>

  <Step title="Create Heroku App">
    ```bash theme={null}
    cd backend
    heroku create petservice-backend
    ```
  </Step>

  <Step title="Add PostgreSQL">
    ```bash theme={null}
    heroku addons:create heroku-postgresql:mini
    ```
  </Step>

  <Step title="Set Environment Variables">
    ```bash theme={null}
    heroku config:set BETTER_AUTH_SECRET=$(openssl rand -base64 32)
    heroku config:set SESSION_SECRET=$(openssl rand -base64 32)
    heroku config:set JWT_SECRET=$(openssl rand -base64 32)
    heroku config:set NODE_ENV=production
    ```
  </Step>

  <Step title="Deploy">
    ```bash theme={null}
    git push heroku main
    ```
  </Step>

  <Step title="Run Migrations">
    ```bash theme={null}
    heroku run npx prisma migrate deploy
    ```
  </Step>
</Steps>

### AWS (Full Stack)

<Tabs>
  <Tab title="Frontend on S3 + CloudFront">
    ```bash theme={null}
    # Build frontend
    cd frontend
    npm run build

    # Deploy to S3
    aws s3 sync .next/static s3://your-bucket/static
    aws cloudfront create-invalidation --distribution-id XXX --paths "/*"
    ```
  </Tab>

  <Tab title="Backend on EC2">
    ```bash theme={null}
    # SSH to EC2
    ssh -i key.pem ec2-user@your-ec2-ip

    # Install dependencies
    sudo yum update
    sudo yum install nodejs npm postgresql

    # Clone and setup
    git clone your-repo
    cd backend
    npm install
    npm run build

    # Setup PM2
    npm install -g pm2
    pm2 start dist/main.js --name petservice-backend
    pm2 save
    pm2 startup
    ```
  </Tab>

  <Tab title="Database on RDS">
    ```bash theme={null}
    # Create RDS PostgreSQL instance via AWS Console
    # Update DATABASE_URL with RDS endpoint
    DATABASE_URL=postgresql://user:pass@rds-endpoint:5432/petservice
    ```
  </Tab>
</Tabs>

***

## Production Checklist

<AccordionGroup>
  <Accordion title="Security">
    * [ ] HTTPS/TLS enabled (use Let's Encrypt or cloud provider SSL)
    * [ ] Strong secrets (32+ characters, randomly generated)
    * [ ] Environment variables properly set (no hardcoded secrets)
    * [ ] CORS configured for specific origins
    * [ ] Rate limiting enabled on API endpoints
    * [ ] Database backups configured (daily/hourly)
    * [ ] Security headers configured (Helmet.js)
  </Accordion>

  <Accordion title="Performance">
    * [ ] CDN configured for static assets
    * [ ] Database connection pooling enabled
    * [ ] Query optimization with proper indexes
    * [ ] Caching strategy implemented (Redis optional)
    * [ ] Image optimization enabled
    * [ ] Gzip compression enabled
  </Accordion>

  <Accordion title="Monitoring">
    * [ ] Application logging configured
    * [ ] Error tracking (Sentry, LogRocket)
    * [ ] Uptime monitoring (UptimeRobot, Pingdom)
    * [ ] Performance monitoring (New Relic, DataDog)
    * [ ] Database monitoring (pgAdmin, Railway analytics)
  </Accordion>

  <Accordion title="Database">
    * [ ] Production database created
    * [ ] Migrations applied: `npx prisma migrate deploy`
    * [ ] Seed data loaded (if needed)
    * [ ] Backup strategy configured
    * [ ] Connection pool configured
    * [ ] Indexes optimized
  </Accordion>

  <Accordion title="Environment">
    * [ ] `NODE_ENV=production` set
    * [ ] All required environment variables configured
    * [ ] Frontend API URL points to production backend
    * [ ] Backend CORS allows production frontend
    * [ ] Email service configured (SMTP credentials)
  </Accordion>
</AccordionGroup>

***

## Continuous Deployment

### GitHub Actions

Create `.github/workflows/deploy.yml`:

```yaml theme={null}
name: Deploy to Production

on:
  push:
    branches: [main]

jobs:
  deploy-backend:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v3
        with:
          node-version: 18

      - name: Install dependencies
        working-directory: backend
        run: npm ci

      - name: Build
        working-directory: backend
        run: npm run build

      - name: Deploy to Railway
        run: |
          npm install -g @railway/cli
          railway up --service backend
        env:
          RAILWAY_TOKEN: ${{ secrets.RAILWAY_TOKEN }}

  deploy-frontend:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v3
        with:
          node-version: 18

      - name: Install dependencies
        working-directory: frontend
        run: npm ci

      - name: Build
        working-directory: frontend
        run: npm run build

      - name: Deploy to Vercel
        run: vercel --prod --token ${{ secrets.VERCEL_TOKEN }}
```

***

## Monitoring & Maintenance

### Health Checks

```bash theme={null}
# Backend health
curl https://api.yourapp.com/health

# Database connection
curl https://api.yourapp.com/db/health

# Frontend
curl https://yourapp.com
```

### View Logs

<Tabs>
  <Tab title="Docker">
    ```bash theme={null}
    docker-compose logs -f backend
    docker-compose logs -f frontend
    ```
  </Tab>

  <Tab title="Railway">
    ```bash theme={null}
    railway logs
    railway logs --service backend
    ```
  </Tab>

  <Tab title="Heroku">
    ```bash theme={null}
    heroku logs --tail --app petservice-backend
    ```
  </Tab>
</Tabs>

### Database Backup

<CodeGroup>
  ```bash Manual Backup theme={null}
  # PostgreSQL dump
  pg_dump -h localhost -U postgres petservice > backup.sql

  # Restore
  psql -h localhost -U postgres petservice < backup.sql
  ```

  ```bash Railway Backup theme={null}
  railway backup create
  railway backup list
  railway backup restore backup-id
  ```

  ```bash Docker Backup theme={null}
  docker-compose exec postgres pg_dump -U postgres petservice > backup.sql
  ```
</CodeGroup>

***

## Troubleshooting

<AccordionGroup>
  <Accordion title="Deployment Fails">
    **Solution:**

    * Check build logs: `railway logs` or `docker-compose logs`
    * Verify environment variables are set
    * Ensure dependencies are installed: `npm ci`
    * Check Dockerfile syntax
  </Accordion>

  <Accordion title="Database Connection Error">
    **Solution:**

    * Verify `DATABASE_URL` is correct
    * Check database is running
    * Confirm firewall rules allow connection
    * Test connection: `psql $DATABASE_URL`
  </Accordion>

  <Accordion title="CORS Errors">
    **Solution:**

    * Set `FRONTEND_URL` in backend environment
    * Verify CORS configuration in `main.ts`
    * Check frontend uses correct API URL
  </Accordion>

  <Accordion title="SSL/HTTPS Issues">
    **Solution:**

    * Use Railway/Vercel automatic SSL
    * For custom domains, configure SSL certificate
    * Use Let's Encrypt for free SSL: `certbot`
  </Accordion>
</AccordionGroup>

***

## Next Steps

<CardGroup cols={2}>
  <Card title="Architecture Overview" icon="diagram-project" href="/architecture">
    Understand system design
  </Card>

  <Card title="API Reference" icon="code" href="/api-reference/introduction">
    Explore REST endpoints
  </Card>

  <Card title="Installation Guide" icon="download" href="/installation">
    Set up development environment
  </Card>

  <Card title="Back to Home" icon="home" href="/">
    Return to homepage
  </Card>
</CardGroup>

***

<Check>
  **Deployment Complete!** Your Pet Service Management System is now live.
</Check>
