Lesson 1 of 9 · 12 min · Containers and images

What containers are, and how to run them

Covers: Docker Engine 29 with Compose 5 and BuildKit on Ubuntu 24.04; images alpine 3.20, nginx 1.27, python 3.12. Updated 13 Nov 2026. Part of the DevOps Engineer roadmap.

What you will learn

  • What a container is and what it is not
  • Containers versus virtual machines
  • The container lifecycle and the commands run, ps, logs, exec, stop, rm
  • Resource limits and what an OOM kill looks like
  • Why the form of CMD decides whether your container stops cleanly

In simple words

"It works on my laptop" is the oldest problem in software. A container fixes it by packing a program together with everything it needs into one sealed box, like a tiffin box that holds the whole meal. The box runs the same way on any machine. This lesson explains what that box is and how to start, check and stop one.

Words to know

  • Container: a running program, sealed off from the rest of the machine, with its own files and settings.
  • Image: the packed, ready-to-run copy that containers are started from.
  • Docker: the most common tool for building and running containers.
  • Virtual machine: a whole pretend computer with its own operating system. It is heavier than a container.

The problem containers solve

"It works on my machine" is an old problem: the app depends on a language version, libraries, system packages and config that differ between laptop, test and production. A container packages an application together with everything it needs to run (except the kernel) and runs it in isolation, so it behaves the same everywhere there is a container runtime.

A container is a process

This is the most important idea of the whole course. A container is not a small virtual machine. It is a normal Linux process (or a few) that the kernel runs with three kinds of restrictions:

  • Namespaces give the process its own view of the system: its own process tree (the main process is PID 1), network interfaces, hostname, mount points (its own filesystem), and users.
  • cgroups (control groups) limit how much CPU, memory and I/O the process may use.
  • Capabilities, seccomp and other security layers restrict what it is allowed to do.

The filesystem it sees comes from an image: a read-only bundle of files (the app plus a minimal operating-system userland). All containers on a machine share one kernel: the host's. We saw it in the Linux course: uname -r inside a container shows the host kernel.

docker run --rm alpine:3.20 sh -c 'cat /etc/os-release | head -2; echo "I am PID $$"; hostname'
NAME="Alpine Linux"
ID=alpine
I am PID 1
f9fba2d9fd43

The shell inside is PID 1 of its own process namespace, and the hostname is the container's id. On the host that same process has an ordinary PID.

Containers versus virtual machines

Virtual machine Container
Isolation by a hypervisor emulating hardware kernel namespaces and cgroups
Has its own kernel yes no, shares the host kernel
Size gigabytes megabytes (alpine image: 12 MB)
Start time tens of seconds well under a second
Density per host tens hundreds
Isolation strength stronger (separate kernels) weaker (shared kernel), so harden carefully
Runs other OS kernels yes no, a Linux container needs a Linux kernel (Docker Desktop on Windows/macOS runs a small Linux VM underneath)

Use containers to package and deploy applications; use VMs when you need a different kernel or stronger isolation boundaries (and often both: containers running inside VMs in the cloud).

Docker's pieces

  • Image: the read-only template (the package).
  • Container: a running (or stopped) instance of an image, plus a thin writable layer.
  • Registry: a server storing images (Docker Hub, Amazon ECR, GitHub Container Registry).
  • Docker Engine: the daemon (dockerd) that builds and runs containers, and the docker CLI that talks to it. Under it sit containerd and runc, which are also what Kubernetes uses. The image format is an open standard (OCI), so other tools (Podman, containerd, Kubernetes) run the same images.

Running containers

docker run alpine:3.20 echo hello        # run a command in a new container, then it exits
docker run -it --rm alpine:3.20 sh       # interactive shell; --rm deletes the container on exit
docker run -d --name web1 nginx:1.27-alpine   # -d = detached (background), --name = a name you choose

If the image is not on the machine, Docker pulls it first (Unable to find image 'nginx:1.27-alpine' locally, then the layers download). Inspect and manage:

docker ps                      # running containers (add -a to include stopped ones)
docker logs web1               # what the main process wrote to stdout/stderr
docker logs -f --tail 50 web1  # follow
docker exec -it web1 sh        # open a shell inside a running container
docker stop web1               # ask it to stop (SIGTERM, then SIGKILL after 10 s)
docker rm web1                 # delete the stopped container
docker container prune         # remove all stopped containers

What we saw for the nginx container:

web1 nginx:1.27-alpine Up 1 second
PID   USER     TIME  COMMAND
    1 root      0:00 nginx: master process nginx -g daemon off;
   30 nginx     0:00 nginx: worker process
web1 Exited (0) Less than a second ago

docker exec ... ps shows the container's own view: nginx's master process is PID 1. After docker stop the container is Exited (0) but still exists until removed.

A container lives as long as its main process. When PID 1 exits, the container stops. That is why docker run -d alpine echo hello ends at once and why a service must run in the foreground (nginx -g 'daemon off;'), never daemonise itself.

Logs: write logs to stdout and stderr, not to files inside the container. Docker captures them (docker logs), and platforms like Kubernetes collect them from there.

The container filesystem is temporary. Changes are in a writable layer that disappears with the container. We proved it: a file written to /tmp in one container was not there in the next one (ls: /tmp/x: No such file or directory). Persistent data needs volumes (lesson 4).

Useful docker run options

