AiCredits
Container Security

Dev Containers and LLM APIs: Keeping Keys Out of Your Images

Keep DeepSeek API keys out of dev container images: devcontainer.json localEnv references, runtime secret mounts, and a scan script that proves your image is clean.

Published 2026-12-04 Updated 2026-12-04 7 min

Why dev containers leak LLM keys

Dev containers are the best onboarding tool Docker ever produced: clone, open, and everything works. They also encourage one bad habit — putting everything the app needs into the image definition, including the API key for your LLM calls. A devcontainer.json is committed to the repo, a Dockerfile builds in CI, and an image lands in a registry with a wider audience than you assume.

The key isn't just "inside the image." It sits in layer contents, in Config.Env visible through docker image inspect, in docker history output, and sometimes in builder provenance attestations. Deleting the ENV line in a later layer does not remove it from the earlier one. If a key ever sat in a layer you pushed, treat it as compromised and rotate it — cleaning comes second, revoking comes first.

The five places a key usually hides

  • ENV DEEPSEEK_API_KEY=... in a Dockerfile, or an ARG with a default value. Both end up in image metadata.

  • A literal value in devcontainer.json under containerEnv or remoteEnv, instead of a host reference.

  • A .env file swept in by COPY . . because .dockerignore was never written.

  • docker build --build-arg KEY=... consumed by a RUN step; BuildKit can record build args in provenance.

  • A notebook cell or test fixture with api_key="sk-...", committed "temporarily" and never removed.

Where it leaksWhat ships with the imageFix
`ENV` or `ARG` in the DockerfileThe value in image config and `docker history`Runtime env or a `/run/secrets` mount
`.env` copied by `COPY . .`A plain-text file inside a layer`.dockerignore` plus `env_file` at runtime
Hardcoded value in `devcontainer.json`The value in git history, forever`${localEnv:VAR}` reference
`--build-arg` for a tokenBuild args in provenance metadata`RUN --mount=type=secret`
Literal key in a notebook or fixtureThe key in the repo and every cloneEnv lookup plus gitleaks in pre-commit

A key is not "removed" from an image when you rebuild — it is absent from the next image. Rotate first, clean second.

Pattern 1: commit the reference, never the value

The Dev Containers CLI expands ${localEnv:DEEPSEEK_API_KEY} from your host shell when the container starts. The committed file then holds only a reference, so a teammate cloning the repo gets an empty variable until they export their own key — which is exactly the behavior you want.

{
  "name": "app-dev",
  "image": "mcr.microsoft.com/devcontainers/python:3.12",
  "remoteEnv": {
    "DEEPSEEK_API_KEY": "${localEnv:DEEPSEEK_API_KEY}"
  },
  "postCreateCommand": "pip install --user openai",
  "containerUser": "vscode"
}

Two caveats. First, the expanded value does live in the running container's environment and is visible via docker inspect on that container — acceptable on your laptop, risky on a shared host or a CI runner you do not control. Second, never echo environment variables in postCreateCommand; build logs are frequently archived and readable by people who should not see them.

Pattern 2: inject at runtime, not at build time

The image should be identical whether or not a key exists. Keep credentials out of the build entirely, run as a non-root user, and let the orchestrator supply the secret when the container starts.

FROM python:3.12-slim

WORKDIR /app

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

COPY . .

RUN useradd --create-home app && chown -R app:app /app
USER app

ENV PYTHONUNBUFFERED=1
# No API key here: resolve it at runtime from env or /run/secrets
CMD ["python", "app/main.py"]
  • Compose route: env_file: [.env.local], with .env.local listed in both .gitignore and .dockerignore. The value stays on the host and is injected at up.

  • Docker secrets route: declare secrets: [deepseek_api_key] with file: ~/.secrets/deepseek. Docker mounts it at /run/secrets/deepseek_api_key instead of baking it into a layer.

  • If a build step genuinely needs a credential, such as a private pip index, use RUN --mount=type=secret,id=pip_token ...; BuildKit exposes it for that step only and keeps it out of the cache and layers.

  • Avoid ARG for anything secret. Even when it is not stored in a layer, it can surface in image history and provenance attestations.

Pattern 3: resolve the key at call time

Read the secret where you use it, with a fallback that produces a useful error instead of a confusing 401. This snippet works unchanged under Docker secrets, Compose env_file, and a plain exported variable, and it takes the fast default model.

import os
from pathlib import Path
from openai import OpenAI

SECRET_PATH = Path("/run/secrets/deepseek_api_key")


