PVC (Persistent Volume Claims)

PandaStack PVC (Persistent Volume Claims) Documentation

What are PVCs?

PVC (Persistent Volume Claims) are storage resources that provide persistent data storage for your applications. Unlike temporary container storage that gets deleted when containers restart, PVCs ensure your data persists across deployments, scaling events, and container restarts.

How PVCs Work

Data Persistence: PVCs create dedicated storage volumes that remain intact even when your application containers are destroyed or recreated during deployments or scaling operations.

Shared Storage: Multiple container instances can access the same PVC, enabling shared file systems and data synchronization across scaled applications.

Automatic Mounting: PVCs are automatically mounted to your containers at specified mount points, making them accessible to your application code.

Backup and Recovery: PVC data is included in PandaStack's backup systems, providing data protection and recovery capabilities.

Available Storage Options

Based on the PandaStack interface, you can configure PVCs with the following storage sizes:

  • 0.5 GB - Suitable for small configuration files, logs, or cache data

  • 1 GB - Good for small databases, user uploads, or session storage

  • 2 GB - Ideal for medium-sized applications with moderate data needs

  • 3 GB - Perfect for larger applications with substantial data requirements

  • 5 GB - Suitable for data-heavy applications or file storage systems

  • Custom sizes - Available for enterprise requirements

Common Use Cases

File Uploads and User Content

Maintain user-uploaded files, images, and documents.

yaml

# Example: Web application with file uploads
volumes:
  - name: user-uploads
    size: 5 GB
    mount_path: /app/uploads

Application Logs

Store application logs for debugging and monitoring.

yaml

# Example: Log storage
volumes:
  - name: app-logs
    size: 1 GB
    mount_path: /var/log/app

Cache and Session Data

Maintain cache files and session data for better performance.

yaml

# Example: Redis cache storage
volumes:
  - name: redis-data
    size: 0.5 GB
    mount_path: /data

How to Use PVCs in Your Application

Step 1: Configure PVC in PandaStack Dashboard

  1. Navigate to your service configuration

  2. Scroll to the "PVC Disk" section

  3. Select your desired storage size from the dropdown

  4. The system will automatically provision the persistent volume

Step 2: Access PVC Data in Your Code

Once configured, your PVC is automatically mounted to your container. Here's how to use it in different programming languages:

Python Example

python

import os

# Write data to persistent storage
def save_user_data(user_id, data):
    pvc_path = "/app/persistent-data"
    os.makedirs(pvc_path, exist_ok=True)
    
    with open(f"{pvc_path}/user_{user_id}.json", "w") as f:
        json.dump(data, f)

# Read data from persistent storage
def load_user_data(user_id):
    pvc_path = "/app/persistent-data"
    file_path = f"{pvc_path}/user_{user_id}.json"
    
    if os.path.exists(file_path):
        with open(file_path, "r") as f:
            return json.load(f)
    return None

Node.js Example

javascript

const fs = require('fs');
const path = require('path');

// Write data to persistent storage
function saveUserData(userId, data) {
    const pvcPath = '/app/persistent-data';
    const filePath = path.join(pvcPath, `user_${userId}.json`);
    
    // Ensure directory exists
    fs.mkdirSync(pvcPath, { recursive: true });
    
    fs.writeFileSync(filePath, JSON.stringify(data, null, 2));
}

// Read data from persistent storage
function loadUserData(userId) {
    const pvcPath = '/app/persistent-data';
    const filePath = path.join(pvcPath, `user_${userId}.json`);
    
    if (fs.existsSync(filePath)) {
        const rawData = fs.readFileSync(filePath, 'utf8');
        return JSON.parse(rawData);
    }
    return null;
}

Step 3: Handle Data in Auto-Scaling Scenarios

When your application auto-scales, all instances share the same PVC. Consider these best practices:

File Locking for Concurrent Access

python

import fcntl

def write_to_shared_storage(data):
    with open('/app/persistent-data/shared.json', 'w') as f:
        fcntl.flock(f.fileno(), fcntl.LOCK_EX)  # Exclusive lock
        json.dump(data, f)
        fcntl.flock(f.fileno(), fcntl.LOCK_UN)  # Release lock

Instance-Specific Data Organization

python

import os
import socket

def get_instance_data_path():
    hostname = socket.gethostname()
    instance_path = f"/app/persistent-data/instances/{hostname}"
    os.makedirs(instance_path, exist_ok=True)
    return instance_path

Best Practices

Data Organization

Structure your persistent data logically with clear folder hierarchies:

/app/persistent-data/
├── user-uploads/
├── database/
├── cache/
└── logs/

Backup Strategy

While PandaStack handles infrastructure backups, implement application-level data export:

python

def export_data_backup():
    backup_data = {
        'users': load_all_users(),
        'settings': load_app_settings(),
        'timestamp': datetime.now().isoformat()
    }
    
    with open('/app/persistent-data/backup.json', 'w') as f:
        json.dump(backup_data, f)

Performance Considerations

  • Use PVCs for data that truly needs persistence

  • Consider caching frequently accessed data in memory

  • Implement proper error handling for disk I/O operations

  • Monitor storage usage to avoid running out of space

Security

  • Never store sensitive data in plain text

  • Implement proper file permissions

  • Use encryption for sensitive persistent data

  • Regularly rotate and update stored credentials

Monitoring and Troubleshooting

Check Storage Usage

bash

# In your application container
df -h /app/persistent-data

Monitor File System Operations

python

import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def safe_write_to_pvc(data, filename):
    try:
        pvc_path = "/app/persistent-data"
        file_path = f"{pvc_path}/{filename}"
        
        with open(file_path, 'w') as f:
            json.dump(data, f)
        
        logger.info(f"Successfully wrote data to {file_path}")
        return True
    except Exception as e:
        logger.error(f"Failed to write to PVC: {e}")
        return False

Pricing

PVC storage is included in your PandaStack plan limits. Additional storage beyond plan limits incurs standard storage fees as outlined in your PandaStack pricing tier.

Last updated