Option Effect
-d, -it, --rm background; interactive terminal; auto-remove
--name choose a name
-p 8080:80 publish a port (lesson 6)
-e KEY=value, --env-file environment variables
-v / --mount storage (lesson 4)
--memory 512m, --cpus 1.5 resource limits
--restart unless-stopped restart policy for services
--user 10001:10001 run as a non-root user
--network which network to join

Resource limits and the OOM kill

Without limits a container can use all the host's memory. With --memory the kernel enforces the limit through cgroups. We started a Python process that tries to allocate 200 MB in a 20 MB container:

docker run -d --name oom --memory 20m python:3.12-slim python -c "x=bytearray(200*1024*1024)"
docker inspect oom --format 'exit={{.State.ExitCode}} oomkilled={{.State.OOMKilled}}'
exit=137 oomkilled=true

Exit code 137 is 128 + 9: the process was killed with SIGKILL by the out-of-memory killer. You will see exactly this as OOMKilled on Kubernetes pods. The cure is to fix a leak, raise the limit, or reduce memory use, not to keep restarting.

Signals and PID 1: why `docker stop` sometimes takes 10 seconds

docker stop sends SIGTERM to the container's PID 1 and waits (10 seconds by default), then sends SIGKILL. If PID 1 does not handle SIGTERM, it will not shut down gracefully. A process running as PID 1 gets no default signal handlers from the kernel: a program that has not installed a handler simply ignores SIGTERM.

The way you write CMD decides what PID 1 is. We built the same Python program (which handles SIGTERM) two ways:

CMD python /sig.py            # shell form: runs  /bin/sh -c "python /sig.py"
CMD ["python", "/sig.py"]     # exec form: runs python directly

The result when stopping each container:

shell form: docker stop took 10.2 s     (log shows only "started")
exec form:  docker stop took 0.1 s      (log shows "got SIGTERM, exiting cleanly")

In the shell form, PID 1 is /bin/sh, which does not pass SIGTERM on to Python, so Docker waited ten seconds and killed it. In the exec form, Python is PID 1, received the signal, and shut down at once. Always use the exec form (JSON array) for CMD and ENTRYPOINT. If you need a shell script as entrypoint, end it with exec "$@" so the real program replaces the shell. For programs that do not reap child processes or handle signals, docker run --init adds a tiny init process (tini) as PID 1.

Cleaning up

Stopped containers, old images and unused volumes accumulate and fill the disk. docker system df shows usage, docker system prune removes stopped containers, unused networks and dangling images (-a also removes unused images, --volumes volumes: read the prompt, volumes hold data).

Common mistakes

  • Treating containers like VMs: installing SSH, running several services in one container, storing data inside. One main process per container, data in volumes, logs on stdout.
  • Shell-form CMD and slow, unclean stops.
  • Running in the background with -d something that daemonises itself, so the container exits immediately.
  • No memory limits in shared environments.
  • Forgetting --rm on throwaway containers and filling the disk.
  • Believing a stopped container is gone. docker ps -a shows it.

Try it yourself

  1. Run docker run -d --name web1 nginx:1.27-alpine, check docker ps, docker logs, docker exec web1 ps, then stop and remove it.
  2. Run docker run --rm alpine sh -c 'echo $$' and explain the number. Compare with echo $$ in a host terminal.
  3. Reproduce the OOM kill with --memory 20m and read OOMKilled with docker inspect.
  4. Write a small script that traps SIGTERM, run it with shell-form and exec-form CMD, and time docker stop.

Check yourself

What is a container, technically?

An ordinary Linux process (or group of processes) isolated with namespaces (own view of processes, network, filesystem), limited with cgroups, and restricted with capabilities and seccomp. It shares the host kernel.

Name three differences between a container and a virtual machine.

A container shares the host kernel while a VM has its own; containers are megabytes and start in milliseconds while VMs are gigabytes and start in seconds; VM isolation is stronger because the boundary is a hypervisor rather than the kernel.

Why does a container stop immediately if its main process forks into the background?

A container lives as long as its PID 1 process. If that process exits (having daemonised its work), the container stops. Services must run in the foreground.

What does exit code 137 with OOMKilled=true mean?

The kernel killed the container's process with SIGKILL (128 + 9) because it exceeded its memory limit.

Interview questions

What happens when you run docker run nginx?

The CLI asks the Docker daemon; if the image is missing locally it is pulled from the registry; the daemon creates a container with a writable layer on top of the image, sets up namespaces, cgroups and a network interface, and starts the image's command as PID 1.

Why should logs go to stdout and stderr in containers?

The runtime captures those streams, so docker logs, Kubernetes and log collectors can read them, and no log files fill the container's temporary filesystem.

What is the difference between CMD ["a","b"] and CMD a b?

The first (exec form) runs the program directly as PID 1 so it receives signals. The second (shell form) runs it through /bin/sh -c, so the shell is PID 1 and signals such as SIGTERM usually do not reach the program.

Summary

  • A container is an isolated, resource-limited Linux process using an image's filesystem and the host kernel.
  • Containers are light and fast, VMs are strongly isolated; they are often combined.
  • Lifecycle: run, ps, logs, exec, stop, rm; the container lives as long as PID 1; its filesystem is temporary; logs go to stdout.
  • Use exec-form CMD, set memory limits, and know that 137 means SIGKILL, often from the OOM killer.

Going deeper

See how much of this you can explain

A free mock interview asks you new questions on Docker and containers for DevOps Engineer and scores every answer, with what to fix.