Running containers well

Configuration with environment variables, resource limits, restart policies and their limits, health checks, clean stops with signals and exit codes, and diagnosing a crash loop.
PodmanRuntimeHealth checkscgroupsCore hour

Hour overview

A container that starts is not the same as a container that runs well. In this hour you configure the sample service at run time, limit how much CPU, memory and processes it can use, decide what happens when it fails, check its health, stop it cleanly and diagnose a crash loop. Every module uses the localhost/podman-app:dev image from hour 2.

Time allocation. Configuration 10, resource limits 10, restart policies 8, health checks 12, signals and exit codes 12, crash loop 8.

Objectives. By the end of the hour you can:

  • pass configuration with -e and --env-file, and check what the process actually received
  • cap memory, CPU and process count, and read the effect in podman stats
  • explain which restart policy applies, and why it does not restart containers after a reboot
  • define a health check and read the health status
  • stop a container so the application shuts down cleanly, and read the exit code
  • find the cause of a crash loop from the logs and the exit code

Prerequisite. The image from hour 2: cd podman-app && podman build -t localhost/podman-app:dev .

Modules

Environment and configuration

Hour 3 · 00–10 · 10 min

The sample reads three environment variables: PORT, GREETING and DATA_DIR. The image sets defaults in its ENV instruction. You override them at run time with -e, or with a file that holds one NAME=value per line:

podman run -d --name cfg -p 127.0.0.1:8001:8000 -e GREETING="hello from the lab" localhost/podman-app:dev
curl -s http://127.0.0.1:8001/
podman rm -f cfg

printf 'GREETING=from an env file\n' > lab.env
podman run -d --name cfg -p 127.0.0.1:8001:8000 --env-file lab.env localhost/podman-app:dev
curl -s http://127.0.0.1:8001/
podman exec cfg printenv GREETING
podman rm -f cfg

Expected: the first curl prints "message": "hello from the lab". The second prints "message": "from an env file". printenv prints the value the process sees, which is how you prove what the container received.

Check the environment in the container's configuration:

podman run -d --name cfg -p 127.0.0.1:8001:8000 -e GREETING=check localhost/podman-app:dev
podman inspect --format '{{json .Config.Env}}' cfg
podman rm -f cfg

Expected: a JSON list that includes GREETING=check and the defaults from the image, such as PORT=8000.

Environment variables appear in podman inspect and to anyone who can read the container's configuration on the host. Use them for settings. Passwords and keys belong in secrets (hour 7).

Common errors.

  • The value does not change: the -e option comes after the image name, so it is passed to the command, not to Podman. Put options before the image name.
  • A line in the env file is ignored: the file has a blank line, a missing = or stray characters. Check the file with cat lab.env.

Production note. Keep environment files out of the image and out of version control when they contain secrets. Name them after the environment they belong to, such as prod.env.

Resource limits

Hour 3 · 10–20 · 10 min

Without limits, one container can use all the memory, CPU or processes on the host. Limits are enforced by the kernel through cgroups. Rootless containers need cgroup v2, with the controllers delegated to your user.

podman info
podman run -d --name lim --memory 256m --cpus 0.5 --pids-limit 50 -p 127.0.0.1:8002:8000 localhost/podman-app:dev
podman stats --no-stream lim

Expected: info reports cgroup v2 in its host section. stats --no-stream prints one line for lim, with a memory limit of about 256 MiB and CPU and process figures. If run fails with an error about a cgroup controller, the controller is not delegated to your user. Ask your administrator, or use a rootful test host for this module.

Watch the process limit at work:

podman run --rm --pids-limit 5 docker.io/library/alpine:3.20 sh -c 'for i in 1 2 3 4 5 6 7 8; do sleep 60 & done; wait'

Expected: after five processes, some forks fail with an error such as Resource temporarily unavailable. The exact text depends on the shell. The point is that the limit stopped the fork bomb pattern before it reached the host.

A memory limit is enforced by killing the process. A container that exceeds its memory limit exits with code 137, and its state shows that it was out of memory. Read that in the diagnosis module below.

Common errors.

  • Error: OCI runtime error: ... cgroup: the controller is not available to your user. Check podman info and the systemd delegation settings.
  • Memory limit ignored: the host does not use cgroup v2, so the limit may not apply. Check the cgroup version first.

