Dify Security and Deployment SKILL
Overview
This SKILL provides a comprehensive guide to Dify platform security practices and deployment operations, helping developers and operators build a secure, stable, and high-performance production environment.
Trigger Scenarios
Use this SKILL when you need:
- 🚀 Deploy Dify to production (Docker/Kubernetes)
- 🔒 Configure security mechanisms (SSRF, sandbox, encryption)
- 🔧 Resolve deployment issues (container startup failures, network configuration, performance bottlenecks)
- 📊 Optimize production environments (monitoring, alerting, high availability, disaster recovery)
- ✅ Perform security audits and configuration validation
Core Capabilities
- Security: SSRF protection, code sandbox, data encryption, permission management
- Docker Deployment: Quick deployment, production configuration, network architecture, resource optimization
- Kubernetes Deployment: High-availability architecture, auto-scaling, Helm deployment
- Monitoring and Alerting: OpenTelemetry, Sentry, log aggregation, performance monitoring
- Disaster Recovery: Problem diagnosis, recovery procedures, backup strategies
Quick Start
Minimal Deployment Configuration
# 1. Clone the repository
git clone https://github.com/langgenius/dify.git
cd dify/docker
# 2. Copy environment variables
cp .env.example .env
# 3. Modify critical security settings
# Edit .env file:
SECRET_KEY=$(openssl rand -base64 42)
DB_PASSWORD=your-strong-password
REDIS_PASSWORD=your-redis-password
SANDBOX_API_KEY=$(openssl rand -base64 32)
# 4. Start services
docker compose up -d
# 5. Verify deployment
docker compose ps
curl http://localhost/health
Security Checklist
Pre-Deployment Checks
- SECRET_KEY changed to a strong key (use
openssl rand -base64 42) - Database password changed from default
- Redis password set
- SSRF Proxy configured to block internal network access
- Sandbox enabled with network proxy
- HTTPS/TLS certificate configured (production environments)
- API Key management mechanism enabled
- File upload limit set (UPLOAD_FILE_SIZE_LIMIT)
- Sensitive environment variables encrypted
Runtime Checks
- Container permissions running as non-root user
- Network isolation ssrf_proxy_network functioning correctly
- Health checks all services healthy
- Logging enabled and outputting normally
- Monitoring and alerting configured (OpenTelemetry/Sentry)
- Backup strategy implemented (database, file storage)
- Resource limits CPU/memory limits configured
- SSL certificate validity check and auto-renewal
Directory Structure
04-security/
├── SKILL.md # This file - Security and deployment overview
├── security/ # Security practices
│ ├── ssrf-protection.md # SSRF protection configuration
│ ├── sandbox.md # Code sandbox isolation
│ ├── encryption.md # Data encryption and TLS
│ └── auth.md # Authentication and permission management
├── deployment/ # Deployment guides
│ ├── docker-compose.md # Docker Compose deployment
│ ├── kubernetes.md # Kubernetes deployment
│ ├── serverless.md # Serverless deployment
│ └── high-availability.md # High-availability architecture
├── operations/ # Operations practices
│ ├── monitoring.md # Monitoring and alerting
│ ├── logging.md # Log management
│ ├── backup.md # Backup and recovery
│ └── troubleshooting.md # Troubleshooting
└── best-practices.md # Best practices summary
I. Security Mechanisms
1.1 SSRF Protection
Dify uses Squid proxy for SSRF (Server-Side Request Forgery) protection, preventing access to internal network addresses.
Core Configuration:
# squid.conf - Internal network address blacklist
acl localnet src 10.0.0.0/8
acl localnet src 172.16.0.0/12
acl localnet src 192.168.0.0/16
acl localnet src 127.0.0.0/8
# Deny access to internal networks
http_access deny localnet
# Allowed ports
acl Safe_ports port 80 443 1025-65535
http_access deny !Safe_ports
Verification Method:
# Test that internal network access is blocked
docker compose exec api curl -x http://ssrf_proxy:3128 http://127.0.0.1
# Should return 403 Forbidden
# Test that external access works
docker compose exec api curl -x http://ssrf_proxy:3128 https://api.openai.com
# Should return normally
📖 Detailed Documentation: security/ssrf-protection.md
1.2 Code Sandbox
The Sandbox service provides a secure code execution environment, isolating user code.
Core Configuration:
# config.yaml
app:
key: dify-sandbox # Change to a strong key
max_workers: 4
worker_timeout: 15
enable_network: true # Access external resources via SSRF Proxy
proxy:
http: 'http://ssrf_proxy:3128'
https: 'http://ssrf_proxy:3128'
Security Features:
- ✅ System call whitelist restrictions
- ✅ Resource quota management (CPU, memory, timeout)
- ✅ Network access via SSRF Proxy
- ✅ Filesystem isolation
📖 Detailed Documentation: security/sandbox.md
1.3 Data Encryption
Transmission Encryption (TLS/HTTPS):
# .env configuration
NGINX_HTTPS_ENABLED=true
NGINX_SSL_CERT_FILENAME=fullchain.pem
NGINX_SSL_CERT_KEY_FILENAME=privkey.pem
NGINX_SSL_PROTOCOLS=TLSv1.2 TLSv1.3
Database Connection Encryption:
# PostgreSQL SSL
DB_HOST=db_postgres
POSTGRES_SSL_MODE=require
# Redis SSL
REDIS_USE_SSL=true
REDIS_SSL_CERT_REQS=CERT_REQUIRED
📖 Detailed Documentation: security/encryption.md
1.4 Permission Management
API Key Management:
# Generate strong keys
SECRET_KEY=$(openssl rand -base64 42)
PLUGIN_DAEMON_KEY=$(openssl rand -base64 42)
PLUGIN_DIFY_INNER_API_KEY=$(openssl rand -base64 42)
OAuth 2.0 Integration:
- Supports third-party service authorization
- Access token auto-refresh
- Scope-based permission control
📖 Detailed Documentation: security/auth.md
II. Docker Deployment
2.1 Quick Deployment
One-Click Start:
cd dify/docker
cp .env.example .env
# Edit .env to change passwords and keys
docker compose up -d
Service Architecture:
nginx (80/443)
├── web (3000) - Frontend UI
├── api (5001) - Business logic
├── worker - Background tasks
├── beat - Scheduled tasks
├── plugin_daemon (5002) - Plugin management
└── sandbox (8194) - Code execution
Base services:
├── db_postgres (5432) - Main database
├── redis (6379) - Cache and queue
├── weaviate (8080) - Vector database
└── ssrf_proxy (3128) - SSRF protection
📖 Detailed Documentation: deployment/docker-compose.md
2.2 Production-Grade Configuration
Resource Limits:
# docker-compose.yaml
services:
api:
deploy:
resources:
limits:
cpus: '2'
memory: 4G
reservations:
cpus: '1'
memory: 2G
Health Checks:
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:5001/health"]
interval: 30s
timeout: 10s
retries: 3
start_period: 40s
Log Management:
logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "3"
📖 Detailed Documentation: deployment/docker-compose.md
2.3 Network Architecture
Network Isolation:
networks:
# Internal network - cannot access external resources
ssrf_proxy_network:
driver: bridge
internal: true
# Default network - can access external resources
default:
driver: bridge
Service Communication:
- API/Worker/Sandbox → ssrf_proxy → External API
- Nginx → API/Web (reverse proxy)
- API → Database/Redis (internal communication)
📖 Detailed Documentation: deployment/docker-compose.md
III. Kubernetes Deployment
3.1 Helm Quick Deployment
# Add Helm repository
helm repo add dify https://borispolonsky.github.io/dify-helm
helm repo update
# Install Dify
helm install my-dify dify/dify \
--set postgresql.enabled=true \
--set redis.enabled=true \
--set weaviate.enabled=true
# View status
kubectl get pods -l app.kubernetes.io/name=dify
3.2 High-Availability Architecture
Multi-Replica Deployment:
# values.yaml
api:
replicaCount: 3
resources:
limits:
cpu: 2000m
memory: 4Gi
requests:
cpu: 1000m
memory: 2Gi
worker:
replicaCount: 2
autoscaling:
enabled: true
minReplicas: 2
maxReplicas: 10
targetCPUUtilizationPercentage: 80
Pod Anti-Affinity:
affinity:
podAntiAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
podAffinityTerm:
labelSelector:
matchExpressions:
- key: app
operator: In
values:
- dify-api
topologyKey: kubernetes.io/hostname
📖 Detailed Documentation: deployment/kubernetes.md
3.3 Managed Service Integration
Using Cloud Managed Services:
# Using RDS PostgreSQL
postgresql:
enabled: false
externalDatabase:
host: your-rds-endpoint.rds.amazonaws.com
port: 5432
database: dify
username: dify
password: your-password
# Using ElastiCache Redis
redis:
enabled: false
externalRedis:
host: your-redis.cache.amazonaws.com
port: 6379
password: your-password
Benefits:
- ✅ Automated backup and recovery
- ✅ High availability and failover
- ✅ Performance monitoring and optimization
- ✅ Reduced operational burden
📖 Detailed Documentation: deployment/high-availability.md
IV. Monitoring and Alerting
4.1 OpenTelemetry Configuration
# .env
ENABLE_OTEL=true
OTLP_BASE_ENDPOINT=http://otel-collector:4318
OTEL_SAMPLING_RATE=0.1
OTEL_BATCH_EXPORT_SCHEDULE_DELAY=5000
OTEL_MAX_QUEUE_SIZE=2048
OTEL_METRIC_EXPORT_INTERVAL=60000
Monitoring Metrics:
- Request latency and throughput
- Error rate and success rate
- Resource usage (CPU, memory, disk)
- Database connection pool status
- Queue depth and processing speed
4.2 Sentry Error Tracking
# .env
API_SENTRY_DSN=https://[email protected]/project-id
API_SENTRY_TRACES_SAMPLE_RATE=1.0
WEB_SENTRY_DSN=https://[email protected]/project-id
PLUGIN_SENTRY_ENABLED=true
4.3 Log Aggregation
# Log configuration
LOG_LEVEL=INFO
LOG_OUTPUT_FORMAT=json
LOG_FILE=/app/logs/server.log
LOG_FILE_MAX_SIZE=20
LOG_FILE_BACKUP_COUNT=5
Log Viewing:
# Docker
docker compose logs -f api
docker compose logs --tail=100 worker
# Kubernetes
kubectl logs -f deployment/dify-api
kubectl logs -l app=dify-worker --tail=100
📖 Detailed Documentation: operations/monitoring.md
4.4 Queue Monitoring
# .env
QUEUE_MONITOR_THRESHOLD=200
[email protected],[email protected]
QUEUE_MONITOR_INTERVAL=30
ENABLE_DATASETS_QUEUE_MONITOR=true
V. Troubleshooting
5.1 Common Issues
Container Startup Failure
Symptom: Containers restart repeatedly or fail to start
Diagnosis:
# View container status
docker compose ps
# View logs
docker compose logs api
# Check health status
docker compose exec api curl http://localhost:5001/health
Common Causes:
-
Database connection failure
# Check database docker compose exec db_postgres pg_isready # Verify connection docker compose exec api env | grep DB_ -
Dependent services not ready
# Check depends_on configuration depends_on: db_postgres: condition: service_healthy -
Environment variable configuration errors
# Verify required variables docker compose config | grep -E "SECRET_KEY|DB_PASSWORD"
Network Connectivity Issues
Symptom: Unable to access external APIs or internal services
Diagnosis:
# Test SSRF Proxy
docker compose exec api curl -x http://ssrf_proxy:3128 https://api.openai.com
# Test internal services
docker compose exec api curl http://redis:6379
docker compose exec api curl http://db_postgres:5432
Performance Issues
Symptom: Slow response, timeouts, resource exhaustion
Diagnosis:
# View resource usage
docker stats
# View database connections
docker compose exec db_postgres psql -U postgres -d dify -c "SELECT count(*) FROM pg_stat_activity;"
# View Redis memory
docker compose exec redis redis-cli INFO memory
📖 Detailed Documentation: operations/troubleshooting.md
5.2 Disaster Recovery Procedures
Database Failure
# 1. Check status
docker compose ps db_postgres
# 2. View logs
docker compose logs db_postgres
# 3. Restart service
docker compose restart db_postgres
# 4. Verify connection
docker compose exec db_postgres pg_isready
# 5. Check data integrity
docker compose exec db_postgres psql -U postgres -d dify -c "SELECT count(*) FROM accounts;"
Service Restart Order
# 1. Base services
docker compose restart db_postgres redis
# 2. Core services
docker compose restart api worker beat
# 3. Frontend services
docker compose restart web nginx
# 4. Verification
docker compose ps
curl http://localhost/health
📖 Detailed Documentation: operations/backup.md
VI. Best Practices
6.1 Security Best Practices
-
Regularly rotate keys
- Rotate SECRET_KEY every 90 days
- Use key management services (AWS KMS, HashiCorp Vault)
-
Principle of least privilege
- Run containers as non-root users
- Grant database users only necessary permissions
-
Network isolation
- Use internal networks to isolate sensitive services
- Control external access via SSRF Proxy
-
Audit logs
- Enable detailed logging
- Regularly review access logs and error logs
6.2 Deployment Best Practices
-
Environment separation
- Keep development, testing, and production environments separate
- Use different configurations and keys
-
Automated deployment
- Use CI/CD pipelines
- Automated testing and validation
-
Version control
- Version configuration files (exclude sensitive information)
- Use Git to manage infrastructure code
-
Monitoring and alerting
- Configure comprehensive monitoring metrics
- Set reasonable alert thresholds
6.3 Operations Best Practices
-
Backup strategy
- Daily automated database backups
- Regularly test recovery procedures
-
Capacity planning
- Monitor resource usage trends
- Scale up proactively to avoid performance issues
-
Documentation maintenance
- Record configuration changes
- Maintain an operations manual
-
Incident response
- Establish incident response procedures
- Regularly practice recovery scenarios
📖 Detailed Documentation: best-practices.md
VII. Configuration Templates
7.1 Development Environment Template
# .env.development
DEBUG=true
LOG_LEVEL=DEBUG
MIGRATION_ENABLED=true
# Use default passwords (development environment only)
DB_PASSWORD=difyai123456
REDIS_PASSWORD=difyai123456
# Disable HTTPS
NGINX_HTTPS_ENABLED=false
7.2 Production Environment Template
# .env.production
DEBUG=false
LOG_LEVEL=INFO
DEPLOY_ENV=PRODUCTION
# Strong keys (must modify)
SECRET_KEY=$(openssl rand -base64 42)
DB_PASSWORD=<strong-password>
REDIS_PASSWORD=<strong-password>
# Enable HTTPS
NGINX_HTTPS_ENABLED=true
NGINX_SSL_CERT_FILENAME=fullchain.pem
NGINX_SSL_CERT_KEY_FILENAME=privkey.pem
# Enable monitoring
ENABLE_OTEL=true
API_SENTRY_DSN=<your-sentry-dsn>
7.3 High-Availability Template
# docker-compose.ha.yaml
services:
api:
deploy:
replicas: 3
resources:
limits:
cpus: '2'
memory: 4G
restart_policy:
condition: on-failure
max_attempts: 3
worker:
deploy:
replicas: 2
resources:
limits:
cpus: '4'
memory: 8G
VIII. References
Official Documentation
Community Resources
Related SKILLs
- 01-workflow - Workflow Design
- 02-plugin - Plugin Development
- 03-performance - Performance Optimization
Quick Command Reference
# Docker deployment
docker compose up -d # Start all services
docker compose ps # View service status
docker compose logs -f api # View API logs
docker compose restart api # Restart API service
docker compose down # Stop all services
# Health checks
curl http://localhost/health # Check service health
docker compose exec db_postgres pg_isready # Check database
docker compose exec redis redis-cli ping # Check Redis
# Log viewing
docker compose logs --tail=100 api # View last 100 log lines
docker compose logs -f worker # View worker logs in real-time
# Database operations
docker compose exec db_postgres psql -U postgres -d dify # Connect to database
docker compose exec db_postgres pg_dump -U postgres dify > backup.sql # Backup
# Kubernetes
kubectl get pods -l app=dify # View Pod status
kubectl logs -f deployment/dify-api # View logs
kubectl describe pod <pod-name> # View Pod details
kubectl exec -it <pod-name> -- /bin/bash # Enter container
Version: 1.0.0 Last Updated: 2026-03-04 Maintainer: Dify SKILL Team