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

# Systemd Deployment

> Deploy Posthoot as a system service using systemd

# Systemd Deployment

This guide covers deploying Posthoot as a system service using systemd. This approach is ideal for Linux servers where you want to run Posthoot as a native service with automatic startup and management.

## Prerequisites

Before you begin, ensure you have:

* **Linux system** with systemd (Ubuntu 16.04+, CentOS 7+, etc.)
* **Go 1.21+** installed
* **PostgreSQL 14+** installed and configured
* **Redis 6+** installed and configured
* **Git** for cloning the repository
* **Root or sudo access** for service installation

## Quick Start

### 1. Install Dependencies

#### Ubuntu/Debian

```bash theme={"dark"}
# Update package list
sudo apt update

# Install Go
sudo apt install golang-go

# Install PostgreSQL
sudo apt install postgresql postgresql-contrib

# Install Redis
sudo apt install redis-server

# Install Git
sudo apt install git
```

#### CentOS/RHEL

```bash theme={"dark"}
# Install Go
sudo yum install golang

# Install PostgreSQL
sudo yum install postgresql postgresql-server postgresql-contrib

# Install Redis
sudo yum install redis

# Install Git
sudo yum install git
```

### 2. Clone and Build

```bash theme={"dark"}
# Clone repository
git clone https://github.com/posthoot/posthoot-backend.git
cd posthoot-backend

# Build the application
go build -o posthoot cmd/main.go

# Move to system directory
sudo mv posthoot /usr/local/bin/
sudo chmod +x /usr/local/bin/posthoot
```

### 3. Create Service User

```bash theme={"dark"}
# Create posthoot user
sudo useradd -r -s /bin/false posthoot

# Create application directory
sudo mkdir -p /opt/posthoot
sudo chown posthoot:posthoot /opt/posthoot
```

### 4. Configure Environment

```bash theme={"dark"}
# Create configuration directory
sudo mkdir -p /etc/posthoot
sudo chown posthoot:posthoot /etc/posthoot

# Create environment file
sudo nano /etc/posthoot/posthoot.env
```

Add your configuration:

```env theme={"dark"}
# Server settings
SERVER_HOST=0.0.0.0
SERVER_PORT=9001
PUBLIC_URL=http://your-domain.com

# Database (PostgreSQL)
POSTGRES_HOST=localhost
POSTGRES_PORT=5432
POSTGRES_USER=posthoot_user
POSTGRES_PASSWORD=your_secure_password
POSTGRES_DB=posthoot
POSTGRES_SSLMODE=disable

# Security
JWT_SECRET=your_very_long_and_secure_jwt_secret_key_here

# Redis
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=your_redis_password
REDIS_DB=0

# Admin account
SUPERADMIN_EMAIL=admin@yourdomain.com
SUPERADMIN_PASSWORD=secure_admin_password
SUPERADMIN_NAME=Admin

# SMTP (for sending emails)
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=your-email@gmail.com
SMTP_PASSWORD=your-app-password
SMTP_FROM_EMAIL=noreply@yourdomain.com
SMTP_PROVIDER=GMAIL
```

### 5. Create Systemd Service

```bash theme={"dark"}
sudo nano /etc/systemd/system/posthoot.service
```

Add the service configuration:

```ini theme={"dark"}
[Unit]
Description=Posthoot Backend Service
After=network.target postgresql.service redis.service
Wants=postgresql.service redis.service

[Service]
Type=simple
User=posthoot
Group=posthoot
WorkingDirectory=/opt/posthoot
ExecStart=/usr/local/bin/posthoot
EnvironmentFile=/etc/posthoot/posthoot.env
Restart=always
RestartSec=5
StandardOutput=journal
StandardError=journal
SyslogIdentifier=posthoot

# Security settings
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/opt/posthoot /var/log/posthoot

# Resource limits
LimitNOFILE=65536
LimitNPROC=4096

[Install]
WantedBy=multi-user.target
```

### 6. Enable and Start Service

```bash theme={"dark"}
# Reload systemd
sudo systemctl daemon-reload

# Enable service
sudo systemctl enable posthoot

# Start service
sudo systemctl start posthoot

# Check status
sudo systemctl status posthoot
```

## Configuration

### Environment Variables

Key environment variables for systemd deployment:

| Variable            | Description         | Default     | Required |
| ------------------- | ------------------- | ----------- | -------- |
| `SERVER_HOST`       | Server bind address | `0.0.0.0`   | No       |
| `SERVER_PORT`       | Server port         | `9001`      | No       |
| `POSTGRES_HOST`     | Database host       | `localhost` | Yes      |
| `POSTGRES_USER`     | Database username   | -           | Yes      |
| `POSTGRES_PASSWORD` | Database password   | -           | Yes      |
| `POSTGRES_DB`       | Database name       | `posthoot`  | No       |
| `REDIS_HOST`        | Redis host          | `localhost` | No       |
| `REDIS_PASSWORD`    | Redis password      | -           | No       |
| `JWT_SECRET`        | JWT signing secret  | -           | Yes      |

### Service Configuration

The systemd service includes several security and performance settings:

* **User isolation**: Runs as dedicated `posthoot` user
* **File system protection**: Restricted access to system directories
* **Resource limits**: Increased file descriptor limits
* **Automatic restart**: Service restarts on failure
* **Dependencies**: Waits for PostgreSQL and Redis

### Logging Configuration

Configure log rotation:

```bash theme={"dark"}
sudo nano /etc/logrotate.d/posthoot
```

Add configuration:

```
/var/log/posthoot/*.log {
    daily
    missingok
    rotate 52
    compress
    delaycompress
    notifempty
    create 644 posthoot posthoot
    postrotate
        systemctl reload posthoot
    endscript
}
```

## Management

### Basic Commands

```bash theme={"dark"}
# Start service
sudo systemctl start posthoot

# Stop service
sudo systemctl stop posthoot

# Restart service
sudo systemctl restart posthoot

# Reload configuration
sudo systemctl reload posthoot

# Check status
sudo systemctl status posthoot

# Enable/disable auto-start
sudo systemctl enable posthoot
sudo systemctl disable posthoot
```

### Monitoring

```bash theme={"dark"}
# View logs
sudo journalctl -u posthoot -f

# View recent logs
sudo journalctl -u posthoot --since "1 hour ago"

# View error logs
sudo journalctl -u posthoot -p err

# Check service status
sudo systemctl is-active posthoot
sudo systemctl is-enabled posthoot
```

### Configuration Updates

```bash theme={"dark"}
# Update environment file
sudo nano /etc/posthoot/posthoot.env

# Reload service
sudo systemctl reload posthoot

# Or restart for major changes
sudo systemctl restart posthoot
```

## Database Setup

### PostgreSQL Configuration

```bash theme={"dark"}
# Switch to postgres user
sudo -u postgres psql

# Create database and user
CREATE DATABASE posthoot;
CREATE USER posthoot_user WITH PASSWORD 'your_secure_password';
GRANT ALL PRIVILEGES ON DATABASE posthoot TO posthoot_user;
\q
```

### Redis Configuration

```bash theme={"dark"}
# Edit Redis configuration
sudo nano /etc/redis/redis.conf

# Add/modify these settings
bind 127.0.0.1
requirepass your_redis_password
maxmemory 256mb
maxmemory-policy allkeys-lru

# Restart Redis
sudo systemctl restart redis
```

## Security

### Firewall Configuration

```bash theme={"dark"}
# Allow necessary ports
sudo ufw allow 22/tcp    # SSH
sudo ufw allow 80/tcp    # HTTP
sudo ufw allow 443/tcp   # HTTPS
sudo ufw allow 9001/tcp  # Posthoot API (if not behind proxy)
sudo ufw enable
```

### Service Security

The systemd service includes several security features:

* **NoNewPrivileges**: Prevents privilege escalation
* **PrivateTmp**: Isolated temporary directory
* **ProtectSystem**: Restricts file system access
* **ProtectHome**: Protects home directories
* **ReadWritePaths**: Only allows writing to specific paths

### File Permissions

```bash theme={"dark"}
# Set proper permissions
sudo chmod 600 /etc/posthoot/posthoot.env
sudo chown posthoot:posthoot /etc/posthoot/posthoot.env

# Create log directory
sudo mkdir -p /var/log/posthoot
sudo chown posthoot:posthoot /var/log/posthoot
```

## Reverse Proxy Setup

### Nginx Configuration

Create Nginx configuration:

```bash theme={"dark"}
sudo nano /etc/nginx/sites-available/posthoot
```

Add configuration:

```nginx theme={"dark"}
server {
    listen 80;
    server_name your-domain.com;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    server_name your-domain.com;

    ssl_certificate /path/to/your/certificate.crt;
    ssl_certificate_key /path/to/your/private.key;

    location / {
        proxy_pass http://localhost:9001;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        
        # Timeouts
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }
}
```

Enable the site:

```bash theme={"dark"}
sudo ln -s /etc/nginx/sites-available/posthoot /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx
```

## Monitoring and Logging

### Health Check

The service provides a health check endpoint:

```bash theme={"dark"}
# Test health endpoint
curl http://localhost:9001/health

# Expected response
{
  "status": "healthy",
  "version": "1.0.0",
  "time": "2024-01-01T12:00:00Z"
}
```

### Log Analysis

```bash theme={"dark"}
# View real-time logs
sudo journalctl -u posthoot -f

# Search for errors
sudo journalctl -u posthoot -p err

# View logs from specific time
sudo journalctl -u posthoot --since "2024-01-01 00:00:00"

# Export logs
sudo journalctl -u posthoot > posthoot.log
```

