# Running containers well: restart policies, limits, config and Compose

Run containers like services: restart policies, memory and CPU limits, configuration from outside, and a whole stack of web, API, database and migration in one Compose file.

Course: [Docker](https://devops.rajeev.pro/courses/docker), lesson 9. About 40 minutes, intermediate. Source: https://devops.rajeev.pro/courses/docker/09-running-containers

## What you will learn

- Choose a restart policy, and see what on-failure does to a crashing container
- Limit memory, CPU and processes, and recognise an OOM kill
- Harden a container at run time with --read-only, --tmpfs and --init
- Configure an image from outside with environment variables, env files and command overrides
- Describe a multi-service app in compose.yaml with dependencies, health checks, volumes and secrets
- Start, inspect, log and tear down a Compose project

## Run it like a service

So far containers have run until you stopped them. A service that exits during the night leaves users with an
outage, while an unbounded process can consume the host's memory. Docker can restart a container and apply
resource limits, but those controls need to match the app's behavior. In this lesson, you'll set restart policies,
pass configuration at runtime, and use Compose to run related services together.

### Restart policies

```sh
$ docker run -d --name flaky --restart on-failure:3 alpine:3.22 sh -c 'echo starting; exit 1'
$ docker inspect flaky --format 'restarts={{.RestartCount}} status={{.State.Status}} exit={{.State.ExitCode}}'
restarts=3 status=exited exit=1
$ docker logs flaky
starting
starting
starting
starting
```

One run plus three restarts, then Docker gives up. The policies:

| `--restart`      | Restarts when                                                        |
| ---------------- | -------------------------------------------------------------------- |
| `no` (default)   | never                                                                |
| `on-failure[:N]` | it exits with a non-zero code, up to N times                         |
| `unless-stopped` | it exits for any reason, and after a reboot, unless you stopped it   |
| `always`         | like unless-stopped, but also after a reboot when you had stopped it |

`unless-stopped` is the usual choice for a service on a single host. Docker waits longer between each
restart, so a crash loop doesn't spin the CPU.

### Limits

Without limits a container can use all the host's memory and CPU. Limits are cgroup settings (lesson 2):

```sh
$ docker run --rm --cpus 0.5 --memory 128m --pids-limit 100 alpine:3.22 \
    sh -c 'cat /sys/fs/cgroup/memory.max /sys/fs/cgroup/cpu.max /sys/fs/cgroup/pids.max'
134217728
50000 100000
100
$ docker run -d --name hog --memory 64m alpine:3.22 sh -c 'tail /dev/zero'
$ docker inspect hog --format 'oom={{.State.OOMKilled}} exit={{.State.ExitCode}}'
oom=true exit=137
```

`cpu.max` of `50000 100000` means 50ms of CPU in every 100ms: half a core. `tail /dev/zero` keeps reading
into memory until it hits 64MB and the kernel kills it. **Exit code 137** (128 + signal 9) with
`OOMKilled=true` is the signature to look for when a container keeps dying. `--pids-limit` stops a fork bomb.
`docker stats` shows live usage against each limit.

### Hardening at run time

```sh
$ docker run --rm --read-only alpine:3.22 touch /x
touch: /x: Read-only file system
$ docker run --rm --read-only --tmpfs /tmp alpine:3.22 sh -c 'touch /tmp/x && echo tmp-ok'
tmp-ok
$ docker run --rm --init alpine:3.22 ps -o pid,comm
PID   COMMAND
    1 docker-init
    7 ps
```

`--read-only` makes the image's filesystem unwritable, so an attacker can't drop files into it; give the app
a `--tmpfs` or a volume for the places it must write. `--init` runs a tiny init as PID 1 that forwards
signals and reaps zombie processes, for apps that don't do that themselves. Lesson 11 adds more.

## Configuration from outside

Build one image, and configure it per environment when you run it. Never bake settings into the image:

```sh
$ docker run -e APP_VERSION=1.2.0 price-api:multi                  # one variable
$ printf 'APP_VERSION=1.2.0\nLOG_LEVEL=debug\n' > app.env
$ docker run --rm --env-file app.env alpine:3.22 sh -c 'env | grep -E "APP_|LOG_"'
LOG_LEVEL=debug
APP_VERSION=1.2.0
$ docker run --rm alpine:3.22 echo override             # anything after the image replaces CMD
$ docker run --rm --entrypoint sh price-api:single -c 'ls /src'   # replace the ENTRYPOINT
```

Environment variables are visible to anyone who can run `docker inspect`, so they suit settings, not
secrets. For passwords, use files mounted from a secret store, as the Compose example below does.

Keeping configuration outside the image lets the same build move from development to staging and production.
Supply non-secret settings when the container starts, then inspect the resolved configuration when a value is
missing or misspelled. Environment variables are not hidden: anyone with permission to inspect the container
can read them. For credentials, use a secret file or runtime secret facility, and scope access to the service that
needs it. Avoid baking environment-specific values into the Dockerfile, because that creates a different image
for each environment and makes deployments harder to compare.

> **Video.** [Docker Compose: Mastering Environment Variables for Configuration & Secrets 🐳](https://www.youtube.com/watch?v=Xpk82bWEBbw&t=45s) (CodeLucky)

## Docker Compose

A real app is several containers: here a web front, the API from lesson 7, a database and a one-off migration.
Typing all their `docker run` flags is error-prone. **Compose** describes them in one file, `compose.yaml`:

```yaml
name: shop

services:
  web:
    image: nginx:1.30-alpine
    ports:
      - "127.0.0.1:8080:80"
    volumes:
      - ./nginx.conf:/etc/nginx/conf.d/default.conf:ro
    depends_on:
      - api

  api:
    build: .
    image: price-api:dev
    environment:
      APP_VERSION: ${APP_VERSION:-dev}
    restart: unless-stopped

  db:
    image: postgres:17-alpine
    environment:
      POSTGRES_PASSWORD_FILE: /run/secrets/db_password
    secrets:
      - db_password
    volumes:
      - pgdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD", "pg_isready", "-h", "127.0.0.1", "-U", "postgres"]
      interval: 2s
      retries: 15

  migrate:
    image: postgres:17-alpine
    depends_on:
      db:
        condition: service_healthy
    secrets:
      - db_password
    command: ["sh", "-c", "PGPASSWORD=$$(cat /run/secrets/db_password) psql -h db -U postgres -c 'create table if not exists prices(item text primary key, cents int)'"]

volumes:
  pgdata:

secrets:
  db_password:
    file: ./db_password.txt
```

`nginx.conf` sends `/api/` to `http://api:8080/`: services reach each other by **name**. `${APP_VERSION:-dev}`
is read from your shell or a `.env` file next to `compose.yaml`, with `dev` as the default. `$$` is a literal
`$` for the shell inside the container. The secret is mounted as a file at `/run/secrets/db_password` and
never appears in `docker inspect`.

> **Figure.** Animated. docker compose up -d in project shop. api has no dependencies and starts first; web depends on api and starts after it. db starts while its healthcheck, pg_isready every 2 seconds, fails three times and then succeeds, so db becomes Healthy. migrate depends on db with condition service_healthy, waits until then, runs CREATE TABLE and exits with code 0. The volume shop_pgdata is attached to db. Finally curl localhost:8080/api/health goes to web, which reaches api by its service name, and returns status ok.
>
> Order from depends_on, readiness from the healthcheck. migrate never runs against a database that isn't ready.

```sh
$ printf 'devpass' > db_password.txt
$ docker compose up -d
```

> **Figure.** Real terminal output of docker compose up -d: network shop_default and volume shop_pgdata created, container shop-db-1 Healthy after 8.7 seconds, shop-api-1 and shop-web-1 Started, shop-migrate-1 Started after 8.9 seconds. Then docker compose ps: api Up, db Up and healthy, migrate Exited (0), web Up with 127.0.0.1:8080 published to port 80.
>
> migrate started only once db reported Healthy, then exited 0 after creating the table.

```sh
$ curl -s localhost:8080/api/health
{"status":"ok","version":"dev"}
$ docker compose logs migrate
migrate-1  | CREATE TABLE
$ docker compose exec db psql -h 127.0.0.1 -U postgres -c '\dt'
 public | prices | table | postgres
```

The everyday commands:

| Command                        | Does                                                                            |
| ------------------------------ | ------------------------------------------------------------------------------- |
| `docker compose up -d`         | create or update everything; only changed services are recreated                |
| `docker compose up -d --build` | rebuild images with a `build:` first                                            |
| `docker compose ps -a`         | services and their state, including finished ones                               |
| `docker compose logs -f api`   | follow one service's logs                                                       |
| `docker compose exec db sh`    | a shell in a running service                                                    |
| `docker compose config`        | the final file after variables are filled in: check it before you blame Compose |
| `docker compose down`          | remove containers and the network, **keep** volumes                             |
| `docker compose down -v`       | also delete the named volumes: the database is gone                             |

> **Started is not ready.** The short form `depends_on: [db]` only waits for the db container to **start**. Postgres needs several seconds more before it accepts connections. Anything that must talk to the database at startup needs a `healthcheck` on db and `condition: service_healthy`, or its own retry loop.

> **In production.** Compose is a good fit for one server: pin image tags, set `restart: unless-stopped`, memory limits (`mem_limit` or `deploy.resources.limits`) and health checks, keep secrets in files outside the repository, and back up the volumes (lesson 6). Across several servers, use an orchestrator (lesson 14).

> **Video.** [Ultimate Docker Compose Tutorial](https://www.youtube.com/watch?v=SXwC9fSwct8&t=973s) (TechWorld with Nana)

## Runtime guardrails: restart, limits, logs and PID 1

`on-failure:3` retries crashes; `unless-stopped` survives daemon restarts. Cgroup limits prevent one container
consuming the host. Rotate logs, and use `--init` so PID 1 reaps child processes.

```sh
$ docker run -d --name worker --restart unless-stopped --memory 256m --cpus 0.50 --pids-limit 100 \
    --init --log-opt max-size=10m --log-opt max-file=3 alpine:3.22 sleep 300
$ docker inspect worker --format 'restart={{.HostConfig.RestartPolicy.Name}} memory={{.HostConfig.Memory}} init={{.Config.Init}}'
restart=unless-stopped memory=268435456 init=true
$ docker rm -f worker
```

Compose profiles and override files keep optional tools and local ports out of production. `depends_on` with
`service_healthy` waits for a health check; it does not restart a failed service.

These flags protect different resources. Restart policies define what Docker does after a process exits; they do
not repair a broken application. Memory and CPU limits keep one container from taking the whole host, while the
PID limit bounds process creation. Log rotation stops the container log file from growing without limit. `--init`
adds a small init process to forward signals and reap child processes, which matters when the app starts other
processes. Set limits from observed workload needs, then check the container's state and logs when it restarts.

## Mission: One command, four services

Write the compose.yaml from this lesson with web, api, db and migrate. Bring it up, prove migrate waited for the database and created the table, reach the API through nginx, then tear it down while keeping the data, and finally delete it.

- You need: Docker with the Compose plugin, the price-api folder from lesson 7, and nginx.conf
- You'll have: migrate Exited (0), curl returning status ok, and shop_pgdata surviving docker compose down

```sh
$ printf 'server {\n  listen 80;\n  location / { return 200 "shop front\\n"; }\n  location /api/ { proxy_pass http://api:8080/; }\n}\n' > nginx.conf
$ printf 'devpass' > db_password.txt && echo db_password.txt >> .gitignore
$ docker compose up -d
$ docker compose ps -a --format 'table {{.Service}}\t{{.Status}}'
$ curl -s localhost:8080/api/health
{"status":"ok","version":"dev"}
$ docker compose exec db psql -h 127.0.0.1 -U postgres -tAc "select count(*) from information_schema.tables where table_name='prices'"
1
$ docker compose down && docker volume ls --filter name=shop
DRIVER    VOLUME NAME
local     shop_pgdata
$ docker compose down -v
```

`down` kept the volume, so the next `up` finds the table already there (`create table if not exists` makes
the migration safe to run twice). `down -v` is the clean slate.

## Try it

- Run a container that exits with code 1 under `--restart on-failure:3` and read its RestartCount.
- Start `tail /dev/zero` with `--memory 64m` and find OOMKilled in docker inspect.
- Read `/sys/fs/cgroup/memory.max` inside a container started with `--memory 128m`.
- Pass two settings in with `--env-file` and print them inside the container.
- Bring up this lesson's Compose stack and run `docker compose ps -a`.
- Run `docker compose down`, then `docker volume ls`, and explain why shop_pgdata is still there.

## Quiz

1. Which restart policy brings a container back after a crash and after a reboot, but not after you stop it yourself?
   - no
   - **unless-stopped** (answer)
   - on-failure:3
   - --rm
   Why: always would also restart a container you stopped on purpose once the daemon restarts. on-failure only reacts to non-zero exit codes.

2. A container started with --memory 64m dies with exit code 137 and OOMKilled=true. What happened?
   - Docker crashed
   - **It used more memory than its cgroup limit, so the kernel's OOM killer sent SIGKILL (128 + 9 = 137)** (answer)
   - It ran out of disk
   - It was stopped by docker stop
   Why: The limit is a cgroup setting (memory.max). Raise it, or fix the leak, but don't remove limits in production.

3. In Compose, what does depends_on: db: condition: service_healthy do?
   - Restarts db when it fails
   - **Waits to start this service until db's healthcheck passes** (answer)
   - Links the containers' filesystems
   - Nothing in Compose v2 and later
   Why: The short form, depends_on: [db], only waits for db to start, not to be ready. Readiness needs a healthcheck.

4. After docker compose down, the database data is still there. Why?
   - down failed
   - **down removes containers and networks but keeps named volumes; down -v also deletes them** (answer)
   - Compose backs it up
   - Postgres refuses to stop
   Why: That's the safe default: the next up reuses shop_pgdata. Use down -v only when you really want a clean slate.

5. How do containers in one Compose project find each other?
   - By IP addresses you configure
   - **By service name, through the DNS on the project's network, such as http://api:8080** (answer)
   - Through published ports only
   - They can't
   Why: Compose creates a network per project (shop_default) and registers each service name in its DNS. Lesson 10 explains this.

## Resources

- [Docker Docs: start containers automatically](https://docs.docker.com/engine/containers/start-containers-automatically/) (Docker Docs)
- [Docker Docs: resource constraints](https://docs.docker.com/engine/containers/resource_constraints/) (Docker Docs)
- [Docker Docs: Compose file reference](https://docs.docker.com/reference/compose-file/) (Docker Docs)
- [Docker Docs: control startup order in Compose](https://docs.docker.com/compose/how-tos/startup-order/) (Docker Docs)
