Back to the catalogue Courses

Docker and system administration: operating an application stack

Build an image, operate a Docker Compose stack, diagnose failures, back up, restore and roll back.

MDJAD Intermediate 36 min read

Objectives and prerequisites

By the end of this course, you will be able to build an image, run an application stack with Docker Compose, diagnose a startup or connection failure, back up and restore data, then update and roll back without losing state. The common thread is a small PHP catalogue with its MariaDB database, first on a development machine and then on a laboratory server.

Prerequisites: use a terminal, read a simple YAML file and understand what a process is. The examples use Docker Engine 27 or later and Docker Compose v2. On macOS or Windows, Docker Desktop runs containers in a Linux virtual machine; on Linux, the engine uses the host kernel directly. This difference explains some performance and permission behaviour.

Path: chapters 1 to 4 cover the execution model, images and builds; chapters 5 to 7 cover data, networking and Compose; chapters 8 to 12 cover configuration, permissions, resources, diagnosis, backups and synthesis. Expect about thirty-five minutes of reading and five to seven hours of practice.

Convention: commands run in a laboratory directory containing compose.yaml and Dockerfile. Published ports use localhost. Passwords shown are fictional and must never be versioned. Destructive commands are flagged; do not run them on an environment holding data you need.

1. Processes, host, virtualisation and isolation

A container is an isolated process on the host kernel, not a small virtual machine. Docker uses kernel namespaces to isolate the view of the filesystem, processes, network and users, and control groups to limit resources. The process therefore runs directly on the Linux kernel, which makes it lightweight, but it shares that kernel with the host and other containers.

A virtual machine embeds a complete operating system and its own kernel. It isolates more strongly and can run a different kernel, but it boots more slowly and consumes more resources. A container usually starts in under a second and suits application services. The choice depends on the isolation requirement, the guest system and host constraints.

On macOS and Windows, Docker Desktop creates a Linux virtual machine that hosts the engine and containers. Files mounted from the Mac cross a sharing layer, which can slow input/output and alter permissions. On Linux, a directory mount is more direct. These differences do not change the concepts, but they explain why a command can be fast on a server and slow on a development machine.

# Check the engine, context and version
docker version
docker context show
docker info --format '{{.ServerVersion}} {{.Driver}} {{.OSType}}'
# Run an isolated process and remove it on exit
docker run --rm alpine:3.20 sh -c 'echo hello; uname -a'

A container's main process is PID 1 in its namespace. It must stay in the foreground and handle signals, otherwise the container exits immediately or ignores stop requests. A web server or database does this naturally; a script that starts a daemon in the background then exits makes the container look finished. Use exec in entrypoint scripts to replace the shell with the main process.

Isolation is not an absolute security boundary. A container that mounts the Docker socket, runs privileged or shares the host network can affect the whole system. Good practice drops capabilities, uses a non-privileged user, limits mounts and publishes only necessary ports. A container is not a magic sandbox: it is a process with security settings that must be verified.

Host resources are shared. A container without limits can consume all memory and cause other services, including the Docker engine, to stop. Memory, CPU and process limits are not only about performance: they protect availability. In development, generous limits are acceptable; in production, they must be sized and monitored.

Finally, distinguish the image from the container. The image is an immutable template; the container is a running instance with an ephemeral writable layer. Deleting and recreating a container from the same image starts from a clean state, except for volumes. This separation is the basis of reproducibility: the image describes the software, the volume keeps the data, the configuration describes the environment.

Control groups, or cgroups, limit and account for memory, CPU, input/output and process count. A container exceeding its memory limit is killed by the kernel, which explains exit code 137. Namespaces isolate what the process can see: filesystem tree, PIDs, network, users, mount points. Docker combines both, but the final configuration depends on the options passed to the container and the capabilities of the host kernel.

This separation also brings development and production closer. The same image can run on a workstation and a server, with different variables and volumes. Remaining differences must be explicit: kernel version, resources, network, certificates, data. A development stack using SQLite while production uses MariaDB does not test the same behaviour. Reduce the gaps, or document those that are unavoidable.

Containers are well suited to stateless services, batch jobs and development environments. Virtual machines remain relevant for strong isolation, different kernels, desktop operating systems and workloads that need a full machine. Many production systems combine both: containers on virtual machines, with the hypervisor providing the outer boundary. Choose the smallest isolation that meets the risk, and do not assume one technology replaces the other in every context.

2. Images, containers, registries and layers

An image is built from a base filesystem and a series of instructions. Each instruction creates a layer; layers are stacked and shared between images. A registry stores and distributes images. docker pull downloads missing layers, docker push publishes an image, and docker run creates a container from a local or remote image.

Layers are read-only. The container adds a writable layer where file changes are stored. Deleting a file in an upper layer does not free space in the lower layer: it creates a whiteout entry. This is why an image that copies then deletes large files in separate instructions remains large. Group operations and clean up in the same layer.

# Minimal example, completed in later chapters
FROM php:8.4-apache
RUN docker-php-ext-install pdo_mysql \
    && a2enmod rewrite
COPY public/ /var/www/html/
EXPOSE 80
CMD ["apache2-foreground"]

