find "$BACKUP_DIR" -name ".env.backup.production.*" -mtime +30 -delete
Additionally, integrate this into your CI/CD pipeline. Every successful deployment that changes environment variables should automatically trigger a backup before the mutation.
# .github/workflows/deploy.yml (excerpt)
- name: Backup production env before deploy
run: |
ssh production-server "cp .env.production .env.backup.production.pre-deploy-$(date +%s)"
CACHE_DRIVER=redis SESSION_DRIVER=redis QUEUE_CONNECTION=redis
STRIPE_KEY=pk_live_your_key STRIPE_SECRET=sk_live_your_key AWS_ACCESS_KEY_ID=YOUR_AWS_ID AWS_SECRET_ACCESS_KEY=YOUR_AWS_SECRET AWS_DEFAULT_REGION=us-east-1 AWS_BUCKET=prod-assets-bucket Use code with caution. Copied to clipboard Critical Security Best Practices Restrict Access : Ensure this file is added to your .gitignore to prevent it from being pushed to public repositories. Permissions
: On your production server, restrict file permissions to the application user only (e.g., chmod 600 .env.backup.production
: For disaster recovery, store an encrypted copy of this file in a secure password manager or dedicated secret management tool like AWS Secrets Manager or HashiCorp Vault. : Periodically update the backup credentials and follow the 3-2-1 backup rule (3 copies, 2 media types, 1 offsite). DEV Community or setting up automated backups for your environment? Stop Using .env Files Now! - DEV Community
STRIPE_SECRET_KEY=sk_live_actual_key_here SENDGRID_API_KEY=SG.actual_key_here AWS_ACCESS_KEY_ID=AKIA... AWS_SECRET_ACCESS_KEY=... S3_BUCKET=prod-bucket-name
ENABLE_ANALYTICS=true ENABLE_CACHE=true MAINTENANCE_MODE=false DEBUG=false .env.backup.production
If you have found a .env.backup.production file, immediate action is required:
Manual backups fail. You will forget. Automation is the only reliable path.
Here is a production-grade cron job (or systemd timer) that should run every 6 hours on your production host:
#!/bin/bash
# /usr/local/bin/backup-env.sh
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
BACKUP_DIR="/var/backups/env"
SOURCE_ENV="/var/www/app/.env.production" find "$BACKUP_DIR" -name "
To understand the value of this file, consider a common horror story:
Friday, 4:55 PM. A junior developer runs git pull on the production server. By mistake, they also run rm -rf .env followed by a botched mv command. The live .env.production is gone. The database connection string is lost. The API keys to the payment processor are missing. The application crashes globally.
Most teams panic at this point. They scramble through Slack history, try to find the original .env in a stale chat thread, or pray that someone remembers the database password.
But a team with a strict backup protocol does the following: Additionally, integrate this into your CI/CD pipeline
cp .env.backup.production .env.production
systemctl restart app
In under 10 seconds, the disaster is over.