Skip to content
Visual explainer 3h to learn 4 steps

Containerise & deploy

Ship the service in Docker to a cloud host with secrets managed properly.

By Invicly Tech, , in AI Engineering with Python. About 12 minutes to read.

Topic 31 of 33

In short

A Docker image packages your service with its exact Python version and dependencies, so it runs the same everywhere. Secrets come from environment variables at runtime, and health checks let the host restart failed instances.

Explained simply

Your service works on your laptop because your laptop has the right Python version, the right packages and your environment variables. A container packages the app with its exact Python and libraries into one image, so it runs the same on any machine that has Docker or a container platform.

A Dockerfile is the recipe for that image. Each line adds a layer: start from a small Python base, install dependencies, copy your code, and say how to start the server. Docker reuses unchanged layers, so rebuilds after small code changes are fast.

Secrets never go into the image. Anyone who can pull an image can read everything inside it. API keys arrive at runtime as environment variables, set by the hosting platform or a secrets manager.

Once running, the platform needs to know the app is healthy. A small /health endpoint lets it restart a stuck container, and logs written to standard output let you see what happened.

Press Play on a diagram to walk through it one step at a time.

FlowFrom code to running service
  1. 1
    Write Dockerfile

    Base image, dependencies, start command

  2. 2
    Build image

    docker build creates a versioned image

  3. 3
    Push to registry

    Store the image where the host can pull it

  4. 4
    Deploy with secrets

    Inject API keys as environment variables

  5. 5
    Health checks and logs

    Host restarts unhealthy containers

FlowFrom commit to live traffic
  1. 1
    Commit

    Pull request merged to main

  2. 2
    CI checks

    Unit tests and eval gate

  3. 3
    Build image

    Tagged with the git SHA

  4. 4
    Push to registry

    Immutable, versioned image

  5. 5
    Deploy revision

    Secrets injected at runtime

  6. 6
    Health checks pass

    Traffic shifts to the new version

In depth

A production Dockerfile, line by line

Start from a pinned slim base image such as python:3.12-slim, not a moving latest tag. Set PYTHONUNBUFFERED=1 so logs appear immediately instead of sitting in a buffer, and PYTHONDONTWRITEBYTECODE=1 to skip .pyc files.

Copy requirements.txt and install dependencies before copying the rest of the code. Docker caches layers in order, so editing main.py then reuses the slow install layer. Use pip install --no-cache-dir to keep the image smaller.

If some packages need compilers to build, use a multi-stage build: build wheels in a first stage that has the tools, then copy only the wheels into a clean final stage. Create a normal user and switch to it with USER, so a bug in your app does not run as root.

Write CMD in exec form, the JSON array style. Then uvicorn runs as process 1 and receives the SIGTERM signal the platform sends on shutdown, so it can finish open requests.

LayersImage layers, from rarely to often changed
  1. 1
    Base image

    python:3.12-slim, pinned

  2. 2
    System packages

    Only what you truly need

  3. 3
    Python dependencies

    Cached until requirements change

  4. 4
    App code

    Changes on almost every build

  5. 5
    Runtime settings

    USER, EXPOSE, HEALTHCHECK, CMD

Keeping secrets and junk out of the image

COPY . . copies everything in the build folder unless a .dockerignore file excludes it. Without one, your .env file with real API keys, the .git history, virtual environments and local data can all end up inside the image. Add .env, .git, .venv, __pycache__, notebooks and eval output folders to .dockerignore.

Do not pass secrets with ARG or ENV in the Dockerfile either. Their values can be seen with docker history or docker inspect. Secrets belong at runtime: docker run -e or --env-file locally, and the platform's secret store in the cloud, which injects them as environment variables or files.

If the build itself needs a secret, for example a token for a private package index, use BuildKit secret mounts (RUN --mount=type=secret,id=...). The secret is available to that one command and is not saved in any layer.

  • .dockerignore: .env, .git, .venv, __pycache__, data folders
  • Never put secrets in ARG or ENV lines
  • Runtime: -e, --env-file or the platform's secret store
  • Build-time: RUN --mount=type=secret

Health checks and graceful shutdown

Platforms ask two different questions. Liveness: is the process alive, or should it be restarted? Readiness: can it serve traffic right now? A liveness endpoint like /health should be cheap and check only the process itself. A readiness check may also confirm the database connection or that the index has loaded.

Do not call the LLM provider in either check. Probes run every few seconds, so that costs money, and a short provider outage would make the platform restart every container, turning a small problem into a full outage.

The Dockerfile HEALTHCHECK instruction is used by Docker and Docker Compose. Kubernetes and many cloud platforms ignore it and use their own probe settings, so configure health checks there too.

On deploys, the platform sends SIGTERM and waits a grace period before killing the container. Long LLM streams need a grace period longer than a typical reply, or users will see answers cut off at every release.

CompareLiveness vs readiness
Liveness
  • Is the process alive?
  • Cheap, no external calls
  • Failure: restart the container
Readiness
  • Can it serve traffic now?
  • May check DB and index
  • Failure: stop sending traffic

Deploying to a cloud host

The flow is the same on most platforms. Build the image in CI, tag it with the git commit SHA (not only latest, so you always know what is running and can roll back), push it to a registry, and deploy that exact tag.

Managed container platforms such as Google Cloud Run, AWS App Runner or ECS, Azure Container Apps, Fly.io and Render run the image for you. Read their rules carefully. Cloud Run, for example, tells the container which port to listen on through the PORT environment variable (8080 by default). Exec-form CMD does not expand variables, so to use $PORT you start the server through sh -c or read the variable in Python.

Check request timeouts and idle timeouts, since long streams can hit them. Platforms that scale to zero save money but add cold starts, so set a minimum of one instance if first-request latency matters.

Logs that work in containers

Containers should not write log files. Write logs to standard output and standard error, and let the platform collect, store and search them. Files inside a container disappear when it is replaced, and nobody reads them anyway.

Write one structured JSON line per event, with fields such as time, level, request ID, trace ID, route, status, latency, model, tokens and cost. JSON is easy for log platforms to parse and filter, and the trace ID links a log line to its trace.

Turn off uvicorn's default access log if you write your own richer request log, so each request is not logged twice. And apply the same redaction rules as for traces: do not log raw API keys, full prompts with personal data, or authorization headers.

Learn it in 4 short steps

About 45m each. Track them with a timer in your plan.

  1. 1
    Write a Dockerfile for the service~45m
  2. 2
    Manage secrets with environment variables~45m
  3. 3
    Deploy to a cloud host~45m
  4. 4
    Add health checks and logs~45m

Key points

  • Never bake API keys into the image; inject them at runtime.
  • Copy dependency files first so Docker caches the install layer.
  • Use a slim base image and run as a non-root user.
  • Expose a /health endpoint and log to stdout.

Key terms

Tap a card to flip it. 0/5 known

Examples

dockerfile
FROM python:3.12-slim
WORKDIR /app

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

COPY . .
RUN useradd -m appuser
USER appuser

EXPOSE 8000
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

# Run: docker run -e LLM_API_KEY=... -p 8000:8000 my-llm-api

Cached dependency layer, non-root user, secrets at runtime.

A multi-stage Dockerfile with a health check

Step 1: the build stage turns requirements.txt into wheels, so any compilers stay out of the final image. Step 2: the final stage starts clean, sets the two Python environment variables, installs only the wheels and creates a non-root user. Step 3: copy the code last so code changes reuse cached layers. Step 4: the HEALTHCHECK uses Python's urllib, because slim images do not include curl; urlopen raises on an error status, so the check fails. Step 5: run with docker run --env-file .env -p 8000:8000 my-llm-api, keeping secrets outside the image.

dockerfile
FROM python:3.12-slim AS build
WORKDIR /app
COPY requirements.txt .
RUN pip wheel --no-cache-dir --wheel-dir /wheels -r requirements.txt

FROM python:3.12-slim
ENV PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1
WORKDIR /app
COPY --from=build /wheels /wheels
RUN pip install --no-cache-dir /wheels/* && rm -rf /wheels && useradd -m appuser
COPY . .
USER appuser
HEALTHCHECK --interval=30s --timeout=3s CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

Local stack with Docker Compose and pgvector

For development you want the API and a Postgres database with pgvector, started with one command. Step 1: the api service builds from your Dockerfile and reads secrets from .env at runtime; .dockerignore keeps that file out of the image. Step 2: the db service uses the pgvector image with a development-only password. Step 3: a healthcheck runs pg_isready, and depends_on with condition service_healthy makes the API wait until the database is accepting connections. Step 4: docker compose up --build starts both.

yaml
services:
  api:
    build: .
    ports: ["8000:8000"]
    env_file: .env   # read at runtime, never copied into the image
    depends_on:
      db:
        condition: service_healthy
  db:
    image: pgvector/pgvector:pg16
    environment:
      POSTGRES_PASSWORD: dev-only
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 5s

Quick reference

  • Copy requirements.txt and install before COPY . . so the dependency layer is cached
  • Add .env, .git, .venv and __pycache__ to .dockerignore
  • Never put secrets in ARG or ENV; inject them at runtime
  • Set PYTHONUNBUFFERED=1 so logs appear immediately
  • Use exec-form CMD so the server gets SIGTERM and can shut down gracefully
  • Tag images with the git SHA so you know what runs and can roll back
  • Health checks must not call the LLM provider
  • Log JSON lines to stdout with request ID and trace ID; no log files

Common mistakes

  • Copying a .env file with secrets into the image.
  • Copying all code before installing dependencies, breaking layer caching.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1You edit one line in main.py and the rebuild reinstalls every dependency. What is the likely cause?

Question 2

2Why should a liveness check not call the LLM provider?

Question 3

3A teammate passes the API key with ARG in the Dockerfile. What is the problem?

Question 4

4Your app on Cloud Run fails to start, though it works locally on port 8000. What should you check first?

Question 5

5Users see streamed answers cut off during every deploy. What helps most?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write a .dockerignore for a Python LLM service that keeps secrets, Git data, virtual environments, caches and local data out of the image.

  2. Exercise 2medium

    Add /health (liveness) and /ready (readiness) endpoints to a FastAPI app. Readiness should check the database with a cheap query and return 503 if it fails; neither should call the model.

  3. Exercise 3hard

    Make the container listen on the PORT environment variable when it is set (as on Cloud Run) and on 8000 otherwise, while still receiving SIGTERM directly.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

How do I pass API keys to a Docker container?
At runtime: docker run -e NAME=value or --env-file locally, and your cloud platform's secrets manager in production. Never bake them into the image.
Should I use python:3.12-slim or alpine for a Python service?
Slim is usually the safer choice. Alpine uses musl instead of glibc, so many Python packages need compiling, which makes builds slower and can cause subtle issues.
Why is my container's print output not showing in the logs?
Python buffers output when it is not attached to a terminal. Set PYTHONUNBUFFERED=1 or use a logger that flushes, and write to stdout or stderr.
Do I need Kubernetes to deploy an LLM app?
No. Managed container platforms run a single image with secrets, health checks and autoscaling, which is plenty for most apps. Kubernetes helps when you run many services and need fine control.
ShareXLinkedInWhatsApp