An image name includes a repository, a tag and optionally a digest. php:8.4-apache is a moving tag; php:8.4.12-apache is more precise; a digest identifies exact content. Moving tags are convenient in development but can change without notice. For production, pin a precise version or digest and document updates.

A container must be disposable. Do not store important data in its writable layer: it disappears with the container and is not backed up by usual tools. Configuration files may be copied into the image or mounted; business data goes into a volume or a database. A recreated container must start without manual intervention.

Public registries impose download limits and may be unavailable. In production, use a controlled registry, authenticate pulls and verify signatures or digests. Do not pull latest in production without a validation process: you will not know which version is actually running. Keep a record of the deployed digest.

Images often contain more than needed: build tools, caches, development files. A smaller image downloads faster, exposes fewer components and reduces the attack surface. Multi-stage builds compile in one image and copy only the result into a final image. We cover them in chapter 4.

Modern images often follow the OCI specification, which defines the image format, manifest and runtime configuration. This standardisation lets Docker, Podman, containerd and other tools consume the same images. A manifest describes layers and platform (architecture, operating system); a multi-architecture image may contain several variants. Understanding this format helps diagnose platform errors, such as an ARM image pulled on an x86 server.

Analyse images before deploying. Scanners detect known vulnerable packages in layers, but they do not replace a version policy or a configuration review. An image with no known vulnerability can still be dangerous if it runs as root or exposes an unnecessary port. Combine scanning, regular rebuilds and privilege checks. Keep results and address critical vulnerabilities before production.

Inspect image size and contents rather than guessing. docker image history shows layers and their size; docker image inspect gives configuration and metadata. A tool such as Dive visualises layers and helps find unnecessary files, but the decision remains yours: a large documentation package may be acceptable, a compiler in a runtime image usually is not. Smaller images are not automatically safer, but they are easier to transfer, scan and reason about.

3. Lifecycle, main process and inspection

Lifecycle commands are simple: docker run creates and starts, docker stop requests a stop, docker start restarts, docker rm removes. docker ps lists running containers, docker ps -a includes stopped ones. A stopped container keeps its writable layer and configuration until removal.

docker run -d --name catalogue -p 8080:80 catalogue:1.0
docker ps
docker logs -f catalogue
docker inspect catalogue --format '{{.State.Status}} {{.Config.Image}}'
docker exec -it catalogue sh
docker stop catalogue && docker rm catalogue

docker logs shows the main process's standard output and standard error. An application must write logs to these streams, not an internal file, so docker logs and logging drivers work. docker exec opens an additional process in the running container; it does not start the main service and does not persist after the container is removed.

docker inspect returns detailed JSON: state, image, environment variables, mounts, network, restart policy. Use --format to extract a precise field rather than reading the whole document. docker stats shows CPU, memory, network and disk usage in real time. docker top lists the container's processes.

Exit codes tell a story. 0 indicates a normal end; 1 an application error; 137 a process killed by SIGKILL, often after a memory limit; 143 a stop by SIGTERM. docker inspect --format '{{.State.ExitCode}}' and {{.State.OOMKilled}} help distinguish a bug from a resource limit.

The restart policy (no, on-failure, always, unless-stopped) determines what happens after a stop or host reboot. always can hide a configuration error by restarting in a loop; on-failure with a limited number of attempts is often healthier. Monitor repeated restarts and read the logs instead of ignoring them.

Finally, do not remove a container to "fix" it without understanding. docker rm erases the writable layer; docker rm -f forces stop and removal. If data lived in the container, it is lost. Prefer inspecting, reading logs, checking mounts, then recreating from a controlled image and volumes.

Stopping a container sends SIGTERM to the main process, waits a delay (ten seconds by default), then sends SIGKILL. An application ignoring SIGTERM is killed abruptly and may leave incomplete files or transactions. Configure stop_grace_period in Compose and test clean shutdown. A well-configured web server or database finishes in-flight requests; a custom script must provide a signal handler.

Choose the logging driver according to the environment. json-file is simple and local but can fill the disk; configure rotation. local is more economical; syslog, journald or fluentd drivers send logs to a central system. In production, centralise logs to survive container loss and correlate several services. Verify that metadata does not expose secrets and that retention meets your obligations.

docker cp copies files between a container and the host, which is useful for extracting a log or a generated artefact, but it is not a backup strategy and can bypass intended permissions. Prefer a controlled export from the application or a dump from the database. Copying files out of a running production container can capture an inconsistent state, and copying files in can change behaviour outside the image build. Treat docker cp as a diagnostic tool, not an operational one.

4. Dockerfile, context, cache and rebuild

The Dockerfile describes the image build. FROM chooses the base image, RUN executes a command during the build, COPY adds files, WORKDIR sets the working directory, ENV defines a variable, EXPOSE documents a port, USER chooses the user, CMD and ENTRYPOINT define the startup command.

