Knowledge
Docker: images and the container lifecycle
Estimated time: 45 minutes.
Quick summary
-
Image management: pull / ls / inspect / history / tag / rm
- Why: docker pull downloads an image (tag latest by default); image ls lists images; inspect shows JSON metadata (OS/architecture/layers); history shows the layer history; tag assigns a new name; rm deletes (docker image). The digest (a hash) ensures the downloaded image is intact and has not been tampered with.
- When it breaks: Not pinning the tag or not checking the digest leads to running the wrong image version in a real environment.
- In real deployments: Standardize tags according to your internal naming scheme; pin the version/digest for reproducible deployments.
-
Container lifecycle
- Why: created → running → (paused) → exited → removed; controlled with stop/start/pause/unpause/rename/rm (docker container). stop → Exited (the container still exists); start → runs the old instance again; rename only changes the "shell"; rm deletes it for good (stop it first if it is running).
- When it breaks: Confusing stop with rm leads you to think a container is gone while it still occupies resources/its name.
- In real deployments: Use a restart policy (always/unless-stopped) for services that must restart automatically; use rm to clean up containers you no longer need.
-
Port mapping -p (bind interface)
- Why: -p 127.0.0.1:8080:80 allows access only from the host itself (localhost); -p 8080:80 (no IP) publishes on 0.0.0.0 — every interface, reachable from other machines via the server IP (docker run). Publishing a port creates a forward from the host port into the container.
- When it breaks: Forgetting -p → the service cannot be reached from the host; leaving 0.0.0.0 by accident exposes it to the network.
- In real deployments: Bind to loopback for internal services; only publish on 0.0.0.0 when other machines truly need access.
-
Accessing a container: top vs exec
- Why: docker container top looks from OUTSIDE — it lists the processes inside (it does not show host processes, which demonstrates PID namespace isolation). docker exec -it goes INSIDE and opens an interactive session (docker container). Inside the container: hostname/IP differ from the host (
hostname -i,cat /etc/hosts); the filesystem is minimal. - When it breaks: Not telling the two ways of observing apart leads to wrong diagnoses (standing outside vs inside the container).
- In real deployments: Use top for a quick look at processes; use exec to go in and diagnose or try commands inside a running container.
- Why: docker container top looks from OUTSIDE — it lists the processes inside (it does not show host processes, which demonstrates PID namespace isolation). docker exec -it goes INSIDE and opens an interactive session (docker container). Inside the container: hostname/IP differ from the host (
-
Immutability and hot edits
- Why: A hot edit (exec + writing a file) takes effect immediately but lives only in the writable layer; rm + run again from the same image → back to the defaults (Docker: volumes). It shows visually that images are immutable and containers do not keep state.
- When it breaks: Treating a hot edit as a durable change means losing everything when the container is recreated.
- In real deployments: For lasting changes, build a new image from source; state that must persist is written to a volume.
-
Logs and monitoring: logs / stats / events
- Why: docker logs -f/--tail follows container logs; docker stats shows CPU/RAM in real time (docker stats); docker events follows start/stop/kill/restart events (docker events). Distinguish container logs (captured by Docker) from app logs (files inside the container).
- When it breaks: Not monitoring events/logs means missing abnormal container restarts/stops — a sign the app has a problem.
- In real deployments: Integrate Vector/VictoriaLogs to collect logs and catch Docker events, and alert when a container is unstable.
Step 1 — hello-world and image management
docker run --rm hello-world confirms Docker is working (like "print Hello World"); Docker looks for the image in its cache first and pulls it from the registry if it is not there. After that, manage images with ls/inspect/history/tag/rm (docker image). inspect --format filters specific fields with a Go template instead of reading the whole long JSON.
When it breaks: Not checking the image before running leads to running the wrong version.
docker run --rm hello-world
docker pull nginx
docker image ls
docker image history nginx
docker image inspect --format "{{.Os}} {{.Architecture}}" nginx
docker image tag nginx lab.inet/nginx:1
Observe with:
docker image ls ; docker image inspect --format "{{.Os}} {{.Architecture}}" <image>
Step 2 — Run Nginx and port mapping
docker run -d --name --hostname --restart always -p 8080:80 nginx: run in the background, set a name, restart automatically, map a port. -p 8080:80 publishes on 0.0.0.0; -p 127.0.0.1:8080:80 allows localhost only (docker run). container port shows the mapping; browsing to http://<ip>:8080 shows the Nginx welcome page.
When it breaks: Forgetting -p → curl localhost:8080 gives Connection refused even though the container is running.
docker run -d --name docker-lab --hostname docker-lab --restart always -p 8080:80 nginx
docker ps
docker container port docker-lab
curl -I http://localhost:8080
Observe with:
docker ps ; docker container port docker-lab
Symptoms when it breaks:
- curl localhost:8080 gives Connection refused/timeout: the PORTS column of docker ps has no 0.0.0.0:8080->80/tcp
How to fix:
-
Run it again with the port published
docker run -d --name docker-lab -p 8080:80 nginx
Step 3 — Lifecycle: stop / start / pause / rename
stop → Exited (check with docker ps -a); start restarts the old instance; pause/unpause freezes the process (the container is "alive" but does not respond to requests); rename changes the name without affecting operation (docker container).
When it breaks: Confusing stop with rm; thinking pause = stop (in fact the process is frozen but still exists).
docker container stop docker-lab
docker ps -a # STATUS = Exited
docker container start docker-lab
docker container pause docker-lab
docker container unpause docker-lab
docker container rename docker-lab docker-lab-2
Observe with:
docker ps -a (Exited/Up/Paused status)
Step 4 — Access from inside: top vs exec
docker container top looks from the outside — it only shows processes inside the container and does NOT show the host's init/systemd (which demonstrates PID namespace isolation). docker exec -it goes inside: the hostname/IP differ from the host, and the filesystem is minimal. The official nginx image has no ip command, so read the IP with hostname -i/cat /etc/hosts inside, or with docker inspect from the host (docker container).
When it breaks: Not distinguishing observation from outside vs inside leads to a wrong understanding of isolation.
docker container top docker-lab-2
docker exec -it docker-lab-2 /bin/sh
# inside the container:
hostname
hostname -i # the container's IP (the nginx image has no ip command)
cat /etc/hosts # last line: the container's IP + hostname
exit
# from the host:
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' docker-lab-2
Observe with:
docker container top docker-lab-2 ; docker exec -it docker-lab-2 /bin/sh
Step 5 — Hot edit → proving immutability (the key point)
exec into the container and overwrite /usr/share/nginx/html/index.html → reloading shows the change. But after stop + rm and running again from the SAME nginx image (not rebuilt) → the content REVERTS TO THE DEFAULT (Docker: volumes). This shows visually that images are immutable and containers do not keep state. To make a lasting change you must build a new image (Part 2).
When it breaks: Believing a hot edit is a durable change → losing everything on recreate; stuffing state into the container and losing it on rm.
docker exec -it docker-lab-2 sh -c 'echo "Hello there" > /usr/share/nginx/html/index.html'
curl http://localhost:8080 # shows "Hello there"
docker container stop docker-lab-2 && docker container rm docker-lab-2
docker run -d --name docker-lab-2 -p 8080:80 nginx
curl http://localhost:8080 # back to the default "Welcome to nginx!"
Observe with:
curl http://localhost:8080 (or reload the browser) before and after rm + run again: "Hello there" → "Welcome to nginx!"
Symptoms when it breaks:
- Expecting the change to survive a recreate: curl after rm + run again returns the default page, and the hot-edited content is gone
How to fix:
-
For lasting changes: edit the source and then build a new image (covered in Part 2)
docker build -t my-nginx:1 . # instead of a hot edit
Step 6 — Inspect, logs (container vs app), stats, events
docker container inspect returns JSON metadata (State/IP/RestartPolicy/storage path /var/lib/docker/containers/<id>/) — used constantly in practice (docker inspect). logs -f/--tail shows container logs; distinguish them from app logs (/var/log/nginx/). stats shows CPU/RAM; events catches start/stop/kill/restart (docker events).
When it breaks: Not monitoring events/logs means missing abnormal container restarts/stops.
docker container inspect --format "{{.State.Status}} {{.HostConfig.RestartPolicy.Name}}" docker-lab-2
docker container logs --tail 20 docker-lab-2
docker container logs -f docker-lab-2 # terminal A
# terminal B: for i in $(seq 1 50); do curl -s localhost:8080/req-$i >/dev/null; done
docker stats --no-stream
docker events --filter container=docker-lab-2 # then restart/stop/start from another terminal
Observe with:
2 terminals: docker logs -f / docker events + generate load; docker stats
Common misconceptions
- Wrong: Editing files in a running container (exec) is how you update an application. Right: A hot edit is only temporary; delete the container and run it again from the same image and everything is lost. The right way is to edit the source (Dockerfile/source code) → build a new image → replace the container.
A container running from an image consists of read-only layers; changes made at runtime go into a thin writable layer that is deleted together with the container on rm (Docker: volumes). The test in Step 5 shows this clearly: edit /usr/share/nginx/html/index.html via exec → reloading shows the change immediately; but after stop + rm + run again from the same nginx image → the content REVERTS TO THE DEFAULT and the change disappears completely. Consequence: images are immutable; to make a lasting change you must build a new image (covered in depth in Part 2). Hot edits are only for diagnosis or temporary experiments.
- Wrong: docker logs shows all of the application's logs inside the container. Right: docker logs only captures the stdout/stderr of the main process; logs the app writes to its own files (for example /var/log/nginx/) are a different kind, independent of Docker's logging mechanism.
Docker captures the main process's stdout/stderr and stores it at /var/lib/docker/containers/<id>/<id>-json.log, which you read through docker logs (docker logs). The application's own logs (Nginx's access/error logs in /var/log/nginx/) are files the app writes itself and do not go through Docker's mechanism (unless they are symlinked to stdout/stderr). Consequence: you need to tell the two sources apart when diagnosing; mount code/data and important logs outside the container via a volume instead of stuffing everything inside.
- Wrong: The latest tag always points to the newest image version. Right: latest is just the default tag when a command does not specify one; it does not automatically follow the newest release.
A tag is a label assigned by whoever creates the image and carries no "newest" semantics. docker pull nginx is equivalent to docker pull nginx:latest because latest is the default tag when none is given (docker image). latest only points to the image that was most recently pushed with the latest label — which can be an old build if a newer one was pushed under a different tag. Consequence: for reproducible deployments, pin a specific tag/version (for example nginx:1.27) or a digest in real environments.
- Wrong: docker stop deletes the container. Right: stop only moves the container to the Exited state; the container still exists (docker ps -a) and can be started again. You must docker rm to delete it for good.
Container lifecycle: created → running → (paused) → stopped/exited → removed (docker container). docker stop sends a stop signal to the main process and the container becomes Exited, but its writable layer and configuration remain intact. docker start restarts exactly that container instance; only docker rm deletes the container and its writable layer. Consequence: stop followed by start loses no writable-layer data; only rm does. Do not mix these two operations up in operations work.
Hands-on 1 — The full Nginx lifecycle
15 minutes
Run an Nginx container and go through the whole lifecycle (stop/start/rename/exec) to see the container state and process isolation (docker container, docker run).
docker run -d --name docker-lab -p 8080:80 nginx
1. Run: docker run -d --name docker-lab --restart always -p 8080:80 nginx, then docker ps and docker container port docker-lab.
The container is Up; PORTS has 0.0.0.0:8080->80/tcp; browsing to http://<ip>:8080 shows the Nginx page.
2. stop → check → start: docker container stop docker-lab, docker ps -a, docker container start docker-lab.
After stop, STATUS = Exited; after start, the website is reachable again.
3. rename + exec inside: docker container rename docker-lab web1, docker exec -it web1 /bin/sh then hostname, hostname -i (or cat /etc/hosts); from the host, compare with docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' web1 and hostname -I.
Renaming does not affect operation; the hostname/IP inside the container differ from the host.
Analysis
Observation: The container moves through the Up/Exited states; inside, it has its own hostname/IP.
Mechanism: stop/start control the main process; namespaces give the container its own hostname/network.
Lesson: stop ≠ rm; the container is preserved across stop/start and is lost only on rm.
Troubleshooting:
- curl localhost:8080 refused: Check that the PORTS column of docker ps has 0.0.0.0:8080->80/tcp; if it is missing, run it again with -p 8080:80.
Hands-on 2 — Proving immutability with a hot edit
10 minutes
Hot-edit index.html → reloading shows the change; delete the container and run it again from the same image → back to the default. This proves that images are immutable and containers do not keep state (Docker: volumes).
docker exec -it web1 sh -c 'echo "Hello there" > /usr/share/nginx/html/index.html'
1. Hot edit: docker exec -it web1 sh -c 'echo "Hello there" > /usr/share/nginx/html/index.html' then reload the browser.
The web page shows "Hello there" — the hot edit takes effect immediately.
2. Delete the container: docker container stop web1 && docker container rm web1.
The container disappears from docker ps -a.
3. Run again from the same image: docker run -d --name web1 -p 8080:80 nginx, reload.
The content REVERTS to the default "Welcome to nginx!" — the hot edit is gone.
Analysis
Observation: After rm and running again from the same image, the web content goes back to the default.
Mechanism: The change lives in the writable layer, which is deleted together with the container; the read-only image is unchanged.
Lesson: Images are immutable; lasting changes require building a new image, and state that must persist is written to a volume.
Hands-on 3 — Real-time logs and events
15 minutes
Follow logs in real time while generating load, and catch lifecycle events with docker events — the basis for monitoring unstable containers (docker logs, docker events). Keep using the web1 container from phases 1-2.
docker container logs -f web1
1. Terminal A: docker container logs -f web1. Terminal B: for i in $(seq 1 50); do curl -s localhost:8080/req-$i >/dev/null; done.
Terminal A shows about 50 access log lines appearing one after another, matching the 50 requests.
2. Terminal A: docker events --filter container=web1. Terminal B: docker restart web1, docker stop web1, docker start web1.
Terminal A shows the kill/die/start/restart/stop events corresponding to each action.
3. Check resources: docker stats --no-stream.
It shows the container's CPU%/MEM.
Analysis
Observation: The number of log lines grows exactly with the number of requests; events accurately reflect the lifecycle actions.
Mechanism: Docker captures stdout/stderr as the container log; the daemon emits real-time events for every state change.
Lesson: Combine logs + events + stats to detect and alert on abnormal container restarts/stops.
Troubleshooting:
- docker events shows nothing: events are only emitted in real time when something happens; make sure the filter matches the right container id/name and perform the actions in another terminal.
Review questions
Question 1. After you exec-edit index.html, then docker rm and docker run again from the SAME image, what does the web content look like?
- The edited content is kept
- It reverts to the image default (the change disappears)
- The container cannot run again
- The content renders with an error
Answer: It reverts to the image default (the change disappears). A hot edit lives in the writable layer, which is deleted together with the container on rm; running again from the same (read-only) image gives the default content — images are immutable and containers do not keep state (Docker: volumes).
Question 2. How does -p 127.0.0.1:8080:80 differ from -p 8080:80?
- There is no difference
- 127.0.0.1 allows access only from the host itself; without the IP it is published on 0.0.0.0 (every interface)
- 8080:80 only works on Windows
- 127.0.0.1 is faster
Answer: 127.0.0.1 allows access only from the host itself; without the IP it is published on 0.0.0.0 (every interface). Binding to 127.0.0.1 limits access to loopback (the host only); omitting the IP publishes on 0.0.0.0, so other machines can reach it via the server IP (docker run).
Question 3. Which logs does docker logs show?
- All of the application's log files inside the container
- The stdout/stderr of the main process in the container
- The host kernel's logs
- Only error logs
Answer: The stdout/stderr of the main process in the container. docker logs captures the main process's stdout/stderr (stored in /var/lib/docker/containers/<id>/<id>-json.log); logs the app writes to its own files (such as /var/log/nginx/) are a different kind (docker logs).
Question 4. Which command shows a container's CPU/RAM usage in real time?
- docker events
- docker stats
- docker top
- docker inspect
Answer: docker stats. docker stats shows CPU%/MEM in real time for containers, similar to top/htop but for containers (docker stats).
Question 5. What does docker container top tell you about isolation?
- It shows the host's processes too
- It shows only the processes inside the container, not the host's init/systemd
- It shows no processes at all
- It shows the processes of every container
Answer: It shows only the processes inside the container, not the host's init/systemd. top lists the processes inside the container; because the PID namespace isolates them, the host's management processes are not visible — evidence of process isolation (docker container).
Question 6. How does the RestartPolicy "unless-stopped" differ from "always"?
- There is no difference
- unless-stopped does NOT restart the container automatically if it was stopped deliberately (but it still restarts on reboot)
- always only runs once
- unless-stopped never restarts
Answer: unless-stopped does NOT restart the container automatically if it was stopped deliberately (but it still restarts on reboot). always keeps trying to restart; unless-stopped restarts unless you stopped it deliberately (it still comes back up after a reboot) — avoiding constant restarts when you stopped it on purpose (docker run §restart).
Flashcards
-
What is an image digest for? A hash that ensures the downloaded image is intact and has not been tampered with; each new build has a different digest. It verifies the integrity of the image.
-
When is docker image history useful? It shows the image's layer history/changes — useful for teams that BUILD their own images; rarely needed if you only pull ready-made images.
-
stop vs rm? stop → Exited (the container still exists and can be started again); rm → deletes the container and its writable layer for good (stop it first if it is running).
-
pause vs stop? pause freezes the process (the container is "alive" but does not respond); stop fully stops the main process and moves the container to Exited.
-
docker top vs docker exec? top: looks from the outside and lists the processes inside (shows the isolation). exec -it: goes inside and opens an interactive session.
-
Hot edit vs rebuild? A hot edit (exec writing a file) is only temporary and is lost on recreate. The right way: edit the source → build a new image → replace.
-
Container logs vs app logs? Container log = the stdout/stderr Docker captures (docker logs). App log = files the app writes itself (e.g. /var/log/nginx/).
-
docker stats vs docker events? stats = CPU/RAM resources in real time. events = real-time start/stop/kill/restart events from the daemon/containers.
-
Does docker events store anything long term? No — it only keeps a recent number of events in memory; filter by time with --since. You need an external tool to store them.