def load_api_key() -> str:
    if SECRET_PATH.is_file():
        return SECRET_PATH.read_text().strip()
    key = os.environ.get("DEEPSEEK_API_KEY", "").strip()
    if not key:
        raise RuntimeError(
            "No API key found. Mount /run/secrets/deepseek_api_key or "
            "export DEEPSEEK_API_KEY."
        )
    return key


client = OpenAI(
    api_key=load_api_key(),
    base_url="https://api.aicreditsapi.com/v1",
)

response = client.chat.completions.create(
    model="deepseek-v4-flash",
    messages=[
        {"role": "system", "content": "You review code diffs. Answer in one sentence."},
        {"role": "user", "content": "Diff: rename get_user to fetch_user across four files."},
    ],
    temperature=0.2,
)

print(response.choices[0].message.content)

Use deepseek-v4-flash for tight iteration loops and switch to deepseek-v4-pro only for the harder reasoning steps; the base URL and key are identical, and pro simply costs more per token. Because the key is resolved per call, swapping it for a rotated one is a restart, not a rebuild.

Pattern 4: scan the image before it leaves your laptop

Do not trust the Dockerfile — inspect the artifact. This script extracts the saved image, prints the baked-in environment, and greps every layer for key-shaped strings. Wire it into CI right after the build step and before the push step.

#!/usr/bin/env bash
set -euo pipefail

IMG="${1:?usage: scan-image.sh <image:tag>}"
WORK="$(mktemp -d)"
trap 'rm -rf "$WORK"' EXIT

docker save "$IMG" -o "$WORK/image.tar"
tar -xf "$WORK/image.tar" -C "$WORK"

echo "--- Config.Env baked into the image ---"
docker image inspect "$IMG" --format '{{json .Config.Env}}'

if grep -rIl --binary-files=text -E 'sk-[A-Za-z0-9_-]{16,}' "$WORK"; then
  echo "FAIL: key-like string found in image layers"
  exit 1
fi

echo "OK: no key-like strings in $IMG"
  • Run docker history --no-trunc <image> and read it. If a secret ever appeared in a RUN line, this shows it.

  • Add gitleaks or trufflehog as a pre-commit hook so the literal never reaches the repo in the first place; the image scan then has less to catch.

  • Keep .env, .env.*, *.pem, and *.key in .dockerignore as a standing rule, not as a per-project fix.

  • Test the negative case: build the image without a key and confirm your app fails at call time with a clear message, not at import time with a stack trace.

Rotate cheaply by scoping keys per project

The practical benefit of all this container hygiene is that rotation becomes boring. If each dev container, side project, or CI job has its own key, a leak costs you one revocation and one environment update rather than an audit of every service that shares the credential.

AiCredits is built for exactly that workflow: per-project keys you can revoke individually, a card or PayPal signup with no Chinese phone number or bank account required, and an OpenAI-compatible endpoint at https://api.aicreditsapi.com/v1. Pricing stays predictable in the qualitative sense that matters for dev containers — flash is the cheaper default, pro costs more, cache hits cost less than fresh tokens, and off-peak usage costs less than peak. Current rates are at aicreditsapi.com/deepseek-prices. If a hardcoded sk- string does slip into a diff, our linting tools flag it before it becomes an image layer.

FAQ

Is `${localEnv:DEEPSEEK_API_KEY}` in devcontainer.json safe to commit?

Yes. The file contains a reference that the Dev Containers CLI expands from your host shell at container start, not the key itself. Never replace it with the literal value — once a literal is pushed, removing it from the next commit does not remove it from history.

Do Docker build args really leak secrets?

They are not stored in layers, but they can appear in image history and in BuildKit provenance attestations. Use RUN --mount=type=secret,id=... for build-time credentials, and keep model API keys out of the build entirely.

Can I use deepseek-v4-pro inside a dev container?

Yes — same base URL, same key, different model string. Default to deepseek-v4-flash for fast loops and switch to deepseek-v4-pro for harder reasoning steps; pro costs more per token.

A key was in an image I already pushed. What now?

Revoke and reissue first, then rebuild and re-push. Deleting the layer does not help because registries and anyone who already pulled the image may still have it. Scope the replacement key to that single project so the next rotation is a one-line change.

Try Lint in 2 seconds

Wrote something? Paste it here for a free grammar check. No account needed.

More Tools →

Related Tools

💻Code Explainer 🔒Security Scan

Was this article helpful?

| Share on X Reddit Copy link
💬
反馈意见 / Feedback ×