The key question is not simply whether data should persist. It is whether data should persist across container restarts, container replacement, host replacement, deployment rollback, or disaster recovery. These are different requirements. A useful operational distinction is:
A volume may provide the first property without providing the other three. 4. Volume Lifecycle and InitializationMany official images initialize a data directory when it is empty. For example, a database image may create system tables and default configuration on first startup. Attaching an existing volume can therefore cause different behavior from attaching a new volume. A safe lifecycle normally includes:
Do not assume that copying arbitrary database files while the database is running produces a consistent backup. Application-aware backups, such as database dump or snapshot procedures, are often safer because they coordinate with transactions and internal state. 5. Backing Up and Restoring a Named VolumeFor file-oriented data, a temporary container can archive a volume. The following example writes an archive to the current host directory: docker run --rm \ --mount source=app-data,target=/data,readonly \ --mount type=bind,source="$PWD",target=/backup \ alpine:3.20 \ tar czf /backup/app-data.tgz -C /data . The volume is mounted read-only to reduce accidental modification. The archive must then be protected, tested, and retained according to policy. A basic restoration pattern is: docker volume create app-data-restored docker run --rm \ --mount source=app-data-restored,target=/data \ --mount type=bind,source="$PWD",target=/backup,readonly \ alpine:3.20 \ sh -c 'tar xzf /backup/app-data.tgz -C /data' Restoration should normally occur into a new volume first. This preserves the original volume for comparison and rollback. File ownership and permissions must be checked because archive extraction performed as a different user can produce unusable files. 5.1 Backup qualityA professional backup process addresses:
A backup that has never been restored in a test is an assumption, not evidence of recoverability. Backup logs should avoid exposing passwords, tokens, or sensitive records. 6. Configuration ManagementConfiguration determines how an application behaves in a particular environment. Examples include database hostnames, listening ports, log levels, feature flags, and connection timeouts. Configuration should be externalized from the image when it varies by environment. Common mechanisms include environment variables, mounted files, command-line arguments, and configuration services. Example: docker run --rm \ --env-file production.env \ --mount type=bind,src="$PWD/config/app.yml",dst=/etc/myapp/app.yml,readonly \ myapp:1.0 Environment files improve repeatability but must be protected if they contain sensitive values. Configuration should be versioned when appropriate, reviewed, validated, and separated into development, test, and production variants. A robust application should fail clearly when required configuration is absent or invalid. Silent fallback to insecure defaults is dangerous. Configuration schemas, startup validation, and documented precedence rules reduce deployment errors. 6.1 Configuration versus secretsA database hostname is normally configuration. A database password is a secret. The distinction is based on sensitivity, not merely on the variable name. Secrets should not be:
Docker Compose supports secret-oriented declarations, and orchestrators such as Swarm and Kubernetes provide more advanced secret mechanisms. In larger environments, a dedicated secret manager may provide encryption, access policies, auditing, rotation, and short-lived credentials. A secret mounted as a file is not automatically safe. File permissions, container privileges, host access, backups, crash dumps, and application logging remain relevant. Secret rotation also requires an application design that can reload or safely restart with new credentials. 7. Stateful Containers and Distributed Systems RisksContainers are easiest to replace when they are stateless. A stateless service can usually be recreated from an image and configuration. A stateful service owns data whose identity, consistency, and recovery must be managed. Common risks include: 7.1 Single-host dependencyA local volume is generally tied to a Docker host unless a storage driver or external storage system provides mobility. Host failure can therefore make the container and its data unavailable together. 7.2 Split-brain and duplicate writersStarting two containers that write to the same database directory is usually unsafe. Filesystem-level sharing does not create database coordination. Applications require transaction protocols, locking semantics, and a supported replication design. 7.3 Identity and permissionsThe user inside a container may have a numeric user ID that differs from the host user. A bind-mounted directory can consequently become unreadable or writable by the wrong account. Images and deployment definitions should document expected ownership and avoid running with unnecessary root privileges. 7.4 Upgrade and rollback hazardsDatabase schema migrations are often not backward-compatible. Rolling back the image without rolling back the schema can leave the application unusable. Upgrades require tested migration plans, backups, compatibility analysis, and a rollback strategy. 7.5 Resource exhaustionA container can fill a volume or host filesystem. Database growth, uncontrolled logs, and temporary files require quotas, monitoring, retention, and alerting. Log rotation must be designed separately from application data retention. 7.6 Security exposureA writable bind mount can expose host files. A mounted Docker socket can provide near-host-level control and should be treated as highly privileged. Containers that can inspect or modify storage belonging to other workloads violate isolation expectations. 8. Applied Case: An Illustrative Online BookstoreBackgroundAn online bookstore consists of a web service, an API service, a PostgreSQL database, and an image-processing worker. Customers upload book-cover images, while the database stores orders and catalogue information. ProblemThe initial deployment stores database files and uploaded images in container writable layers. After a routine deployment, the containers are recreated and customer uploads disappear. Developers then propose bind-mounting the entire host filesystem to prevent future loss. AnalysisThe first design confuses container replacement with data retention. The proposed host-wide bind mount would create excessive privilege and portability risks. The data has different characteristics and should not share one storage mechanism. Approach and solutionThe team adopts the following design:
The database is backed up using a database-consistent method, and volume-level archives are used only where appropriate. Restoration is tested in an isolated environment. The API validates required configuration at startup, and containers run with non-root users where supported. OutcomeA deployment can replace web and worker containers without losing data. Database recovery is documented and tested. The storage design is more portable than a host-wide bind mount and exposes fewer host resources. Learning points
9. Professional Practices and GovernanceA production storage design should be documented as an operational contract. At minimum, document each mount’s source, destination, mode, owner, data classification, backup method, retention period, and deletion procedure. Recommended practices include:
Governance may also be affected by privacy and regulatory obligations. Customer records, health information, financial data, and authentication material may require access logging, encryption, retention limits, regional storage controls, and secure disposal. The exact obligations depend on the organization’s jurisdiction and sector; technical teams should involve security, legal, and compliance specialists rather than assuming that a container boundary satisfies regulation. 10. Contemporary DevelopmentsModern platforms increasingly separate compute from durable storage. Containerized applications may use managed databases, object-storage systems, distributed filesystems, or CSI-compatible storage in Kubernetes. This can improve availability and operational maturity but introduces network dependency, cost, latency, and provider-governance considerations. Ephemeral environments and infrastructure-as-code make disposable containers practical, but they do not make business data disposable. Automated deployments should provision storage, access policies, backups, and monitoring together. Policy-as-code and secret-scanning tools can prevent common mistakes before deployment. AI-assisted development can help generate Docker Compose files, backup scripts, and configuration templates, but generated artifacts require human review. AI tools may reproduce insecure patterns such as plaintext secrets, unrestricted bind mounts, or destructive volume commands. They should not receive confidential production data unless approved controls exist. Chapter SummaryDocker separates immutable image layers from a container-specific writable layer. The writable layer is appropriate for temporary data but is lost when the container is removed. Bind mounts expose explicit host paths and are useful for development or controlled host integration, but they create coupling and permission risks. Named volumes are Docker-managed resources suited to durable application data, although they are not backups. Effective persistence design classifies data by lifetime, sensitivity, consistency, and recovery requirements. Configuration should be externalized and validated; secrets should be protected through secret-specific controls. Stateful containers require attention to host dependency, permissions, concurrency, upgrades, capacity, backup, restoration, and security. A professional solution combines appropriate mounts with tested recovery procedures, monitoring, least privilege, and clear governance. Key TermsWritable layer: The container-specific filesystem layer where runtime changes are stored. Image layer: A read-only filesystem layer forming part of a Docker image. Copy-on-write: A mechanism that copies a lower-layer file before modifying it. Bind mount: A mapping of a specific host path into a container. Named volume: A Docker-managed persistent storage resource identified by name.
Read-only mount: A mount that allows the container to read but not modify the mounted data. Persistence: Survival of data beyond the ordinary lifetime of a container. Backup: A separate copy of data retained for recovery. Restoration: The process of rebuilding usable data from a backup. RPO: Recovery point objective; the acceptable amount of data loss measured in time. RTO: Recovery time objective; the target time for restoring service. Configuration: Non-secret values that control application behavior. Secret: Sensitive information such as a password, token, or private key. Stateful service: A service that owns or depends on durable application data. Schema migration: A controlled change to a database’s structure. Least privilege: Providing only the permissions required for a task. Object storage: A storage service that manages data as objects rather than ordinary local files. Review QuestionsShort Answer Questions
Long Answer Questions
Analytical / Application Questions
Multiple Choice Questions with AnswersQuestion 1Which storage mechanism is normally most appropriate for Docker-managed database data? A. The container writable layer B. A named volume C. A host-wide bind mount D. A temporary tmpfs mount Correct Answer: B. A named volume Question 2What is the defining characteristic of a bind mount? A. It is stored only in container memory B. It is automatically encrypted by Docker C. It maps a specific host path into the container D. It disappears whenever the container stops Correct Answer: C. It maps a specific host path into the container Question 3Which statement about a named volume is correct? A. It is automatically a disaster-recovery backup B. It normally survives removal of the container using it C. It can only be used for read-only data D. It must always refer to a path in the application image Correct Answer: B. It normally survives removal of the container using it Question 4Which use is most appropriate for a tmpfs mount? A. Permanent customer order records B. A database’s primary data directory C. Temporary processing files D. Long-term backup archives Correct Answer: C. Temporary processing files Question 5Why should a mount be marked read-only when writing is unnecessary? A. To increase the image size B. To reduce accidental modification and tampering C. To make the container stateful D. To ensure the data is deleted immediately Correct Answer: B. To reduce accidental modification and tampering Question 6Which item is normally a secret rather than ordinary configuration? A. Application listening port B. Log verbosity level C. Database password D. Feature flag name Correct Answer: C. Database password Question 7What is the principal purpose of testing restoration from a backup? A. To increase the container’s writable layer B. To prove that the backup can produce usable recovered data C. To replace access control policies D. To remove the need for replication Correct Answer: B. To prove that the backup can produce usable recovered data Question 8What is a major risk of storing persistent data only on a local Docker host? A. The image becomes read-only B. The data may be unavailable if that host fails C. The container cannot expose ports D. The application cannot use environment variables Correct Answer: B. The data may be unavailable if that host fails Question 9Which practice best protects a database during a version upgrade? A. Delete the existing volume before upgrading B. Run two writers against the same database directory C. Create and test a recovery plan before migration D. Embed the database password in the Dockerfile Correct Answer: C. Create and test a recovery plan before migration Question 10What does RPO describe? A. The target time required to restore service B. The acceptable amount of data loss measured in time C. The number of containers in a deployment D. The maximum size of a named volume Correct Answer: B. The acceptable amount of data loss measured in time
Containerization with Docker
|
Chapter 5 of 15 |