Lab 02 - Docker containers

Lab 02 - Docker containers

Goal: the container lifecycle, and why the writable layer matters. Cheat sheet: Docker

# 1 - the shortest possible container
sudo docker run hello-world
sudo docker ps                       # nothing - it already exited
sudo docker ps -a                    # there it is, Exited (0)

A container lives exactly as long as its main process. hello-world prints and exits, so the container is finished before docker ps can see it. This is the same reason a Kubernetes Pod with no long-running process ends up in CrashLoopBackOff.

# 2 - interactive; exiting the shell ends it, --rm cleans up
sudo docker run -it --rm busybox sh
  hostname                           # a container ID, not the host name
  ip address                         # its own network namespace
  ps aux                             # PID 1 is your shell - its own PID namespace
  exit

Those three commands are the whole isolation story: the process sees its own hostname, network and process table, but it is running on support01’s kernel.

# 3 - a long-running one with a published port
sudo docker run -d --name web -p 8080:80 nginx:1.27
sudo docker ps
curl -s localhost:8080 | head -5

-p 8080:80 maps a port on support01 to a port in the container. Without it the container is reachable only from inside the Docker network.

# 4 - look inside a running container
sudo docker logs web                 # whatever the process wrote to stdout
sudo docker top web                  # its processes, as seen from the host
sudo docker exec -it web sh -c 'ls /usr/share/nginx/html; nginx -v'
sudo docker inspect -f '{{.NetworkSettings.IPAddress}}' web

logs, exec and inspect become kubectl logs, kubectl exec and kubectl get -o yaml. Learning them now is not wasted time.

# 5 - stop, start, restart - the filesystem survives
sudo docker exec web sh -c 'echo hello > /tmp/marker'
sudo docker restart web
sudo docker exec web cat /tmp/marker     # still there
sudo docker stop web
sudo docker ps -a                        # Exited
sudo docker start web

Stopping does not destroy the writable layer - only docker rm does.

# 6 - the writable layer disappears with the container
sudo docker rm -f web
sudo docker run -d --name web -p 8080:80 nginx:1.27
sudo docker exec web cat /tmp/marker     # No such file

That is the entire argument for volumes, and later for PersistentVolumes.

# 7 - resource limits
sudo docker run -d --name small --memory 64m --cpus 0.2 nginx:1.27
sudo docker stats --no-stream small web

--memory and --cpus are cgroup limits - the same mechanism behind resources.limits on a Kubernetes container.

Clean up

# 8 -
sudo docker rm -f web small
sudo docker ps -a