Docker Volumes Advanced
7. Docker Volumes Advanced
Section titled “7. Docker Volumes Advanced”🗄️ Persistent Database with Backups
Section titled “🗄️ Persistent Database with Backups”# Run PostgreSQL with named volumedocker run -d \ --name postgres \ -v postgres-data:/var/lib/postgresql/data \ -e POSTGRES_PASSWORD=secret \ postgres:15
# Inspect volume location on hostdocker volume inspect postgres-data# Output: Mountpoint: /var/lib/docker/volumes/postgres-data/_data💾 Backup Strategies
Section titled “💾 Backup Strategies”# ─── Method 1: Volume Backup to tar.gz ───────────────────────docker run --rm \ -v postgres-data:/data \ -v $(pwd):/backup \ alpine \ tar czf /backup/postgres-backup-$(date +%Y%m%d).tar.gz -C /data .
# ─── Method 2: PostgreSQL pg_dump via exec ────────────────────docker exec -t postgres \ pg_dumpall -c -U postgres \ > backup-$(date +%Y%m%d).sql
# ─── Method 3: MongoDB mongodump ──────────────────────────────docker exec mongodb \ mongodump --username admin --password password \ --authenticationDatabase admin \ --out /dump
docker cp mongodb:/dump ./mongo-backup-$(date +%Y%m%d)
# ─── Restore PostgreSQL ───────────────────────────────────────cat backup.sql | docker exec -i postgres psql -U postgres
# ─── Restore MongoDB ──────────────────────────────────────────docker cp ./mongo-backup mongodb:/dumpdocker exec mongodb \ mongorestore --username admin --password password \ --authenticationDatabase admin /dump🔄 Shared Volume Between Containers
Section titled “🔄 Shared Volume Between Containers”# Multiple containers sharing one volume (e.g., log aggregator)services: api: volumes: - app-logs:/app/logs
log-aggregator: image: fluentd volumes: - app-logs:/fluentd/log # Same volume!
volumes: app-logs: