Containerising and Scaling

Containerising and Scaling in Flask: --- A city food-truck company runs a dozen identical trucks.


The Analogy: The Food-Truck Fleet and the Central Commissary

A city food-truck company runs a dozen identical trucks. Every truck is built to one master specification -- same griddle, same layout, same stock of utensils -- so a truck rolling out of the depot is interchangeable with every other. When it is sent to a pitch, the dispatcher hands the crew that morning's location, menu-of-the-day, and till float; the truck itself is not painted for one street corner. If a truck breaks down mid-service, it is towed and an identical spare takes its pitch within the hour, and customers barely notice. The master build spec is your container image; the dispatcher's morning briefing is configuration injected from the environment; the freely swapped trucks are disposable, stateless container instances.

The one rule that makes the fleet work is that nothing a customer depends on may live inside a single truck. Orders, the loyalty-card records, and the day's takings are all radioed to the central commissary, not kept in a ledger in one truck's cab. That discipline is what lets the company add five trucks for the lunch rush and pull them at three o'clock: any truck can serve any customer because the truck holds no unique state, only a copy of the shared build and a live link to the commissary. Scaling out is just parking more identical trucks; scaling in is driving some home.

Because every truck is built from the identical spec and told its specifics at dispatch, the company never asks "which truck was set up for the festival?" -- any truck, given the festival briefing, becomes the festival truck. A truck with the festival menu welded into its bodywork at the factory would be useless everywhere else and impossible to reproduce if it crashed. The same image plus different environment configuration yields a development truck, a staging truck, and a production truck from one build -- the reproducibility that makes "it worked in the depot" mean "it works on the street."

The failure arrives the day a crew decides it is quicker to keep regulars' loyalty punch-cards in their own truck's glovebox instead of radioing them to the commissary. It works perfectly while that one truck serves those regulars. Then the rush comes, the company adds trucks, and the dispatcher round-robins customers to whichever truck is free: a regular who bought nine coffees at truck A walks up to truck B for her free tenth and is told she has no card. Worse, when truck A breaks down and is scrapped that evening, every punch-card in its glovebox is gone for good. The trucks were meant to be interchangeable and disposable, and one cab full of private state quietly broke both promises -- exactly what happens when a scaled-out app keeps sessions or uploads in one instance's memory or local disk.


Syntax or Core Structure

Containerising a Flask app is less about writing new Flask code and more about a discipline: the same image must run unchanged in development, staging, and production, and everything that differs between those places -- the database URL, the secret key, the debug flag -- arrives from the environment at startup rather than being baked into the code. This is the first rule of a twelve-factor app, and it is what makes an image reproducible. An application factory that reads only from os.environ (with sane fallbacks) is the whole of it.

import os
from flask import Flask


def create_app():
    app = Flask(__name__)
    app.config["ENV_NAME"] = os.environ.get("ENV_NAME", "development")
    app.config["DB_URL"] = os.environ.get("DB_URL", "sqlite:///local.db")
    app.config["DEBUG"] = os.environ.get("FLASK_DEBUG", "0") == "1"
    return app


# the container runtime injects configuration through the environment
os.environ["ENV_NAME"] = "production"
os.environ["DB_URL"] = "postgresql://db:5432/app"
os.environ["FLASK_DEBUG"] = "0"

app = create_app()
print("env  :", app.config["ENV_NAME"])
print("db   :", app.config["DB_URL"])
print("debug:", app.config["DEBUG"])

Output:

env  : production
db   : postgresql://db:5432/app
debug: False

The factory never mentions "production" in its body; it is handed that fact. Swap the three environment variables and the identical function yields a development app pointed at SQLite. Notice FLASK_DEBUG is compared as the string "1" -- environment variables are always strings, so a config that treats a bare non-empty "0" as truthy is a classic way to ship debug mode to production by accident.


Technical Depth: Workers, Images, and Disposability

Flask's built-in server (app.run()) is single-process and explicitly not for production. In a container you run Flask behind a production WSGI server -- Gunicorn is the common choice -- and Gunicorn's job is to run several copies of your app and hand each incoming request to a free one. How it achieves concurrency depends on the worker class you pick, and the wrong class silently caps your throughput.

Worker classes and what they suit

Worker classConcurrency modelBest forWatch out for
syncOne request per worker, start to finishCPU-bound or short handlersA slow request blocks its whole worker
gthreadThreads within each workerMixed I/O with some blocking callsThe GIL still serialises CPU work
geventCooperative greenlets, monkey-patched I/OMany slow, I/O-bound requestsAny blocking C call stalls the whole worker
eventletCooperative greenlets (alternative loop)High-concurrency I/OSame blocking-call hazard as gevent

The default sync worker serves exactly one request at a time, so your concurrency equals your worker count. That makes sizing the pool the first number to get right.

Sizing the worker pool

Gunicorn's own documentation suggests (2 * CPU cores) + 1 sync workers as a starting point -- enough that while some workers wait on the network, others keep the CPUs busy, without so many that they thrash.

def sync_workers(cpus):
    return 2 * cpus + 1


for cpus in (1, 2, 4):
    print("cpus=" + str(cpus), "->", sync_workers(cpus), "workers")

# a sync worker serves ONE request at a time, so N workers => N concurrent
workers = sync_workers(4)
inflight = 12                       # 12 requests arrive at once
serving = min(inflight, workers)
queued = max(0, inflight - workers)
print("workers:", workers, "serving:", serving, "queued:", queued)

Output:

cpus=1 -> 3 workers
cpus=2 -> 5 workers
cpus=4 -> 9 workers
workers: 9 serving: 9 queued: 3

On a 4-core box you get 9 sync workers; a burst of 12 simultaneous requests serves 9 and queues 3 until a worker frees up. You launch that pool from the command line, never from Python:

gunicorn -w 9 -b 0.0.0.0:8000 --timeout 30 "app:create_app()"

The container image and its process

The image is the master build spec: a frozen filesystem with your code, its pinned dependencies, and the command that starts the server. A production-grade Dockerfile installs dependencies in a cacheable layer, runs as a non-root user, and starts Gunicorn in exec form so the server becomes PID 1 and receives signals directly.

FROM python:3.12-slim
WORKDIR /app

# dependencies first, in their own layer, so code edits do not reinstall them
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY . .

# never run the process as root inside the container
RUN useradd --create-home appuser
USER appuser

EXPOSE 8000
# exec form (JSON array): gunicorn is PID 1 and gets SIGTERM straight from the runtime
CMD ["gunicorn", "-w", "5", "-b", "0.0.0.0:8000", "app:create_app()"]

Three details carry weight. Copying requirements.txt and installing before copying the code means a one-line code change reuses the cached dependency layer instead of reinstalling everything. Running as appuser rather than root limits the blast radius if the app is compromised. And the exec-form CMD (a JSON array, not a shell string) is what lets the orchestrator's SIGTERM reach Gunicorn -- the shell form wraps the process in /bin/sh, which does not forward the signal, so shutdowns become 10-second kills.

The container's own filesystem is ephemeral: when an instance is restarted, replaced, or scaled down, it starts fresh from the image and everything written to its local disk is gone. That is by design -- it is what makes instances disposable -- and it means every piece of durable or shared state must live in a backing service the app connects to over the network. Compose makes that concrete, running a stateless web container alongside the Redis and Postgres services it externalises state into.

services:
  web:
    build: .
    ports:
      - "8000:8000"
    environment:
      ENV_NAME: production
      DB_URL: postgresql://db:5432/app
      SESSION_BACKEND: redis://redis:6379/0
    depends_on:
      - redis
      - db
  redis:
    image: redis:7
  db:
    image: postgres:16
    environment:
      POSTGRES_PASSWORD: change-me

The web service holds no state of its own -- sessions go to Redis, rows go to Postgres -- so you can run docker compose up --scale web=5 and every replica is equivalent. Notice the config still arrives through environment, exactly as the factory expects. The one thing depends_on does not guarantee is that Postgres is ready to accept connections, only that its container has started; production setups add a healthcheck or connection retry so the app does not crash-loop on boot against a database still warming up.

Graceful shutdown for zero-downtime deploys

A rolling deploy stops old instances while new ones start. If an instance is killed mid-request, that user sees an error. Graceful shutdown means: on SIGTERM, stop accepting new connections, let in-flight requests finish within a timeout, then exit. Gunicorn does this for you, but an app with its own background loop must handle the signal so the orchestrator's polite SIGTERM is not escalated to a hard SIGKILL.

import signal

_shutting_down = {"flag": False}


def _handle_sigterm(signum, frame):
    # flip a flag; let the current unit of work drain, then exit cleanly
    _shutting_down["flag"] = True


signal.signal(signal.SIGTERM, _handle_sigterm)

The pattern above is illustrative -- it registers the handler but does not run a loop here. In a real worker you check _shutting_down["flag"] between units of work and stop pulling new ones once it is set, giving the orchestrator the clean exit it asked for instead of a killed process and a half-finished request.


Real World Example: A Shopping Cart That Forgets Half Its Items

An online shop has been containerised and scaled to two identical instances behind a round-robin load balancer -- the textbook horizontal scale-out. To keep the cart fast, the team stored it in a per-process dictionary: no database round-trip, just an in-memory lookup keyed by user. On one developer's laptop, running a single instance, it worked flawlessly. The program below reproduces the production topology in-process: two independent app instances, each with its own carts dict, and a load balancer that alternates between them request by request.

from flask import Flask, jsonify


def make_instance():
    app = Flask(__name__)
    carts = {}                       # in-memory: private to THIS process

    @app.post("/cart/<user>/add/<item>")
    def add(user, item):
        carts.setdefault(user, []).append(item)
        return jsonify(cart=carts[user])

    @app.get("/cart/<user>")
    def view(user):
        return jsonify(cart=carts.get(user, []))

    return app.test_client()


# two identical containers behind a round-robin load balancer
instances = [make_instance(), make_instance()]
rr = {"i": 0}


def lb(method, path):
    c = instances[rr["i"] % len(instances)]
    rr["i"] += 1
    return c.post(path) if method == "POST" else c.get(path)


print("add ->", lb("POST", "/cart/ada/add/book").get_json()["cart"])
print("add ->", lb("POST", "/cart/ada/add/pen").get_json()["cart"])
print("view->", lb("GET", "/cart/ada").get_json()["cart"])

Output:

add -> ['book']
add -> ['pen']
view-> ['book']

Trace the routing and the output makes brutal sense. The first add (round-robin index 0) lands on instance 0, whose cart for Ada becomes ['book']. The second add (index 1) lands on instance 1 -- a different process that has never heard of Ada -- so its cart starts empty and becomes ['pen'], which is why the response is ['pen'] and not ['book', 'pen']. The view (index 2, and 2 % 2 is 0) routes back to instance 0, which still holds only ['book']. The pen exists, but on the wrong truck.

Ada added two items and is never once shown a cart containing both. Which item she appears to "have" depends entirely on which instance the balancer happened to hand her -- a coin flip she cannot see. On a single instance, the developer's laptop, all three requests share one dictionary and she correctly sees ['book', 'pen'], so every test passes and the bug ships. It only surfaces under horizontal scaling, and horizontal scaling is the entire reason the app was containerised. The feature that was supposed to make the shop faster is what breaks its cart.

The genuine design flaw is that the cart lives in one instance's memory, which quietly assumes there is only one instance -- or that every request from a user is pinned to the same one. Neither holds for a scaled, disposable fleet: the balancer spreads requests across instances, and because a container's memory and filesystem are ephemeral, an instance replaced during a routine deploy carries its carts to the grave. The fix is to externalise the state exactly as the commissary holds the loyalty cards: store sessions and carts in a shared backing service -- Redis or the database, via a server-side session store -- so any instance can serve any request and losing an instance loses nothing. Sticky sessions, which pin a user to one instance, look like a cheaper fix but are a band-aid: they break the moment that instance dies or the pool is rescaled, which is precisely the resilience you containerised to gain.


Common Mistakes

  1. Keeping session, cart, or upload state in instance memory or local disk. This is the flaw the Real World example dramatises. A per-process dict or a file under /app/uploads works on one instance and fragments the moment you scale, then vanishes when a container is replaced. Any state a second request might need belongs in a shared backing service.
  1. Baking configuration and secrets into the image. Hard-coding the production database URL or secret key into the code, or copying a .env full of secrets into the image, ties one image to one environment and leaks credentials to anyone who can pull the image. Read config from the environment at startup instead.
  1. Running the Flask development server in production. app.run() is single-threaded, unhardened, and prints a warning telling you not to do this. Put a production WSGI server -- Gunicorn or uWSGI -- in front of the app and let it manage the worker pool.
  1. Using the shell form of CMD or ENTRYPOINT. CMD gunicorn ... (a bare string) runs the server as a child of /bin/sh, which does not forward SIGTERM. The orchestrator's graceful stop is ignored and every shutdown becomes a 10-second wait ending in SIGKILL. Use the exec form: CMD ["gunicorn", ...].
  1. Running the container as root. The default user inside most base images is root; a process breakout then has root on the host namespace. Create an unprivileged user in the Dockerfile and switch to it with USER before the process starts.
  1. Treating depends_on as a readiness guarantee. In Compose, depends_on only waits for the dependency's container to start, not to be ready to accept connections. Without a healthcheck or an application-level connection retry, the app crash-loops on boot against a database that is still initialising.
  1. Assuming the container filesystem persists. Writing logs, uploads, or a SQLite file to the container's own filesystem loses all of it on the next restart, redeploy, or scale event. Send logs to stdout for the runtime to collect, and put durable files in object storage or a mounted volume.
  1. Parsing boolean environment variables carelessly. Environment variables are always strings, and "0" is a non-empty string, so bool(os.environ.get("FLASK_DEBUG")) is True -- you just enabled debug mode in production. Compare explicitly (== "1") or use a helper that understands "false", "0", and "".
  1. Guessing the worker count or picking the wrong worker class. Too many workers thrash the CPU and exhaust memory; too few leave cores idle under load. Start from (2 * cores) + 1 for sync workers, and switch to threaded or async workers when handlers spend most of their time waiting on I/O rather than computing.

Best Practices

  • Keep every instance stateless and externalise shared state. Sessions to a server-side store (Redis or the database), uploads to object storage, cache to Redis. When no instance holds anything unique, you can add, remove, and replace instances freely -- the whole point of the fleet.
  • Drive all configuration from the environment. One image should run in development, staging, and production unchanged, differing only by the environment variables injected at startup. Never bake environment-specific values or secrets into the image.
  • Pin dependencies and order Dockerfile layers for caching. Install pinned requirements in their own layer before copying application code, so routine code changes reuse the cached dependency layer and builds stay fast and reproducible.
  • Run as a non-root user on a slim base image with an exec-form command. A minimal base reduces attack surface and image size; a non-root USER limits breakout damage; the exec-form CMD ensures the server receives signals directly.
  • Serve behind a production WSGI server and size the pool deliberately. Put Gunicorn (or uWSGI) in front of Flask, start sync workers at (2 * cores) + 1, and choose a threaded or async worker class when the workload is I/O-bound.
  • Log to stdout and stderr. Let the container runtime and platform collect and ship logs, rather than writing files inside an ephemeral container. This keeps instances disposable and centralises observability.
  • Design for graceful shutdown. Handle SIGTERM, stop accepting new work, and let in-flight requests drain within a bounded timeout. This is what turns a rolling deploy into a zero-downtime one instead of a burst of dropped connections.
  • Expose health and readiness probes and retry backing-service connections. Give the orchestrator a shallow liveness endpoint and a dependency-aware readiness endpoint, and have the app retry its database and cache connections on boot so a slow dependency does not become a crash loop.

Practice Exercises

  1. Fix the fragmented cart. Take the two-instance program from the Real World example and give both instances a shared cart store (a single dict passed into make_instance, standing in for Redis). Re-run the same add/add/view sequence through the round-robin balancer and confirm the view now returns ['book', 'pen'] no matter which instance each request hit. Explain why the shared store makes the routing irrelevant.
  1. Write a safe boolean parser. Implement parse_bool(value) that returns True only for "1", "true", "yes" (case-insensitive) and False for "0", "false", "", and None. Show that parse_bool(os.environ.get("FLASK_DEBUG")) correctly reads "0" as False, and contrast it with the bool(...) trap from the Common Mistakes.
  1. Size a pool for a target load. Extend the worker-sizing snippet: for core counts 1 through 8, print the sync worker count and how many of 20 simultaneous requests are served versus queued. Then report the smallest core count at which no request is queued, and say what changes if each request spends 90% of its time waiting on the network.
  1. Author a production Dockerfile. Write a Dockerfile for a Flask + Gunicorn app that pins the Python base image, installs pinned requirements in a cached layer before copying code, creates and switches to a non-root user, exposes the port, and starts Gunicorn in exec form. Annotate the single line that ensures a SIGTERM from the orchestrator reaches Gunicorn rather than being swallowed by a shell.