FROM php:8.4-apache AS runtime
WORKDIR /var/www/html
RUN docker-php-ext-install pdo_mysql \
    && a2enmod rewrite \
    && rm -rf /var/lib/apt/lists/*
COPY --chown=www-data:www-data public/ ./
COPY docker/apache.conf /etc/apache2/sites-available/000-default.conf
USER www-data
EXPOSE 80
CMD ["apache2-foreground"]

The build context is the set of files sent to the engine. An oversized context slows the build and may send secrets or unnecessary data. A .dockerignore file excludes .git, node_modules, vendor, log files and local variables. Check what enters the context before building.

The build cache reuses layers whose instruction and inputs have not changed. Place stable instructions first and frequently modified files last: copying all code before installing dependencies invalidates the cache on every change. docker build --no-cache forces a full rebuild, useful to verify reproducibility, not for every build.

Multi-stage builds separate compilation from execution. A stage with build tools produces artefacts; the final stage copies them into a minimal image. This reduces size and attack surface. For PHP, it can install extensions or compile assets; for Node, build the front end then copy the result into Nginx.

CMD provides a default command, replaceable by docker run arguments. ENTRYPOINT sets the base command and receives the arguments. Use the JSON form (["executable", "arg"]) to avoid an intermediate shell and transmit signals correctly. If you must initialise files then launch the service, end the script with exec "$@".

An image must be reproducible: same inputs, same result. Avoid commands that download an unpinned version, embed dates or fetch unverified network dependencies. Record the base image digest, lock package versions and test the build in a clean environment. An image that does not rebuild identically is hard to audit and restore.

Build arguments (ARG) are available during the build, unlike runtime environment variables. They can pass a version or distribution channel, but must not contain secrets: their value may appear in image history and metadata. A Dockerfile analyser such as Hadolint flags risky instructions and poor practice. Integrate it into the validation chain rather than an occasional review.

BuildKit, the modern builder, can cache mounts, parallelise stages and produce multi-platform images. docker buildx build --platform linux/amd64,linux/arm64 builds for several architectures, provided instructions do not depend on the platform. Verify the result on each target architecture, because an image that builds does not guarantee it runs. Document the builder and platform used for production.

Instruction order affects cache reuse in subtle ways. A RUN apt-get update separated from RUN apt-get install can reuse a stale package index; combine them and clean the cache in the same layer. A COPY . . before dependency installation invalidates everything after it when any file changes. Use specific COPY instructions, pin package versions where possible and review the build log to see which layers were cached. The build log is a diagnostic document, not noise.

5. Ephemeral filesystem, volumes and mounts

A container's writable layer is ephemeral: it disappears with the container. To keep data, use a named volume or a host directory mount. A volume is managed by Docker, stored outside the container layer and survives its removal. A bind mount points to a host path and allows live file editing, at the cost of a dependency on the workstation layout.

# Named volume for MariaDB data
docker volume create catalogue_db
docker run -d --name db \
  -e MARIADB_ROOT_PASSWORD=lab-root \
  -e MARIADB_DATABASE=catalogue \
  -v catalogue_db:/var/lib/mysql \
  mariadb:10.6

# Bind mount for code in development
docker run --rm -v "$PWD/public:/var/www/html" php:8.4-cli ls /var/www/html

A named volume is preferable for production data: Docker manages it, it can be backed up and it is not tied to a user path. A bind mount is convenient in development to reload code without rebuilding the image; in production, it couples the container to the host tree and complicates permissions. Choose according to use, not habit.

Permissions are a frequent source of errors. In a Linux container, the www-data user has a UID that must match volume or bind mount rights. On macOS, permission translation differs. If the application cannot write to uploads, check UID, GID and directory rights before running the container as root. chown in the Dockerfile does not apply retroactively to an existing volume.

Read-only mounts limit damage: -v config:/app/config:ro prevents the process from modifying configuration. For temporary files, a tmpfs avoids disk writes and disappears on stop. For secrets, do not mount them in a volume shared with other services. Every mount must have a justification and minimal rights.

Persistence is not only about files. A database needs a volume for its files, but also a coherent backup strategy. Copying the data directory while running can produce an inconsistent backup; use a logical dump or a suitable backup tool. The volume guarantees survival, not backup quality.

Finally, docker volume ls, docker volume inspect and docker volume rm manage volumes. Removing a volume is permanent. docker compose down -v removes declared volumes: never run it on an environment you need. Document which volumes hold data and which are only caches.

Backing up a volume is not just copying its directory. For application files, stop the service or use a consistent snapshot; for a database, prefer a dump. A cache volume can be recreated without backup, but an uploads volume holds user data that must be protected and restored. Classify each volume and test restoration in a separate container, with the same UID and permissions as production.

Volume drivers depend on the platform and host. A local volume does not survive host loss; a network volume or object storage may be needed for high availability. Check durability, performance and backup guarantees before choosing. A local volume is perfect for a laboratory but does not replace an off-site backup strategy. Document the driver, path and backup responsibilities.

Choose between a volume and a bind mount from the requirement, not convenience. Use a named volume for data Docker should manage, a bind mount for source code and configuration you edit on the host, and a tmpfs for disposable temporary files. In production, bind mounts require a clear ownership model and a deployment process that keeps host files in sync. A volume is not automatically backed up, and a bind mount is not automatically portable. Write the choice down for each mount.

6. Networks, internal DNS and published ports

By default, a container has a network interface and can reach the outside. Containers on the same user-defined network can reach each other by service name through Docker's internal DNS. A container cannot reach another through localhost: localhost refers to the container itself, not the host or other services.

docker network create catalogue_net
docker run -d --name db --network catalogue_net mariadb:10.6
docker run -d --name app --network catalogue_net -p 8080:80 php:8.4-apache
# From app, the database is reachable at "db:3306"
docker exec -it app getent hosts db

Publishing a port with -p 8080:80 exposes container port 80 on host port 8080. Do not publish the database port on the host if it does not need external access. Services should communicate on an internal network, and only the reverse proxy or web server exposes a public port. This reduces the attack surface and avoids port conflicts.

Internal DNS resolves container names and network aliases. A service name in Compose becomes a hostname for other services. If resolution fails, check that services share the network, that the name is correct and that the service is running. getent hosts, nslookup or ping from a diagnostic container help isolate the problem.

Ports exposed in the Dockerfile with EXPOSE are documentary; they publish nothing. Only -p or Compose's ports section publishes. This distinction prevents believing a service is accessible when it is not, or the reverse. Check with docker port and from outside, not only from inside the container.

Custom networks also provide isolation. One network per application stack prevents unrelated containers from reaching each other. For test environments, create a dedicated network and remove it with the stack. host and none networks have specific uses: host shares the host network stack and reduces isolation; none isolates completely, useful for offline processing.

Host firewalls and proxies can interfere. A port published on 127.0.0.1 is reachable only from the host, which is safer than a port open on all interfaces. In production, place a reverse proxy in front of services, terminate TLS at the right place and limit published ports to the strict minimum. A container network is not automatically protected by the host firewall.

A port conflict occurs when a host port is already in use. docker compose ps, lsof -i :8080 or ss -ltnp identify the offending process. Change the published port or stop the competing service, but do not change the internal port without reason: other services know it. In production, a reverse proxy can route several domain names to several containers on the same port 80/443, avoiding one published port per application.

A reverse proxy terminates TLS, adds security headers, rate-limits and routes to containers. It becomes a critical point: its configuration must be versioned, tested and monitored. Place it on a network that can reach the services, but do not expose the services directly. Check forwarded headers (real address, protocol) and the trust the application grants them. A bad configuration can break secure cookies or distort logs.

Be explicit about address families and bind addresses. A service listening only on IPv4 may be unreachable over IPv6, and a port published on all interfaces may be exposed beyond the intended network. Bind to 127.0.0.1 for local-only access, verify with ss -ltnp and test from another machine. Container networking is powerful but not self-documenting; the effective listening address is part of the design.

7. Compose: declare, read and operate the stack

Compose describes several services in a YAML file. Each service specifies an image or build, variables, volumes, networks, ports and a restart policy. docker compose up -d creates and starts the stack, docker compose ps shows status, docker compose logs -f follows logs, docker compose down stops and removes containers and networks.

services:
  app:
    build:
      context: .
      dockerfile: Dockerfile
    ports:
      - "127.0.0.1:8080:80"
    environment:
      APP_ENV: dev
      DB_HOST: db
      DB_NAME: catalogue
      DB_USER: catalogue
      DB_PASSWORD: ${DB_PASSWORD:?set DB_PASSWORD}
    volumes:
      - uploads:/var/www/html/uploads
    depends_on:
      db:
        condition: service_healthy
    restart: unless-stopped

  db:
    image: mariadb:10.6
    environment:
      MARIADB_DATABASE: catalogue
      MARIADB_USER: catalogue
      MARIADB_PASSWORD: ${DB_PASSWORD:?set DB_PASSWORD}
      MARIADB_ROOT_PASSWORD: ${DB_ROOT_PASSWORD:?set DB_ROOT_PASSWORD}
    volumes:
      - db_data:/var/lib/mysql
    healthcheck:
      test: ["CMD", "healthcheck.sh", "--connect", "--innodb_initialized"]
      interval: 10s
      timeout: 5s
      retries: 10
    restart: unless-stopped

volumes:
  uploads:
  db_data:

depends_on controls startup order, not actual availability. With condition: service_healthy, Compose waits for the service healthcheck to pass. Without a healthcheck, a service may be "started" while the database is not yet accepting connections. Add a healthcheck to the database and test a cold start, not only a warm restart.

docker compose config shows the resolved configuration, with interpolated variables and defaults. Use it before starting to check paths, ports and variables. docker compose config --quiet validates syntax without printing content. A missing variable can silently produce an empty string; the ${VAR:?message} syntax fails startup with a clear message.

docker compose up --build rebuilds images before starting. docker compose up -d --force-recreate recreates containers even if the image has not changed. docker compose down keeps named volumes; down -v removes them. docker compose down --remove-orphans removes containers for services no longer declared. Choose the option matching the objective consciously.

Compose profiles keep development services out of the production stack, such as Adminer or a test mail server. profiles: ["dev"] and docker compose --profile dev up enable the service on demand. This separation avoids exposing administration tools in production while keeping a single readable file.

Finally, version the Compose file and test it in a clean environment. A file that works on its author's machine may depend on an existing volume, an undocumented variable or an occupied port. The reference test is: clone the repository, copy the example environment file, docker compose up, verify the application. If this path fails, the documentation is incomplete.

docker compose watch, available in recent versions, synchronises changed files or rebuilds the service according to declared rules. It improves development without replacing a bind mount or a full staging rebuild. Use it with a correct .dockerignore and verify that synchronised files do not contain secrets. The feature depends on the Compose version; document the prerequisite.

Override files, such as compose.override.yaml, adapt the stack for development without duplicating the main file. Compose merges them automatically. Use this to mount code, expose a debug port or enable a profile, but keep the base file clean and test the resolved configuration. A forgotten override can explain why production behaves differently from the repository.

Scaling stateless services with docker compose up --scale app=3 requires care: published host ports conflict unless removed, and session state must be shared or stored outside the container. Stateful services such as databases do not scale by simply adding replicas; they need replication, failover and a consistent write model. Compose is excellent for a small stack, but it is not a cluster orchestrator. Know the limit before designing for it.

8. Variables, configuration and secrets

An image must be independent of the environment. Values that change between development, staging and production — database address, password, log level — must be injected at runtime, not frozen into the image. This lets you promote the same image from one environment to another and reduces differences.

Environment variables are easy to use, but visible in docker inspect, in processes and sometimes in logs. Do not put a durable secret in an environment variable if a better mechanism is available. For a laboratory, an unversioned .env file is enough; for production, use a secret manager or the orchestrator's secrets.

# Local .env file, ignored by Git
DB_PASSWORD=change-me-lab
DB_ROOT_PASSWORD=change-me-root

# Check the resolved configuration without printing secrets
docker compose config --quiet
# Inspect a container's variables (beware of secrets)
docker inspect app --format '{{range .Config.Env}}{{println .}}{{end}}'

Compose supports secrets in a limited way: a secret can be mounted as a file in the container. The file does not appear in the process environment, but it is readable by the container user. Protect permissions, mount it read-only and do not copy it into the image. For a more robust deployment, an external manager injects secrets at startup or exposes them through a service identity.

Configuration must be validated at startup. An application that starts with an empty connection string and fails on the first request is harder to diagnose than one that refuses to start with a clear message. Check the presence and format of critical variables without printing their value. An error message should say which variable is missing, not the secret itself.

Never version a .env containing secrets. Provide a .env.example with fictional values and comments. Add .env to .gitignore and check Git history if a secret was exposed. Removing the file from the last commit is not enough: revoke and replace the secret.

Finally, distinguish build configuration from runtime configuration. A variable used during RUN or COPY is part of the image; a variable provided to docker run or Compose belongs to the container. Build arguments can appear in image history; do not use them for secrets. The boundary between the two is a design decision, not a detail.

Docker Swarm secrets are encrypted at rest and mounted into the containers of the relevant services; Compose alone does not provide the same guarantee. Do not confuse the two modes. If you use Compose for production, an external secret manager or read-only mounted files with strict permissions are often safer than environment variables. Whatever the method, plan rotation and revocation.

Understand variable precedence: the shell environment, the .env file, the Compose file and command-line arguments can overlap. A variable exported in the shell can mask the file value and explain unexpected behaviour. docker compose config shows the resolved value, but be careful not to display it in front of an audience. Document the precedence order and use explicit names to avoid collisions between services.

When a secret is mounted as a file, check its ownership and mode inside the container. A file readable by every user in the container may be exposed to a compromised process, and a file owned by root may be unreadable by a non-privileged application. Prefer a dedicated group, mode 0400 or 0440, and read it once at startup rather than on every request. Delete temporary copies and never write the secret to a log or a crash report.

9. Users, permissions, resources and protections

By default, many images run as root. A root process in a container has broad rights over mounted files and may, depending on configuration, affect the host. Create a non-privileged user in the Dockerfile, give it the necessary rights on useful directories and declare USER before CMD. Verify with docker exec id.

FROM php:8.4-apache
RUN useradd --create-home --uid 10001 app \
    && mkdir -p /var/www/html/uploads \
    && chown -R app:app /var/www/html
USER app
WORKDIR /var/www/html
CMD ["apache2-foreground"]

Volume permissions are independent of the image. A volume created before the non-privileged user may belong to root; the process cannot write to it. Fix rights when creating the volume or through an initialisation script, and document the UID used. On macOS, bind mounts can hide Linux permissions; test on a Linux machine before concluding.

Limit resources with --memory, --cpus, --pids-limit or Compose's deploy.resources section. A too-low memory limit causes OOM kills; too high lets a service starve others. Measure actual consumption and allow a margin. Monitor docker stats and oom events.

Reduce privileges: --read-only for a read-only root filesystem, with tmpfs for temporary directories; --cap-drop ALL then add only strictly necessary capabilities; --security-opt no-new-privileges. These options can break a poorly designed image, but they reveal unnecessary dependencies. Test the application after each restriction.

Never mount the Docker socket into an application container: it is equivalent to giving root access to the host. Avoid --privileged, mounting / and unnecessary devices. If a service needs specific features, document why and limit them. A stack's security is judged by its actual permissions, not its diagram.

Base image updates are part of maintenance. An image pinned to an old base accumulates vulnerabilities. Rebuild regularly, scan layers and test. Pin the version for reproducibility, but plan its evolution. An image without an update process becomes an invisible security debt.

Registry authentication needs its own hygiene. Use short-lived credentials or a robot account with pull-only rights for deployment, and never bake a registry token into an image. Store credentials in the CI secret store or the host's credential helper, rotate them and revoke them when a person leaves. A compromised push credential can replace a trusted image with malicious content, which is far more dangerous than a read-only leak.

Docker rootless mode runs the daemon and containers without root privileges on the host. It reduces the impact of a container escape, but imposes constraints on low ports and mounts. User namespaces remap container UIDs to unprivileged host UIDs. These mechanisms do not replace a well-built image, but they add a defence layer. Check availability on your platform before enabling them.

Linux capabilities split root privileges. A container that does not need to change the clock, mount filesystems or open raw sockets does not need the corresponding capabilities. --cap-drop ALL then a targeted --cap-add reduces the surface. Test the application after each removal: a library may fail obscurely. Document the capabilities actually required and reassess them at each version upgrade.

Seccomp and AppArmor profiles restrict system calls and program behaviour beyond capabilities. Docker applies a default seccomp profile that blocks some dangerous calls; a custom profile can tighten it further for a specific application. These controls can break legitimate software and require testing, so introduce them with observation and a rollback plan. They are defence in depth, not a substitute for a minimal image and least privilege.

10. Logs, health, diagnosis and startup failure

A container that does not start does not always leave a clear message. Start with docker compose ps, then docker compose logs --tail=100 for the affected service. docker inspect gives the exit code and reason. If the container restarts in a loop, read the logs before they are replaced by the next restart.

docker compose ps
docker compose logs --tail=100 app
docker inspect app --format '{{.State.Status}} exit={{.State.ExitCode}} oom={{.State.OOMKilled}}'
docker compose exec app sh -c 'getent hosts db; nc -zv db 3306'
docker compose events --json

A healthcheck describes how to verify a service is truly ready. For a database, a simple connection is not always enough: wait for the engine to initialise. For an application, a /health endpoint checking critical dependencies is more useful than a port test. The healthcheck must be fast, side-effect free and have a sufficient startup delay.

Connection failures between services have recurring causes: wrong hostname, different network, unexposed port, database not ready, wrong credentials, TLS required. Test in steps: DNS resolution, open port, authentication, query. getent hosts, nc -zv, mariadb -h db -u ... isolate the faulty layer. Do not conclude "the network does not work" without testing each step.

Logs must be structured and limited. The json-file driver can fill the disk if no rotation is configured; use max-size and max-file, or a centralised driver. Do not log passwords, tokens or unnecessary personal data. A too-detailed production log level can expose information and cost money.

Disk failures are common: full volume, permissions, read-only filesystem. docker system df shows space used by images, containers and volumes. docker system prune removes unused resources, but may delete images or volumes you need; read the confirmation. Never blindly clean a production server.

Finally, document symptoms and likely causes. A short runbook — "container restarts: check OOM, variables, migration; database refuses connection: check healthcheck, volume, password" — speeds recovery and prevents every incident from becoming an investigation from scratch. Update it after each real failure.

Calibrate healthchecks carefully. A too-short interval overloads the service; a too-short startup delay declares the application sick before it is ready. For a database, use the script provided by the image rather than a simple port test. For an application, an endpoint checking the database, cache and storage can help, but it must remain fast and not depend on an optional service. A healthcheck that always fails makes the stack unstable.

Monitor Docker events: starts, stops, restarts, OOM errors, health changes. docker events live or a central collector helps correlate an outage with a deployment or resource limit. A container restarting every thirty seconds is not "working" because the process restarts: it is failing in a loop. Count restarts, alert beyond a threshold and find the cause in logs.

Centralised logging changes the diagnosis workflow. When logs from several containers carry a service name, timestamp and correlation identifier, you can follow one request across the stack. Without structure, you search text in several streams and miss the sequence. Agree on a small set of fields, avoid logging secrets and test that the collector is reachable when the primary service fails. Logging must not become a new single point of failure.

Time synchronisation matters when correlating logs across containers and the host. Containers share the host clock, but a host with drifting time produces misleading timestamps and can break TLS or database replication. Configure NTP on the host and monitor clock offset. Use UTC in logs and store the timezone in the display layer. Consistent time is a quiet but essential part of diagnosis and incident reconstruction.

11. Backup, restore, updates and rollback

A database backup is not made by copying the data directory while running. Use a consistent logical dump, for example mariadb-dump with --single-transaction for InnoDB, or a suitable physical tool. For uploaded files, back up the volume with a method that handles files being written, or accept a documented consistency window.

# Dump from the container to a host file
docker compose exec -T db sh -c \
  'mariadb-dump --single-transaction --routines --triggers \
   -u root -p"$MARIADB_ROOT_PASSWORD" catalogue' | gzip > backup.sql.gz

# Verify restoration into a separate database
docker compose exec -T db sh -c \
  'mariadb -u root -p"$MARIADB_ROOT_PASSWORD" -e "CREATE DATABASE catalogue_restore"'
gunzip -c backup.sql.gz | docker compose exec -T db \
  sh -c 'mariadb -u root -p"$MARIADB_ROOT_PASSWORD" catalogue_restore'
docker compose exec -T db sh -c \
  'mariadb -u root -p"$MARIADB_ROOT_PASSWORD" -e "SELECT COUNT(*) FROM catalogue_restore.orders"'

Restoration must be tested in a separate environment, not over the production database. Check the table count, a few rows, constraints and sequences. A dump that reloads without error may have lost data because of an option, encoding or different version. Record the date, duration and result.

Updates follow a cycle: read release notes, back up, test in staging, deploy, verify, keep the ability to roll back. For an image, pull the new tag, rebuild if necessary, recreate the container. For a database, apply migrations after backup and verify the schema. Do not mix image update and data migration in one untested operation.

Rollback depends on what changed. Returning to the previous image is simple if the tag is kept and the schema remains compatible. Returning after a destructive migration is harder: restore the backup or apply a reverse migration. Document version compatibility and test rollback before you need it.

Volumes must be backed up according to content. For an application data volume, a tar archive may suffice if files are consistent; for a database, prefer a dump. For a cache volume, backup is unnecessary. Classify volumes and apply the right method to each. An unbacked-up volume is a single point of loss.

Finally, automate what can be automated, but verify the result. A backup job that fails silently is worse than no backup, because it creates false confidence. Monitor the age of the last backup, file size and the result of the last restoration. Keep backups off the host and encrypt them if they contain personal data.

Define recovery objectives: acceptable downtime (RTO) and acceptable data loss (RPO). These objectives determine backup frequency, the need for replication and the failover procedure. A daily backup with a one-hour RTO is only consistent if restoration is fast and tested. Write the objectives, measure them in exercises and adjust the architecture accordingly.

Adopt a readable tag convention: application version, date or build number, plus a moving tag for development. Do not reuse a production tag for different content; it makes rollback ambiguous. Keep old images for the rollback window, then clean up. A well-organised registry shows which image runs, when it was built and from which commit.

Verify backups automatically where possible: check that the dump file is non-empty, that it contains the expected tables and that a checksum matches. A backup that is zero bytes because the database was down is a common failure. Send the result to monitoring and treat a missed backup as an incident. Manual verification is valuable for restoration drills, but routine checks should not depend on someone remembering.

Schedule restoration drills, not only backups. A quarterly exercise restores a copy into an isolated environment, runs consistency checks and records the duration. It reveals missing files, wrong credentials, incompatible versions and undocumented steps. Assign an owner and a date, and treat a failed drill as an incident with a corrective action. A backup that has never been restored is only a hope.

12. Synthesis: rebuild and explain what survives

For the catalogue stack, the image contains the code and dependencies; the container is disposable; the db_data volume holds the database; the uploads volume holds files; the internal network lets the application reach db:3306; port 8080 is published on the host; variables provide configuration and secrets. Each element has a distinct role and lifetime.

Rebuilding the stack means: fetch the repository, create the environment file, run docker compose up -d --build, wait for the healthcheck, verify the application and logs. Data should be present if the volumes exist. If you remove the volumes, the database starts empty and uploaded files disappear. Knowing what survives each command is the central Docker administration skill.

What survives...
docker restart        : container, writable layer, volumes
docker rm             : named volumes, bind mounts (host data)
docker compose down   : named volumes, images
docker compose down -v: nothing for declared volumes
docker image rm       : existing containers, volumes
rebuild               : volumes, host data

Effective diagnosis follows a method: identify the service, read state and logs, check the resolved configuration, test DNS and port, verify credentials and migrations, then recreate only what is necessary. Avoid restarting everything at random: a restart can erase clues and hide the cause.

Stack security rests on cumulative choices: pinned and rebuilt image, non-privileged user, limited ports, internal network, unversioned secrets, resource limits, controlled logs and tested backups. None of these is sufficient alone, and each has an operational cost. Document the trade-offs and review them when the environment changes.

Finally, reproducibility is the quality criterion. Another person must be able to rebuild the stack from the repository and documentation, without accessing your machine. If a step depends on an unversioned local file, a hand-created volume or an undocumented command, the stack is not reproducible. Containerisation makes reproducibility easier, but does not guarantee it: discipline around images, volumes and configuration does.

A stack runbook contains start, stop, backup, restore, update and rollback commands, plus contacts and alert thresholds. It also lists critical volumes and the full rebuild procedure. Review it after each incident and have someone who did not write it test it. Documentation that is never executed almost always contains an obsolete command.

A runbook must also state how to verify the stack after recovery: the application responds, the database accepts connections, volumes are mounted, migrations are applied, queues are empty or processing, recent backups exist. Recovery is not complete when containers are "up", but when the service behaves as expected. Record the verification and the person who performed it.

Simplicity is an operational quality. Every service, volume, network and variable adds something to understand, back up and troubleshoot. A well-documented three-service Compose stack is often more reliable than a ten-container architecture whose dependencies nobody masters. Before adding a component, ask what problem it solves, what its maintenance cost is and how it will be backed up. Containerisation does not remove this discipline; it makes it more visible.

Handover is part of operability. A guided demonstration followed by an independent rebuild reveals the implicit steps documentation forgets. Note the questions asked and complete the runbook. The person taking over should know where volumes live, which commands are destructive and whom to contact. A stack that only one person can operate is a single point of failure, regardless of how many replicas it runs.

Exercise 1 — Build and run

Write a Dockerfile for a PHP 8.4 application with Apache, install the pdo_mysql extension, copy the public code and start Apache. Build the image, run a container on port 8080 and verify the HTTP response and logs.

Solution

Use FROM php:8.4-apache, RUN docker-php-ext-install pdo_mysql, COPY public/ /var/www/html/ and CMD ["apache2-foreground"]. Build with docker build -t catalogue:1.0 ., run with docker run -d -p 8080:80 --name catalogue catalogue:1.0, then check curl -I localhost:8080 and docker logs catalogue. A database connection failure is expected at this stage: the database is not running yet.

Exercise 2 — Optimise the Dockerfile and cache

The Dockerfile copies the whole repository before installing dependencies, invalidating the cache on every code change. Reorder the instructions, add a .dockerignore and explain the effect on rebuilds.

Solution

Copy dependency files first (for example composer.json and composer.lock), install dependencies, then copy the code. The dependency cache remains valid as long as dependency files do not change. The .dockerignore excludes .git, node_modules, vendor, .env and logs. A rebuild after a code change no longer reinstalls dependencies.

Exercise 3 — Persistence and permissions

Run MariaDB with a named volume, create a table, remove the container, recreate it with the same volume and verify the table exists. Explain what would happen without a volume and how to fix a permission problem on a bind mount.

Solution

The db_data:/var/lib/mysql volume keeps the database files after docker rm. Without a volume, data lives in the writable layer and disappears with the container. For a bind mount, check the container user's UID/GID and host directory rights; fix with chown or an aligned user. Do not run the container as root to work around the problem.

Exercise 4 — Network and DNS

Create a user network, run a database and an application on it, then verify the application resolves db and reaches port 3306. Explain why localhost does not work to reach the database from the application.

Solution

Use docker network create catalogue_net and --network catalogue_net for both containers. From the application, getent hosts db should return the database container address, and nc -zv db 3306 should succeed. localhost refers to the application container itself; the database is another container, reachable by service name on the shared network.

Exercise 5 — Compose, healthcheck and secrets

Write a Compose file with app and db services, a database healthcheck, depends_on with service_healthy, a data volume and passwords read from the environment. Explain what happens if DB_PASSWORD is missing.

Solution

The db service uses the mariadb:10.6 image, a db_data volume and a healthcheck.sh --connect --innodb_initialized healthcheck. app depends on db with condition: service_healthy. Passwords use ${DB_PASSWORD:?set DB_PASSWORD}: if the variable is missing, Compose fails at startup with a clear message instead of launching a stack with an empty password. Secrets must not be versioned.

Exercise 6 — Backup, restore and rollback

Dump the database, restore it into a separate database, verify the row count, then simulate an image update and a return to the previous tag. Describe what must be backed up before each step.

Solution

Use mariadb-dump --single-transaction from the container, then reload into catalogue_restore. Check tables and a few rows. For the update, note the current tag, pull the new one, recreate the container, verify, then return to the previous tag if needed. Back up the database and uploaded files before any migration. Image rollback does not restore a destructive migration: you need the backup or a reverse migration.

Capstone — operate the catalogue stack

Deliver a complete stack: a multi-stage or justified Dockerfile, a Compose file with app and db, healthchecks, a database volume and a files volume, an internal network, a published port limited to 127.0.0.1, variables documented in .env.example, a non-privileged user, resource limits, log rotation, a backup and restore procedure, and an update procedure with rollback.

Grid: the stack starts from a clean repository; data survives docker compose down; down -v is documented as destructive; the healthcheck prevents the application from starting before the database; secrets are not versioned; restoration is proven; rollback is tested; logs are usable. Record commands, results and limits. A stack that only starts on your machine is not delivered, and an unverified claim is not evidence.

Common errors and diagnostic method

Confusing image and container, storing data in the writable layer, using localhost between containers, publishing the database on all ports, forgetting depends_on with a healthcheck, versioning .env, running as root or mounting the Docker socket are classic mistakes. Believing a container is a virtual machine, or that docker compose down -v is safe, is part of the same family.

Method: read state and logs, check the resolved configuration, test DNS then port then authentication, verify volumes and permissions, then recreate only the affected service. Compare what changed since the last working state. Document the cause and fix. A general restart may make the symptom disappear without fixing the cause.

Self-assessment

You should now be able to explain the difference between an image, a container and a volume; describe what survives restart, rm, down and down -v; write a Dockerfile with cache and a non-privileged user; diagnose DNS resolution or a closed port; distinguish an environment variable from a secret; verify a restoration; return to a previous image.

Self-assessment: I can rebuild the stack from a clean repository; I can explain why localhost fails between containers; I can read exit code 137; I can back up and restore the database; I can limit ports and capabilities; I can document what is persistent and what is disposable. To progress, study orchestrators, registries, multi-architecture builds and observability.

References