Production note. Set a memory limit and a process limit on every container. Set CPU limits only when you measure a need, because CPU limits can throttle a service that has short bursts.

Restart policies

Hour 3 · 20–28 · 8 min

A restart policy tells Podman what to do when a container stops:

PolicyBehaviour
nonever restart. This is the default
on-failure[:N]restart only after a non-zero exit, up to N times
alwaysrestart whenever it stops
unless-stoppedrestart unless you stopped it yourself
podman run -d --name r1 --restart on-failure:3 -p 127.0.0.1:8003:8000 localhost/podman-app:dev
podman inspect r1
podman rm -f r1

Expected: inspect shows the restart policy in its HostConfig section. While the container runs, the policy does nothing, because the container never fails.

The limit. Podman has no daemon. The restart policy works while Podman is managing the container, which means while your session and the host are up. After a reboot, nothing starts the container unless systemd does. Verify this on a test host: start a container with --restart always, reboot, and check podman ps -a. You will find it stopped. Hour 7 shows the fix: Quadlet, which runs the container as a systemd service.

Do not rely on --restart always for a service that must come back after a reboot. Use Quadlet, and test the reboot.

Common errors.

  • A container with --restart on-failure stops and does not restart: its exit code was zero. The policy restarts only after a failure.
  • A restart loop that never ends: always with a crash at start-up. Use on-failure:N so the loop stops after N attempts.

Production note. Choose the policy from the failure mode you expect. A short retry count with on-failure stops a bad release from flapping forever.

Health checks

Hour 3 · 28–40 · 12 min

A running process is not always a healthy service. A health check runs a command at an interval, and Podman records the result as starting, healthy or unhealthy.

podman run -d --name hc -p 127.0.0.1:8004:8000 \
  --health-cmd 'wget -qO- http://127.0.0.1:8000/health || exit 1' \
  --health-interval 10s --health-retries 3 --health-timeout 3s \
  localhost/podman-app:dev
sleep 15
podman healthcheck run hc
podman inspect --format '{{.State.Health.Status}}' hc

Expected: healthcheck run runs the command once and exits with status zero when the service answers. After the first interval, inspect prints healthy. The command must exist in the image. The sample is Alpine-based, so wget is present through BusyBox.

Check that failures are recorded. Replace the check with one that always fails:

podman run -d --name hcbad --health-cmd 'false' --health-interval 5s --health-retries 2 localhost/podman-app:dev
sleep 25
podman inspect --format '{{.State.Health.Status}}' hcbad

Expected: after the retries, the status is unhealthy. The container is still running. A health check reports the state, it does not stop the container.

To act on an unhealthy result, Podman 4.2 and later have --health-on-failure, which takes none, kill, restart or stop. Check your version's documentation for the exact behaviour before you rely on it.

Check the application, not just the process. A process that is alive but serves errors should fail its health check. Test the real route that users call.

Common errors.

  • The status stays starting: the first interval has not passed yet. Wait, then inspect again.
  • executable file not found in the health log: the command is not in the image. Use a tool the image has.

Production note. Use a health check that reads a real route, with a short timeout. Add --health-on-failure restart only where a restart is safe for that service.

Stop, signals and exit codes

Hour 3 · 40–52 · 12 min

podman stop sends SIGTERM, the polite stop signal, and waits. If the process has not exited by the timeout (10 seconds by default, set with -t), Podman sends SIGKILL, which cannot be caught. Whether your application gets the chance to shut down depends on which process receives the signal.

Compare two ways of starting the same program:

podman run -d --name exec1 localhost/podman-app:dev python app.py
podman run -d --name shell1 localhost/podman-app:dev sh -c 'python app.py'
time podman stop -t 5 exec1
time podman stop -t 5 shell1
podman inspect --format '{{.State.ExitCode}}' exec1 shell1
podman rm exec1 shell1

Expected: exec1 stops quickly, because Python is the main process and receives SIGTERM. shell1 takes about 5 seconds, because sh is the main process and does not pass the signal on. Podman then sends SIGKILL, and the exit code is 137. The exit code of exec1 is usually 143, which is 128 plus 15, the SIGTERM value. Exact times vary by machine.

Exit codes.