### Performance Monitoring

```bash theme={"dark"}
# Check resource usage
sudo systemctl show posthoot --property=MemoryCurrent,CPUUsageNSec

# Monitor system resources
htop
iotop
```

## Backup and Recovery

### Database Backup

Create backup script:

```bash theme={"dark"}
sudo nano /opt/scripts/backup-postgres.sh
```

Add content:

```bash theme={"dark"}
#!/bin/bash
BACKUP_DIR="/opt/backups/postgres"
DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="$BACKUP_DIR/posthoot_$DATE.sql"

mkdir -p $BACKUP_DIR

pg_dump -h localhost -U posthoot_user -d posthoot > $BACKUP_FILE

# Compress backup
gzip $BACKUP_FILE

# Keep only last 30 days
find $BACKUP_DIR -name "*.sql.gz" -mtime +30 -delete
```

Make executable:

```bash theme={"dark"}
sudo chmod +x /opt/scripts/backup-postgres.sh
```

### Automated Backups

Add to crontab:

```bash theme={"dark"}
sudo crontab -e

# Add this line for daily backups at 2 AM
0 2 * * * /opt/scripts/backup-postgres.sh
```

## Troubleshooting

### Common Issues

#### 1. Service Won't Start

```bash theme={"dark"}
# Check service status
sudo systemctl status posthoot

# View detailed logs
sudo journalctl -u posthoot -n 50

# Check configuration
sudo systemctl cat posthoot
```

#### 2. Database Connection Issues

```bash theme={"dark"}
# Check if PostgreSQL is running
sudo systemctl status postgresql

# Test connection
sudo -u postgres psql -d posthoot -c "SELECT 1;"

# Check PostgreSQL logs
sudo tail -f /var/log/postgresql/postgresql-*.log
```

#### 3. Permission Issues

```bash theme={"dark"}
# Check file permissions
ls -la /etc/posthoot/
ls -la /opt/posthoot/

# Fix permissions
sudo chown -R posthoot:posthoot /opt/posthoot
sudo chmod 600 /etc/posthoot/posthoot.env
```

#### 4. Port Already in Use

```bash theme={"dark"}
# Check what's using the port
sudo netstat -tlnp | grep :9001

# Kill the process
sudo kill -9 <PID>
```

### Debugging

```bash theme={"dark"}
# Run service in foreground
sudo systemctl stop posthoot
sudo -u posthoot /usr/local/bin/posthoot

# Check environment variables
sudo -u posthoot env

# Test configuration
sudo -u posthoot /usr/local/bin/posthoot --help
```

## Performance Tuning

### System Optimization

```bash theme={"dark"}
# Increase file descriptor limits
echo "posthoot soft nofile 65536" | sudo tee -a /etc/security/limits.conf
echo "posthoot hard nofile 65536" | sudo tee -a /etc/security/limits.conf

# Optimize PostgreSQL
sudo nano /etc/postgresql/*/main/postgresql.conf

# Add these settings
shared_buffers = 256MB
work_mem = 16MB
max_connections = 100
```

### Service Optimization

```bash theme={"dark"}
# Edit service file for performance
sudo nano /etc/systemd/system/posthoot.service

# Add performance settings
[Service]
# ... existing settings ...
LimitNOFILE=65536
LimitNPROC=4096
Nice=-10
IOSchedulingClass=1
IOSchedulingPriority=4
```

## Production Considerations

### High Availability

For production environments:

1. **Load balancer**: Use multiple instances behind a load balancer
2. **Database clustering**: Consider PostgreSQL clustering solutions
3. **Monitoring**: Implement comprehensive monitoring and alerting
4. **Backup strategy**: Regular backups with off-site storage

### Security Hardening

```bash theme={"dark"}
# Regular security updates
sudo apt update && sudo apt upgrade

# Configure firewall
sudo ufw enable

# Monitor system logs
sudo tail -f /var/log/auth.log

# Regular security audits
sudo apt install rkhunter
sudo rkhunter --update
sudo rkhunter --check
```

### Monitoring Setup

Install monitoring tools:

```bash theme={"dark"}
# Install monitoring tools
sudo apt install htop iotop nethogs

# Install log monitoring
sudo apt install logwatch
```

## Support

For systemd-specific issues:

1. Check systemd logs: `sudo journalctl -u posthoot`
2. Verify service configuration: `sudo systemctl cat posthoot`
3. Check dependencies: `sudo systemctl list-dependencies posthoot`
4. Review system logs: `sudo journalctl -xe`

## Next Steps

After successful deployment:

1. **Configure monitoring** and alerting
2. **Set up backups** and test recovery
3. **Implement security** best practices
4. **Plan scaling** strategies
5. **Document procedures** for your team
