Knowledge
Docker: data storage and centralized logging
Estimated time: 50 minutes.
Quick summary
-
Three places a container writes data
- Why: The writable layer (the default, lost on rm) · a volume managed by Docker · a bind mount pointing at a host directory (Docker: storage). Choosing the wrong place to write is the most common cause of data loss when operating containers.
- When it breaks: If data stays in the writable layer, every container replacement wipes it out — and replacing containers happens all the time.
- In real deployments: Set a convention at the start of the project: durable data → volume; content/configuration supplied from the host → bind mount; everything else is acceptable to lose.
-
Volumes: create, inspect, attach, clean up
- Why: docker volume create/ls/inspect/rm/prune; inspect shows the real Mountpoint on the host (Docker: volumes). Attach with -v volume-name:/path or --mount source=...,target=...; a volume exists independently of the container that mounts it.
- When it breaks: Removing the container looks like a full cleanup, but orphaned volumes still take up space and pile up on the host.
- In real deployments: Name volumes after the service, and take stock periodically with docker system df before cleaning up.
-
Bind mounts and read-only mode
- Why: -v /opt/html:/usr/share/nginx/html mounts a host directory into the container; add :ro so the container cannot write (Docker: bind mounts). Editing a file on the host takes effect immediately in the container; removing the container does not affect the content on the host.
- When it breaks: A bind mount overlays whatever the image already has at the mount point — mounting an empty directory by mistake makes the service lose all of its original files.
- In real deployments: Supply static content/configuration through a :ro bind mount; keep the host path in the deployment documentation because it depends on each machine.
-
Docker's disk: /var/lib/docker and system df
- Why: docker info shows the Docker Root Dir (default /var/lib/docker); docker system df reports the space used by images/containers/volumes/build cache with a RECLAIMABLE column (docker system df, docker info).
- When it breaks: Without monitoring, the partition fills up silently, and by the time you notice, containers have stopped en masse.
- In real deployments: Monitor the free space of the partition that holds the Docker Root Dir; consider moving data-root to a separate data partition.
-
Log drivers and size limits
- Why: By default json-file stores logs at /var/lib/docker/containers/<id>/<id>-json.log with no size limit; set max-size/max-file in daemon.json or with --log-opt at run time (Docker: configure logging).
- When it breaks: Unlimited logs are the fastest way to fill the disk and take down every container on the host.
- In real deployments: Standardize log-opts in daemon.json for the whole host as soon as Docker is installed, not after an incident.
-
Centralized log collection: Vector → VictoriaLogs
- Why: Vector installed on the Docker host uses the docker_logs source to read the logs of every container without declaring any path, transforms them and ships them to a central logging system (Vector: docker_logs, VictoriaLogs). Run vector validate before starting: with a bad configuration the process does not start.
- When it breaks: Missing permission to read Docker (the user is not in the docker group) makes the agent run but collect not a single log line.
- In real deployments: Each host with Docker gets one agent; logs are centralized in one place so you can query by container name during an incident.
-
Data shared across hosts (NFS/NAS)
- Why: When several hosts need the same data area, a directory shared over NFS/NAS is mounted on the host and then bind-mounted into the container. The common safe model is one writer process with all the other processes read-only.
- When it breaks: Many containers writing to the same file on a network share easily cause contention and data corruption.
- In real deployments: Use it for shared static content/documents; transactional data should be handled by a dedicated database system.
Step 1 — Find out where Docker is using space
docker info shows the Docker Root Dir — the directory that holds all images/containers/volumes/logs (default /var/lib/docker). du -sh gives the actual figure, and docker system df breaks it down by category along with the reclaimable portion (docker system df).
When it breaks: If you do not know where Docker is using space, then when the disk fills up you will clean the wrong place while containers keep stopping.
docker info
docker info --format "{{.DockerRootDir}}"
du -sh /var/lib/docker
docker system df
docker system df -v
Observe with:
docker info | grep -i "root dir" ; du -sh /var/lib/docker ; docker system df
Symptoms when it breaks:
- Containers stop en masse and docker commands report write errors: df -h shows the partition holding /var/lib/docker at 100% Use%
How to fix:
-
See which category is using space and how much is reclaimable
docker system df -v -
Clean up unused images/containers/build cache (read carefully before running)
docker system prune
Step 2 — A volume outlives the container that created it
Create a volume, write data with a container that uses --rm (it removes itself when it finishes), then read it back with a second container. The volume lives outside the container lifecycle, so the content stays intact (Docker: volumes).
When it breaks: If you write to a path that is not mounted, the data lands in the writable layer and disappears along with the container.
docker volume create lab-vol
docker volume ls
docker volume inspect lab-vol
docker run --rm -v lab-vol:/data alpine sh -c "date > /data/created; cat /data/created"
docker ps -a
docker run --rm -v lab-vol:/data alpine cat /data/created
ls -l /var/lib/docker/volumes/lab-vol/_data
Observe with:
docker volume inspect lab-vol (see the Mountpoint) ; ls in the Mountpoint directory on the host
Note: The first container removed itself, yet the second container still reads exactly what it wrote — proof that a volume is independent of the container lifecycle.
Step 3 — Bind mount: content supplied by the host
Prepare a content directory on the host and mount it onto Nginx's web root. Editing a file on the host takes effect on the next page load, because the container reads that directory directly (Docker: bind mounts).
When it breaks: Mounting an empty directory by mistake hides all of the original content in the image, and the service returns 403/404 even though the container is still running.
mkdir -p /opt/html
echo "<h1>Page served by the host</h1>" > /opt/html/index.html
docker run -d --name lab-web2 -p 8080:80 -v /opt/html:/usr/share/nginx/html:ro nginx
curl -s http://localhost:8080
echo "<h1>Content updated</h1>" > /opt/html/index.html
curl -s http://localhost:8080
Observe with:
curl http://localhost:8080 before and after editing the file on the host
Symptoms when it breaks:
- The page returns 403 Forbidden even though the container is Up: docker logs lab-web2 reports directory index of "/usr/share/nginx/html/" is forbidden
How to fix:
-
Check that the host directory has an index.html file and read permission
ls -l /opt/html
Step 4 — Read-only mode and what remains after the container is removed
The :ro suffix blocks writes from the container side while the host can still edit — exactly the model for supplying static content. Remove the container and then check the host directory again to see that the data does not go away with the container.
When it breaks: Without :ro, a compromised process inside the container can modify the data on the host directly.
docker exec lab-web2 sh -c "echo test > /usr/share/nginx/html/x.html"
docker rm -f lab-web2
ls -l /opt/html
cat /opt/html/index.html
Observe with:
docker exec trying a write (denied) ; ls /opt/html after docker rm
Symptoms when it breaks:
- The write command inside the container is denied: sh: can't create /usr/share/nginx/html/x.html: Read-only file system
Step 5 — Cleaning up volumes and the cost of cleaning the wrong one
docker volume rm removes the specified volume; docker volume prune removes every volume not used by any container. There is no undo (Docker: pruning).
When it breaks: A volume that has just lost its reference because a container was temporarily removed is still treated by prune as unused, and its data gets deleted.
docker volume ls
docker volume rm lab-vol
docker volume ls -f dangling=true
docker volume prune
docker system df
Observe with:
docker volume ls before/after ; docker system df, watching the LOCAL VOLUMES line
How to fix:
-
List the orphaned volumes and cross-check them before cleaning up
docker volume ls -f dangling=true
Note: CI/CD environments generate volumes constantly and do not clean them up on their own — you need a controlled cleanup schedule instead of ad-hoc prunes.
Step 6 — Limit logs before logs limit the system
The default json-file log driver writes without any limit. Setting max-size/max-file in daemon.json applies to every new container, or use --log-opt for an individual container (Docker: configure logging).
When it breaks: One chatty container is enough to fill the partition and drag down every other container on the host.
du -sh /var/lib/docker/containers/* | sort -h | tail -5
docker run -d --name web-limited -p 8080:80 --log-opt max-size=10m --log-opt max-file=3 nginx
docker inspect --format "{{.HostConfig.LogConfig}}" web-limited
Observe with:
du -sh /var/lib/docker/containers/* | sort -h | tail
Script it: Put it at /etc/docker/daemon.json and restart Docker; it applies to containers created afterwards.
{
"log-driver": "json-file",
"log-opts": {
"max-size": "10m",
"max-file": "3"
}
}
Step 7 — Build a centralized logging system with Docker itself
VictoriaLogs runs like an ordinary container: publish the UI/API port and attach a volume for the data so logs are not lost when the container is replaced (VictoriaLogs).
When it breaks: If you forget to attach a volume for the data directory, all the logs collected so far are deleted along with the container.
docker volume create victoria-logs-data
docker run -d --name victoria-logs --restart unless-stopped \
-p 9428:9428 \
-v victoria-logs-data:/victoria-logs-data \
victoriametrics/victoria-logs:latest
docker ps
curl -s http://localhost:9428/health
Observe with:
docker ps ; open the UI on the published port
Note: A lesson that follows on from Part 1: an infrastructure service is also just a container — but its data must live on a volume.
Step 8 — Vector reads the logs of every container and ships them to one place
Vector's docker_logs source receives logs directly through Docker, automatically picks up containers created later too, and attaches name/image labels for filtering (Vector: docker_logs). vector validate checks the configuration before start — with a bad configuration the service does not come up.
When it breaks: If the user running Vector is not in the docker group, the agent comes up but cannot read any logs, which is easily mistaken for a broken logging system.
usermod -aG docker vector
vector validate --config /etc/vector/vector.yaml
systemctl restart vector
systemctl status vector --no-pager
docker run -d --name lab-web3 -p 8081:80 nginx
for i in $(seq 1 50); do curl -s localhost:8081/req-$i >/dev/null; done
Observe with:
vector validate ; journalctl -u vector -f ; the VictoriaLogs UI filtered by container name
Symptoms when it breaks:
- Vector fails to start right after a configuration change: vector validate returns an error at the exact faulty configuration block, and the process does not start
- Vector runs but no container logs reach the central system: the service log reports permission denied when accessing the Docker socket
How to fix:
-
Grant Docker access to the user running the agent, then restart the service
usermod -aG docker vector && systemctl restart vector -
Fix the configuration until validate is clean before starting
vector validate --config /etc/vector/vector.yaml
Script it: A minimal Vector configuration skeleton; change the endpoint to the IP of the machine running VictoriaLogs when the two services are on different hosts.
sources:
docker:
type: docker_logs
sinks:
victoria:
type: elasticsearch
inputs: [docker]
endpoints: ["http://127.0.0.1:9428/insert/elasticsearch/"]
mode: bulk
api_version: v8
healthcheck:
enabled: false
query:
_msg_field: message
_time_field: timestamp
_stream_fields: container_name
Common misconceptions
- Wrong: Removing a container also removes the data of the application that ran inside it. Right: Only data in the writable layer is lost with the container. Data placed in a volume or a bind mount stays intact after the container is removed.
By default a container writes to the writable layer — a thin layer tied to that very container, deleted together with the rm command (Docker: storage). The class demo shows the opposite for volumes: the first container, run with --rm, writes a file into a volume and removes itself; the second container mounts the same volume and can still read the file's content. Consequence: anything that must outlive the container (databases, uploads, configuration generated at run time) has to be placed in a volume or bind mount from the design stage, not patched in after the data is lost.
- Wrong: docker volume prune only cleans up junk, so it is always safe to run. Right: prune permanently deletes the volumes not used by any container — including a volume holding important data of a container that was only temporarily removed.
docker volume prune deletes every volume that is currently unreferenced, with no way to recover (Docker: pruning). A volume that has just lost its reference because the container mounting it was rm'd still has its data intact, but by prune's criteria it is "unused". The experience shared in class: CI runner environments generate volumes constantly and do not clean them up, so manual cleanup easily sweeps into volumes that hold real data. Consequence: preview with docker volume ls and docker system df, name volumes after the service so you can identify them, and back up before cleaning in a real environment.
- Wrong: Container logs are nothing to worry about because they are just a few lines of text. Right: Logs are the fastest-growing component on a Docker host; unlimited logs can fill the partition and stop every container on the machine.
The default json-file log driver writes continuously to /var/lib/docker/containers/<id>/<id>-json.log and by default has NO size limit (Docker: json-file driver). A service with ordinary traffic generates tens of thousands of lines per hour; multiplied by the number of containers on one host, the partition holding /var/lib/docker fills up very quickly — and once the disk is full, the daemon and the running containers all hit write errors. Consequence: set max-size/max-file for the log driver in daemon.json or per container, and consider moving /var/lib/docker to its own partition so that a log incident does not take the whole operating system with it.
- Wrong: A bind mount and a volume are just two ways of writing the same thing. Right: A volume is created and managed by Docker in its own area; a bind mount attaches an existing path on the host directly into the container. They differ in ownership, portability and risk.
A volume is under Docker's management (default mountpoint under /var/lib/docker/volumes/), has its own lifecycle commands and can be moved between hosts with supporting tools (Docker: volumes). A bind mount maps a host directory directly, and its content is owned by the host operating system (Docker: bind mounts). A bind mount lets you edit a file on the host and see the effect in the container immediately — very handy in development or when feeding static content to a web server; in exchange it depends on the directory layout of that specific machine and can overwrite content already in the image at the mount point. Consequence: use a volume for data generated by the application, use a bind mount when you need to share one specific host directory, and add :ro when the container only needs to read.
- Wrong: To collect the logs of 100 containers you have to configure a log path for each container. Right: The log-collection agent reads directly through Docker (the docker_logs source) and automatically picks up every existing container as well as containers created later — no need to declare each one.
Vector with the docker_logs source connects to the Docker daemon and receives the log streams of running containers, with name/ID/image labels for filtering later (Vector: docker_logs source). This mechanism replaces pointing at each json-file, which is not feasible when containers are constantly created and deleted and the ID changes every time. The prerequisite is that the agent process has access to Docker — on Linux that means the user running the agent is in the docker group. Consequence: the log-collection model for a Docker host is one agent on each host, shipping to one central logging system; in exchange you must accept installing an agent on every machine that runs Docker.
Hands-on 1 — A volume outlives the container
15 minutes
Prove that a volume is independent of the container lifecycle: the first container removes itself after writing, and the second container can still read it back (Docker: volumes).
docker volume create lab-vol
Observe: docker volume inspect lab-vol ; ls in the Mountpoint on the host
1. Create and inspect the volume: docker volume create lab-vol, docker volume inspect lab-vol.
The Mountpoint field points at a directory under /var/lib/docker/volumes/lab-vol/_data.
2. Write with a self-removing container: docker run --rm -v lab-vol:/data alpine sh -c "date > /data/created; cat /data/created", then docker ps -a.
The command prints the time of the write; docker ps -a no longer shows that container.
3. Read it back with another container: docker run --rm -v lab-vol:/data alpine cat /data/created.
It prints exactly what the first container wrote.
Analysis
Observation: The container that created the data is gone, yet the data can still be read.
Mechanism: A volume is a storage area managed by Docker, attached to the container at run time rather than belonging to the container.
Takeaway: Any data that must outlive the container has to live on a volume or bind mount, not in the writable layer.
Troubleshooting:
- The second container reports that the file is not found: Check that the mount target matches the path written in step 2 (the same /data).
Hands-on 2 — Bind mount and read-only mode
15 minutes
Supply web content from a host directory, and verify that an edit on the host takes effect immediately and that the data does not go away with the container when it is removed (Docker: bind mounts).
docker run -d --name lab-web2 -p 8080:80 -v /opt/html:/usr/share/nginx/html:ro nginx
Observe: curl http://localhost:8080 before/after the edit ; ls /opt/html after removing the container
1. Prepare the content: mkdir -p /opt/html and then create /opt/html/index.html with a single heading line.
The /opt/html directory contains an index.html file.
2. Run Nginx with a read-only bind mount, then curl -s http://localhost:8080.
The page returns exactly the content of the file on the host.
3. Edit the file on the host and curl again.
The new content appears immediately, with no need to restart the container.
4. Try to write from inside the container: docker exec lab-web2 sh -c "echo test > /usr/share/nginx/html/x.html".
It is denied with a Read-only file system message.
5. Remove the container: docker rm -f lab-web2 and then ls -l /opt/html.
The file on the host is intact.
Analysis
Observation: The content changes instantly when edited on the host; the container cannot write; removing the container does not lose the file.
Mechanism: A bind mount maps the host directory directly into the container, and write permission is decided by the :ro suffix.
Takeaway: A bind mount suits content/configuration supplied by the host; :ro limits the damage if a process inside the container is compromised.
Troubleshooting:
- The page returns 403 Forbidden: The mounted directory lacks index.html or has the wrong read permission — check ls -l /opt/html.
- Port 8080 is busy: Remove the old container holding the port (docker ps and then docker rm -f) or switch to another port.
Hands-on 3 — Taking stock of disk usage and limiting logs
15 minutes
Understand where Docker is using space and block the risk of logs filling the disk before an incident happens (docker system df, Docker: configure logging).
docker system df -v
Observe: du -sh /var/lib/docker ; docker inspect --format "{{.HostConfig.LogConfig}}" <container>
1. Measure the total size: du -sh /var/lib/docker and docker system df.
You see the total size and a table broken down by IMAGES/CONTAINERS/LOCAL VOLUMES/BUILD CACHE.
2. Find the container with the most logs: du -sh /var/lib/docker/containers/* | sort -h | tail -5.
A list of the 5 container directories taking the most space.
3. Run a container with a log limit: add --log-opt max-size=10m --log-opt max-file=3 and check with docker inspect --format "{{.HostConfig.LogConfig}}".
The log configuration shows exactly the max-size and max-file you just set.
Analysis
Observation: Most of the space is usually in images and container logs.
Mechanism: json-file writes continuously without a limit; each container has its own log directory named by ID.
Takeaway: Set default log-opts in daemon.json as soon as Docker is installed, instead of dealing with it after the disk is full.
Hands-on 4 — Centralized log collection with Vector and VictoriaLogs
25 minutes · optional
Build a centralized logging system right on the Docker host and have an agent read the logs of every container — a model that remains workable when the number of containers grows to dozens (VictoriaLogs, Vector: docker_logs).
docker run -d --name victoria-logs -p 9428:9428 -v victoria-logs-data:/victoria-logs-data victoriametrics/victoria-logs:latest
Observe: The UI on port 9428, filtered by container name ; journalctl -u vector -f
1. Run VictoriaLogs with a data volume, and check with docker ps and curl -s http://localhost:9428/health.
The container is Up and the health endpoint responds.
2. Install Vector following the official documentation, write a configuration with a docker_logs source and a sink pointing at VictoriaLogs, then run vector validate.
Validate reports the configuration as valid; if it errors, fix it until it is clean before moving on.
3. Grant permission and start: usermod -aG docker vector, systemctl restart vector, systemctl status vector.
The service is active (running), with no more Docker access errors.
4. Generate logs: run one more Nginx container on port 8081 and send 50 requests to it.
In the centralized log UI, filtering by container name shows the access lines you just generated.
Analysis
Observation: Logs of the new container appear without changing the agent configuration.
Mechanism: The agent receives the log stream directly through Docker along with name/image labels, so containers created later are still collected.
Takeaway: Every host running Docker needs an agent; in return you get centralized log queries by container name during an incident.
Troubleshooting:
- The agent service does not start after a configuration change: Run vector validate to get the exact error location; the process does not come up while the configuration is invalid.
- The agent runs but there are no container logs: Check whether the user running the agent is in the docker group yet, then restart the service.
Review questions
Question 1. The first container, run with --rm, writes a file into a volume and removes itself. The second container mounts the same volume and reads that file. What is the result?
- It cannot read it because the first container has been removed
- It reads exactly what was written
- The volume is removed along with the first container that mounted it
- It can only read it if the two containers run at the same time
Answer: It reads exactly what was written. A volume lives outside the container lifecycle: content written into the volume remains after the container that created it is removed, so the second container can read it back. The --rm flag only removes the container and does not touch the volume — a volume is lost only when an rm/prune command targets it (Docker: volumes).
Question 2. After removing a container that had the bind mount /opt/html, what happens to the data in /opt/html?
- It is deleted along with the container
- It stays intact on the host
- It becomes a Docker volume
- It remains only if it was mounted in :ro mode
Answer: It stays intact on the host. A bind mount only maps an existing host directory into the container; removing the container removes the mapping, while the directory and its content belong to the host and are unchanged. The :ro suffix only decides whether the container may write, and has nothing to do with whether the data survives after the container is removed (Docker: bind mounts).
Question 3. Which command shows how much space images, containers, volumes and build cache are using, and which part is reclaimable?
- docker stats
- docker system df
- docker volume ls
- docker info
Answer: docker system df. docker system df reports usage by category along with a RECLAIMABLE column; add -v to see each image/volume in detail. This differs from docker stats (which measures real-time CPU/RAM) and docker info (an overview of the configuration including Docker Root Dir, without a space breakdown) (docker system df).
Question 4. Does the default json-file log driver have a size limit?
- Yes, 10MB by default
- No, you have to set max-size/max-file yourself
- Yes, it deletes itself after 7 days
- No, it does not write to disk so no limit is needed
Answer: No, you have to set max-size/max-file yourself. json-file writes logs to disk and by default has no size limit; you must declare max-size/max-file in daemon.json or with --log-opt when running the container. At the default driver level there is no mechanism that expires logs by days — logs persist until the container is removed or the file is rotated according to the configuration (Docker: json-file driver).
Question 5. Why does Vector's docker_logs source not need a log path declared for each container?
- Because it reads files in the host's /var/log
- Because it fetches logs directly through Docker, so it also picks up containers created later
- Because all containers write to one single file
- Because it only collects logs from containers with a special label
Answer: Because it fetches logs directly through Docker, so it also picks up containers created later. Vector connects to Docker and receives the log stream with name/ID/image labels, so containers created later are still collected without changing the configuration. Each container has its own log file named by ID, so pointing at each file by hand is not feasible when containers are constantly created and deleted (Vector: docker_logs).
Question 6. The log-collection agent runs but no container log lines reach the central system. What is the first cause to check?
- The container has not produced any logs
- The user running the agent has no access to Docker (not in the docker group)
- The central logging system has not created an index
- Port 9428 is not open to the Internet
Answer: The user running the agent has no access to Docker (not in the docker group). The docker_logs source needs permission to talk to Docker; a user outside the docker group is denied access, and the agent runs but collects nothing. An Internet-facing port is irrelevant when the agent and the logging system are on the same host, and whether the container produces logs can be verified immediately with docker logs (Vector: installation).
Question 7. Which volumes does docker volume prune delete?
- Only empty volumes
- Every volume not used by any container
- Every volume, even those in use
- Only automatically created volumes without a name
Answer: Every volume not used by any container. prune sweeps by the criterion "not referenced" and does not consider whether a volume holds data — so a volume that has just lost the container mounting it is deleted too. A volume that a container is using is kept; conversely, a volume with important data that happens to be idle is lost (Docker: pruning).
Flashcards
-
Three places a container writes data? The writable layer (lost on rm) · a volume managed by Docker · a bind mount pointing at a host directory. Choosing the right place to write decides whether data survives or is lost when a container is replaced.
-
Is a volume lost when the container is removed? No. A volume exists independently; it is lost only through docker volume rm or prune.
-
Default mountpoint of a volume? /var/lib/docker/volumes//_data — see the exact path with docker volume inspect.
-
How does a bind mount differ from a volume? A bind mount attaches an existing host directory directly (owned by the host); a volume lives in the area Docker manages and has its own lifecycle commands.
-
What does the :ro suffix do? The container can only read that mount point; the host can still write normally.
-
When do you use docker system df? When you need to know how much images/containers/volumes/build cache use and which part is reclaimable; add -v for details.
-
Where do container logs live by default? /var/lib/docker/containers/<id>/<id>-json.log, written by the json-file log driver, with no size limit by default.
-
How do you stop logs from filling the disk? Set max-size/max-file in /etc/docker/daemon.json or use --log-opt when running the container; consider moving data-root to a separate partition.
-
Why use the docker_logs source instead of reading files? It fetches logs directly through Docker, so it automatically picks up containers created later and has name/image labels ready for filtering.
-
What is vector validate for? It checks the configuration before start; if the configuration is not clean the service cannot start.
-
What about data shared across many hosts? Mount an NFS/NAS directory on the host and then bind-mount it into the container; the safe model is one place that writes and the others read-only.