CodeMeaning
0the program finished successfully
1the program failed, for example an unhandled error
125Podman could not start the container
126the command was found but cannot run
127the command was not found
137killed with SIGKILL, which is 128 plus 9
143ended by SIGTERM, which is 128 plus 15
Use the exec form of CMD, as the sample does (CMD ["python", "app.py"]). The program then becomes PID 1 and receives the signal. For programs that spawn children, add --init to podman run so a small init process handles signals and reaps zombies.

Common errors.

  • Stop takes exactly the timeout every time: the process ignores SIGTERM, or the shell form hides it. Compare the exec and shell forms as above.
  • Exit code 137 after a stop: the process was killed. Check whether it was out of memory (hour 3, m2) or the stop timeout was too short.

Production note. Set the stop timeout to the time your service needs to drain requests, for example -t 30, and check that the application handles SIGTERM.

Diagnose a crash loop

Hour 3 · 52–60 · 8 min

A crash loop is a container that starts, fails and is restarted again and again. The sample has a clear configuration error to diagnose: PORT must be a number, and PORT=abc makes the program fail at start-up.

Start it with a restart policy and watch it fail:

podman run -d --name broken -e PORT=abc --restart on-failure:2 localhost/podman-app:dev
sleep 10
podman ps -a
podman logs broken
podman inspect --format '{{.State.ExitCode}}' broken

Expected: ps -a shows broken with status Exited. The logs show a Python traceback that ends with a ValueError about invalid literal for int() with abc. The exit code is 1, a normal failure. A crash loop shows up as the same error repeated in the logs.

Fix the configuration and run it again:

podman rm -f broken
podman run -d --name fixed -e PORT=8000 -p 127.0.0.1:8005:8000 localhost/podman-app:dev
curl -s http://127.0.0.1:8005/health
podman rm -f fixed

Expected: the health route prints {"status": "ok"}.

The diagnosis order. Work through the same order every time: the status in ps -a, the exit code, the last lines of logs, then inspect for the configuration you actually ran. Change one thing, then run the same check again.

A restart policy with a crash at start-up hides the first error under many repeats. Read the first traceback in the log, not the last one.

Common errors.

  • The logs are empty: the process failed before it wrote anything. Check the exit code and the configuration with inspect.
  • The container keeps restarting and the logs scroll away: save them first with podman logs broken > broken.log, read the file, then remove the container with podman rm -f broken.

Cheat sheet

Hour 3 ·
TaskCommand
Set an environment variablepodman run -e NAME=value IMAGE
Load an env filepodman run --env-file FILE IMAGE
Check what a process receivedpodman exec NAME printenv NAME
Memory, CPU and process limitspodman run --memory 256m --cpus 0.5 --pids-limit 50 IMAGE
Live usage, oncepodman stats --no-stream NAME
Restart on failure, up to 3 timespodman run --restart on-failure:3 IMAGE
Run the health check nowpodman healthcheck run NAME
Read health statuspodman inspect --format '{{.State.Health.Status}}' NAME
Stop with a 30-second timeoutpodman stop -t 30 NAME
Read the exit codepodman inspect --format '{{.State.ExitCode}}' NAME
Crash loop logspodman logs NAME, then podman ps -a

Capstone lab: a service with limits, checks and a clean stop

Hour 3 ·

Goal. Run the sample service with configuration, limits, a health check and a restart policy. Prove it is healthy, then stop it cleanly and read the exit code.

cd podman-app
podman rm -f prod 2>/dev/null
podman run -d --name prod -p 127.0.0.1:8010:8000 \
  -e GREETING="capstone" --memory 256m --pids-limit 50 \
  --restart on-failure:3 \
  --health-cmd 'wget -qO- http://127.0.0.1:8000/health || exit 1' \
  --health-interval 10s --health-retries 3 \
  localhost/podman-app:dev
sleep 15
curl -s http://127.0.0.1:8010/
podman inspect --format '{{.State.Health.Status}}' prod
podman stop -t 10 prod
podman inspect --format '{{.State.ExitCode}}' prod
podman rm prod

Expected. The curl prints "message": "capstone". The health status is healthy. After stop, the exit code is 143, because the exec form passes SIGTERM to Python.

Verify. podman ps -a lists prod as Exited before the rm, and no longer lists it after.

Final quiz

Hour 3

Sources and version notes