Shell, Docker and environments

Part of the free LogicWiz Data Engineering course, Module 10: Working like an engineer. The SQL and Python run in the app, on real Postgres and real Python in the browser.

It is 3:00 a.m. on Tuesday, and the orders loader has died with exit code 137. Nobody was deploying. The same loader takes 20 minutes to build, weighs 2.1 GB, and dies with the same 137 in the middle of a batch at every deploy. Nora looks at the list: "Three problems, one box. Open the box."

You'll learn to

  • Ask a server what happened with a few shell commands
  • Read an exit code, and write scripts that fail out loud
  • Explain why an image builds slowly or grows big
  • Stop a container cleanly, and recognise an out-of-memory kill

Learn

First, look at what landed

The loader runs on a server, and on a server your debugger is the shell: a prompt where you type small commands and read what they print.

A handful of them answer most questions about a pipeline. ls lists what arrived. head shows the first lines of a file. wc -l counts lines. grep -c counts the lines that match a pattern.

What makes them powerful is the pipe, written |. It feeds one command's output straight into the next, with no file in between. sort | uniq -d sorts the lines and keeps only the repeated ones: a quick way to spot a file delivered twice.

So: did this week's files arrive, and are they whole?

Five questions about the landing folder

Runs on your laptop:

ls landing/orders
head -3 landing/orders/2025-06-03.csv
wc -l landing/orders/*.csv
grep -c ",placed," landing/orders/2025-06-05.csv
cat landing/orders/2025-06-03.csv landing/orders/2025-06-03_retry.csv | sort | uniq -d | wc -l
$ ls landing/orders
2025-06-01.csv  2025-06-02.csv  2025-06-03.csv  2025-06-03_retry.csv  2025-06-04.csv  2025-06-05.csv  2025-06-06.csv  2025-06-07.csv
$ head -3 landing/orders/2025-06-03.csv
order_id,customer_id,order_ts,status,updated_at
1008,16,2025-06-02T07:26:57Z,shipped,2025-06-03T09:26:57Z
1012,23,2025-06-02T21:31:17Z,shipped,2025-06-03T23:31:17Z
$ wc -l landing/orders/*.csv
    7 landing/orders/2025-06-01.csv
    9 landing/orders/2025-06-02.csv
    8 landing/orders/2025-06-03.csv
    8 landing/orders/2025-06-03_retry.csv
    9 landing/orders/2025-06-04.csv
   12 landing/orders/2025-06-05.csv
   13 landing/orders/2025-06-06.csv
   10 landing/orders/2025-06-07.csv
   76 total
$ grep -c ",placed," landing/orders/2025-06-05.csv
6
$ cat landing/orders/2025-06-03.csv landing/orders/2025-06-03_retry.csv | sort | uniq -d | wc -l
8

Read each $ line as a question and what follows as the answer. wc -l counts the header too, so a file of 8 lines holds 7 orders. The last pipe finds lines that appear in both 3 June files: all 8, header included. The retry is a pure duplicate.

The only clue is a number

The files are fine. The loader still died, and all it left behind is a number: 137.

Every program ends with an exit code. 0 means success. Anything else means failure. You never see it unless you ask (echo $?), but machines judge a run by it: Airflow marks the task failed and retries it, GitHub Actions turns red, Kubernetes marks the job failed.

Codes above 128 are special. They mean the program did not end by itself. Something sent it a signal, a message from the operating system, and the code is 128 plus the signal's number. 137 is 128 + 9, and signal 9 is SIGKILL: stop now, no last words.

Exit codes worth knowing by heart

CodeMeansYou see it when
0successevery run that should be green
1general erroran uncaught Python exception, sys.exit(1)
2wrong usagebad command-line arguments (argparse exits with 2)
126 / 127not executable / command not founda missing chmod +x, a tool not installed in the image
128 + nkilled by signal nthe process did not exit by itself
130SIGINT (2)Ctrl-C
137SIGKILL (9)the OOM killer, or a stop that outlasted its grace period
143SIGTERM (15)a stop request the program did not handle

137 alone does not say who sent SIGKILL. docker inspect (State.OOMKilled) or Kubernetes (reason: OOMKilled) tells an out-of-memory kill from a slow shutdown.

Read an exit code

import signal

def explain(code):
    if code == 0:
        return "success"
    if code > 128:
        sig = signal.Signals(code - 128)
        return f"killed by {sig.name} (signal {sig.value})"
    return {1: "error: an uncaught exception or sys.exit(1)", 2: "wrong usage",
            126: "found but not executable", 127: "command not found"}.get(code, "failed")

for code in (0, 1, 2, 127, 130, 137, 143):
    print(code, explain(code))

Before you run it, guess what 143 is. A shell reports a process killed by signal n as 128 + n, and so do Docker and Kubernetes. Anything above 128 means the program never got to choose its own exit code.

A script must fail out loud

The other side of the same coin: your own scripts must tell the truth with their exit code.

When a check fails, end with sys.exit(1), or let the error escape. Never print("error") and carry on. The script then ends with 0, and every system downstream believes the run worked.

Shell scripts need three settings most people forget. Out of the box, bash carries on after a failed command, treats a variable that was never set as an empty string, and gives a pipe the exit code of its last command only. So curl "$URL" | gzip > orders.gz succeeds even when the download failed.

One line at the top fixes all three: set -euo pipefail.

A script that fails properly

def run_checks(rows_loaded, expected_min):
    problems = []
    if rows_loaded == 0:
        problems.append("no rows loaded")
    elif rows_loaded < expected_min:
        problems.append(f"only {rows_loaded} rows, expected at least {expected_min}")
    return problems

def main(rows_loaded):
    problems = run_checks(rows_loaded, expected_min=50)
    for p in problems:
        print("CHECK FAILED:", p)
    return 1 if problems else 0

# A real script ends with: sys.exit(main(rows_loaded))
print("exit code:", main(80))
print("exit code:", main(12))

main returns the exit code instead of exiting, so it is easy to test. The last line of the real script hands it to sys.exit.

Open the box: images and containers

Now the box itself. The loader does not run straight on the server. It runs in a container: a process with its own files, its own Python and its own libraries, walled off from everything else on the machine.

A container is started from an image: a packed, read-only copy of everything the program needs. Build the image once, and the same bytes run on your laptop, in CI and in production. That is the cure for "it works on my machine".

The recipe for an image is a short text file called a Dockerfile. Each line is one step. Here is the loader's, as it should be.

The recipe: a Dockerfile

Runs on your laptop:

FROM python:3.12-slim

WORKDIR /app

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY src/ ./src/

ENV SWIFTKART_ENV=dev
CMD ["python", "-m", "src.load_orders"]

Read it top to bottom: start from a base, install the packages, copy the code, say what to run.

The Dockerfile, line by line

LineWhat it does
FROM python:3.12-slimstart from an official image: Python 3.12 on a small Linux, pinned by its tag
WORKDIR /apprun the next steps inside the folder /app
COPY requirements.txt .copy only the list of pinned packages first...
RUN pip install ... -r requirements.txt...and install them
COPY src/ ./src/copy your code last, because it changes most often
ENV SWIFTKARTENV=deva default setting, overridden at run time with -e
CMD [...]what the container runs when it starts

WORKDIR, ENV and CMD only record settings in the image. The COPY and RUN steps add files, and that will matter in a moment.

Build the image, run a container

Runs on your laptop:

docker build -t swiftkart-loader:1.4.0 .
docker run --rm -e SWIFTKART_ENV=staging -e WAREHOUSE_PASSWORD swiftkart-loader:1.4.0
echo $?
$ docker build -t swiftkart-loader:1.4.0 .
[+] Building 23.6s (10/10) FINISHED
 => [1/5] FROM docker.io/library/python:3.12-slim                      4.1s
 => [2/5] WORKDIR /app                                                 0.1s
 => [3/5] COPY requirements.txt .                                      0.0s
 => [4/5] RUN pip install --no-cache-dir -r requirements.txt          18.2s
 => [5/5] COPY src/ ./src/                                             0.0s
 => exporting to image                                                 1.1s
 => => naming to docker.io/library/swiftkart-loader:1.4.0              0.0s
$ docker run --rm -e SWIFTKART_ENV=staging -e WAREHOUSE_PASSWORD swiftkart-loader:1.4.0
loading orders for staging
rows in source: 80
rows loaded: 80
$ echo $?
0

Look at the times on the right: the install is 18.2 of the 23.6 seconds. --rm deletes the stopped container afterwards. -e WAREHOUSE_PASSWORD with no value passes the variable from your own shell into the container, so the secret is never written into the image.

Twenty minutes: the cache missed

Why did the old loader take 20 minutes to build? Look at how an image is stored. It is a stack of layers. Each COPY or RUN step adds one: a bundle of the files that step added or changed.

When you build again, Docker does not redo every step. For each one it asks: are the inputs the same as last time? For RUN, the input is the command text. For COPY, it is a checksum of the files. If nothing changed, it reuses the layer from its build cache.

The catch: the first step that misses is rebuilt, and so is every step after it. The old loader copied all its code before it installed its packages. So every edit to any file reinstalled everything.

The loader image, top layer first

Stacked boxes from the top: the writable container layer, the layer with the code, the layer with the installed packages, the small layer with requirements.txt, and the shared base image layers at the bottom.

Read it bottom up: that is the order the steps ran in. Change src/load_orders.py and only the code layer is rebuilt and pushed. Change requirements.txt and the install runs again too. So order the steps from least to most often changed.

Change one file, see what rebuilds

The five steps of the Dockerfile in three builds: in the first build every step runs, after a change to the code only the last step runs, and after a change to requirements.txt the last three steps run again.

  1. The first build. Nothing is cached, so all five steps run. The install takes 18.2 of the 23.6 seconds.

  2. You edit src/load_orders.py and build again. Steps 1 to 4 have the same inputs as last time, so their layers are reused. Only the last step runs, and it takes no time at all.

  3. You change a version in requirements.txt. The file's checksum changes, so step 3 misses. Steps 4 and 5 come after it, so they run again too, although the code did not change.

Read it top to bottom, in the order the steps run. Find the first orange step: everything under it is orange too.

2.1 GB: the image ships its tools

Why 2.1 GB? Because building needs things that running does not: compilers, header files, pip's download cache. The old image carried all of them into production.

A multi-stage build fixes it. The Dockerfile gets two parts. The first stage installs and compiles. The final stage starts from a clean base and copies in only the result. The compilers never reach the image you ship: it is smaller, and a security scanner has less to flag.

Deleting the tools in a later step would not help. A deleted file is only hidden: its bytes stay in the earlier layer, in every download.

The same goes for secrets. A token used during the build must never land in a layer.

Two stages, one shipped

Two boxes: a build stage holding the base image, the compilers, pip's download cache and the installed packages, and a final image holding only the base image, the installed packages copied from the build stage, the code and a non-root user.

Compare the two boxes: only one thing, the installed packages in /opt/venv, crosses from the left box to the right. The next card is the Dockerfile that does it.

The same loader, in two stages

Runs on your laptop:

# syntax=docker/dockerfile:1
FROM python:3.12-slim AS build
RUN apt-get update && apt-get install -y --no-install-recommends build-essential
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
COPY requirements.txt .
RUN --mount=type=cache,target=/root/.cache/pip pip install -r requirements.txt

FROM python:3.12-slim
COPY --from=build /opt/venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
RUN useradd --create-home loader
WORKDIR /app
COPY src/ ./src/
USER loader
ENTRYPOINT ["python", "-m", "src.load_orders"]

The first FROM ... AS build starts the build stage, and COPY --from=build is the one line that crosses over. --mount=type=cache lets pip reuse its downloads from build to build without storing them in the image. The last line is in bracket form, so Python is the container's first process: the next section shows why that matters.

Every deploy: the stop signal never arrives

Now the kill at every deploy. To replace a running container, Docker first asks politely: it sends the signal SIGTERM, "please stop". It waits 10 seconds. Then it sends SIGKILL.

A loader that hears SIGTERM can finish its batch and leave with code 0. Ours never hears it.

The signal goes to the first process in the container, PID 1. The old Dockerfile said CMD python -m src.load_orders. That is the shell form: Docker starts a shell, and the shell starts Python. The shell is PID 1, and it does not pass the signal on.

The bracket form, the exec form, makes Python PID 1: CMD ["python", "-m", "src.load_orders"]. Python must also set up a handler, a function to run when SIGTERM arrives. PID 1 only receives signals it has a handler for.

A deploy stops the loader mid-batch

A conversation between docker stop, a shell that is PID 1 and the Python loader in three steps: SIGTERM reaches the shell and is ignored, ten seconds later SIGKILL kills both with exit 137, and with the exec form and a handler the loader gets SIGTERM, finishes the batch and exits 0.

  1. The deploy asks the loader to stop. docker stop sends SIGTERM to PID 1. PID 1 is the shell. It has no handler, so it ignores the signal and does not pass it on. The loader keeps writing batch 7.

  2. Ten seconds later. Docker sends SIGKILL to PID 1. When PID 1 dies, the operating system kills every other process in the container, so the loader goes with it, mid-batch. Exit code 137.

  3. The same deploy, fixed. With the exec form, Python is PID 1 and receives the SIGTERM. Its handler finishes batch 7, releases the lock and exits 0 after 3 seconds.

Read it top to bottom. Arrows are signals; an arrow that returns to its own line is what that process does next.

3 a.m.: the box has a ceiling

One 137 is left: Tuesday, 3 a.m., nobody deploying.

A container runs under limits. The one that matters here is memory: docker run --memory 2g gives the box a ceiling of 2 GB. Above it there is no warning. The OOM killer of the kernel, the core of the operating system, sends SIGKILL to a process in the container. OOM is short for out of memory.

That is why the log was empty. Python never got the chance to raise MemoryError or print a traceback. All that is left is exit 137, and one flag Docker keeps: OOMKilled: true.

On Tuesday the export was three times its usual size, and the loader read it whole.

An out-of-memory kill, on purpose

Runs on your laptop:

docker run --name oom-demo --memory 256m --memory-swap 256m python:3.12-slim \
    python -c "x = bytearray(512 * 1024 * 1024)"
echo "exit code: $?"
docker inspect --format '{{.State.OOMKilled}} {{.State.ExitCode}}' oom-demo
docker rm oom-demo
$ docker run --name oom-demo --memory 256m --memory-swap 256m python:3.12-slim \
    python -c "x = bytearray(512 * 1024 * 1024)"
$ echo "exit code: $?"
exit code: 137
$ docker inspect --format '{{.State.OOMKilled}} {{.State.ExitCode}}' oom-demo
true 137
$ docker rm oom-demo
oom-demo

Python asked for 512 MiB and wrote zeros into it. At 256 MiB the kernel killed the process before Python could raise anything. Silence plus 137 is the fingerprint of the OOM killer.

Remember: 137 is 128 + 9: killed, not crashed. Then ask who sent the kill. A stop that ran out of patience, or the memory ceiling (OOMKilled: true).

Three Dockerfile mistakes that reach production. Using latest (FROM python:latest), so the image changes under you one day: pin a version. Baking secrets into the image (ENV WAREHOUSE_PASSWORD=..., or copying .env): anyone who can pull the image can read them, so pass them with -e at run time. Copying the code before installing the packages, so every code change reinstalls everything.

Numbers to remember

WhatValueNotes
set -euo pipefailthe first line of a bash script-e stops on a failed command, -u on a variable that was never set, and pipefail makes a pipe fail when any command in it fails.
More shelltail -f, du -sh, zcat big.csv.gz | headFollow a running job's log; find what is filling a disk; peek into a compressed file (the pipe stops as soon as head has its ten lines).
Grace period10 s for docker stop, 30 s in KubernetesThe wait between SIGTERM and SIGKILL. In Kubernetes it is terminationGracePeriodSeconds.
--inita flag of docker runStarts a tiny first process that forwards signals, for programs you cannot change.
--memory 2gthe memory ceilingWith no --memory-swap, the container may also use as much swap as memory if the host has swap. Set both to the same value for none.
--cpus 1.5150 ms in every 100 msHow much CPU time the container may use in each period.
--pids-limit 256processes and threadsA thread leak hits its own wall and not the host's. --ulimit nofile=4096:4096 does the same for open files.
Layers on diskoverlay2 on LinuxStacks the read-only layers and adds one thin writable layer on top, which is gone with the container. A layer is named by the sha256 digest of its content, and images on the same base share its layers.
Build secretRUN --mount=type=secret,id=piptokenShows a token to that one step only. It is never written to a layer, unlike a value passed with ARG or ENV, and changing it does not invalidate the cache.
Pin the basepython:3.12-slim@sha256:...A tag can be moved to a new image. A digest cannot. Use it for builds that must never drift.

On laptops, teams use Docker Compose to start a whole stack with one command: Postgres, Airflow and a loader, wired together in a docker-compose.yml. In production, images are pushed to a registry (Docker Hub, Amazon ECR, Azure Container Registry) and an orchestrator runs them, often Kubernetes. Databricks is different: you attach libraries to a cluster rather than building images, though custom containers exist for special cases.

What changed at SwiftKart

Three problems, three fixes, one Dockerfile.

  • 20 minutes: the packages are installed before the code is copied. A code change now rebuilds one small layer.
  • 2.1 GB: a multi-stage build leaves the compilers behind.
  • 137 at every deploy: the exec form and a SIGTERM handler. The loader finishes its batch and exits 0.

The 3 a.m. kill is explained, but not yet cured. You know the ceiling exists. You do not yet know how high to set it, or what the kernel counts against it. And SwiftKart's Spark jobs are about to move onto Kubernetes, where every executor lives under such a ceiling. That is the next lesson: Containers, Kubernetes and memory limits.

In one line

A job's exit code is its verdict (0 is success, 128 + n means killed by signal n, so 137 is a kill); an image is a stack of cached layers, so order the steps by how often they change and ship only what running needs; and a container must hear SIGTERM to stop cleanly and is killed without a word when it passes its memory limit.

Interview corner

What is a Docker image made of, and how does the build cache decide what to rebuild?

An ordered list of read-only layers, each a tar of the files one RUN, COPY or ADD changed and named by its content digest, plus a config with the command, environment and user. A container stacks them with an overlay filesystem and adds a thin writable layer. The cache reuses a step when its key matches the last build (the command text for RUN, a checksum of the files for COPY), and the first miss rebuilds every later step, so stable steps go first and the code last. A file deleted in a later step still sits in the earlier layer, so secrets must never be copied in at all.

Your loader container exits with 137. What are the possible causes, and how do you tell them apart?

137 is 128 + 9: the process was killed with SIGKILL, so it ran no cleanup. Either the kernel's OOM killer fired because the container passed its memory limit (docker inspect shows OOMKilled: true; in Kubernetes reason: OOMKilled), or a stop outlasted its grace period, typically because SIGTERM never reached the program: shell-form CMD, or Python as PID 1 without a SIGTERM handler. The log helps too: an OOM kill leaves no traceback, while a stop shows the shutdown request time.

A scheduled job failed at 3 am. How do you start investigating from a shell?

Find the run's log and read the end of it with tail, then grep for ERROR or the traceback. Check the exit code and what changed: the input files (ls -lh, head, wc -l against the usual size), the code version, and the environment. Then rerun the same input in dev to reproduce before fixing.