Can a free LLM API key go inside a Docker image?
No. Keep a provider key out of the image build. Do not put it in a Dockerfile ARG or ENV, copy a real .env file into the build context, or bake the key into application assets. Give the running container its credential at startup instead. Use a BuildKit secret mount only when a build step truly needs a temporary credential; it does not turn a build-time API call into a good place to use your model key.
For a ChinaGenAI client, the same boundary applies whether your key comes from ChinaGenAI or another free LLM API: build a reusable image without the key, then grant only the application container the key it needs. ChinaGenAI's connection guide documents its OpenAI-compatible endpoint and client setup.
Which Docker step can expose the key?
| Where the value enters | What can retain it | Safer boundary |
|---|---|---|
ARG CHINAGENAI_API_KEY=... or --build-arg |
Build history, metadata, or provenance can reveal a build argument. | Keep the provider key out of build arguments. |
ENV CHINAGENAI_API_KEY=... |
The image configuration and containers created from it inherit the environment value. | Set a runtime value only when the process starts, or mount a runtime secret file. |
COPY .env . or a broad COPY . . |
A file in the build context can be copied into an image layer. Removing it in a later layer does not make the earlier layer a safe place for the secret. | Exclude local secret files from the build context and never copy a real key file. |
RUN --mount=type=secret,... |
The mounted value is available to that build instruction; the mount itself is not committed to the image. A build command can still leak it if it prints or copies the value. | Reserve it for a genuine build dependency, such as private package download. Do not call the model to create normal build output. |
| Container runtime | An environment value can be visible to processes and Docker-daemon users; a Compose secret is a file mount available to services explicitly granted it. | Prefer a runtime secret mount when the app can read a file; otherwise scope and protect the runtime environment. |
Docker's build-variable guidance warns that build arguments may appear in image metadata, provenance, or history and are not for secrets. Its SecretsUsedInArgOrEnv check recommends secret mounts instead. The important distinction is lifecycle: a build secret exists for one build instruction; a provider key is needed later by the running API client.
Exclude local key files from the build context
Add a narrow ignore list at the root of the context sent to docker build:
.env
.env.*
!.env.example
secrets/
Docker removes matching files from the context before sending it to the builder. Check the active ignore file: when a Dockerfile-specific ignore file exists beside a selected Dockerfile, it takes precedence over the root .dockerignore. Also check which directory or remote repository is actually being used as the context. A .dockerignore protects context transfer and broad COPY instructions; it does not make ARG or ENV safe, undo a key already committed to Git, or protect a separate runtime bind mount.
Keep .env.example synthetic and blank, for example CHINAGENAI_API_KEY=replace-me. A real .env, secret directory, or key file must stay out of commits and image contexts. If you use an image build context from Git, review the exact ref and subdirectory being sent rather than assuming your workstation's ignored files are the context.
Mount a runtime secret in Compose
For a Linux-container Docker Compose service, a file-backed secret gives the app a file at /run/secrets/chinagenai_api_key without adding that value to the image:
services:
api:
build: .
secrets:
- chinagenai_api_key
secrets:
chinagenai_api_key:
file: ./secrets/chinagenai_api_key.txt
The app can read the mounted file when it starts. This small Python example never prints the credential:
from pathlib import Path
from openai import OpenAI
key = Path("/run/secrets/chinagenai_api_key").read_text(encoding="utf-8").strip()
client = OpenAI(
api_key=key,
base_url="https://chinagenai.com/v1",
)
Compose grants a secret to a service through its secrets entry. For local Compose, a file-backed secret is still sourced from a host file and mounted into the container; protect that file on the host and do not mistake this for an encrypted remote secret manager. The Compose secrets guide describes the mount and service-scoped access. Compose documents secrets for Linux containers; verify the platform requirements for your environment.
If your application only accepts an environment variable, inject it when the container starts and scope who can inspect the Docker daemon. Avoid putting the literal value in compose.yaml, a Dockerfile, a shell command saved in history, or a checked-in .env. Environment variables are operationally convenient but are not a secret store by themselves.
Use a build secret only for a build-time dependency
A private package registry may need a token while dependencies are installed. Docker BuildKit can expose a temporary secret to that RUN instruction:
# syntax=docker/dockerfile:1
FROM node:22
WORKDIR /app
COPY package*.json ./
RUN --mount=type=secret,id=registry_token,env=NPM_TOKEN npm ci
COPY . .
docker build --secret id=registry_token,env=NPM_TOKEN -t api-client .
This example is for a package-registry credential, not a free LLM API key. If build code echoes the value, writes it into a generated file, or captures it in output, a secret mount cannot undo that behavior. Normal application calls belong after the container starts, with a runtime credential.
Run a no-key audit before publishing an image
Use a fake canary, never a live credential, for a local audit:
- Search the selected Dockerfile and build scripts for
ARGorENVnames containingKEY,TOKEN,SECRET, orPASSWORD. Any provider key in a build instruction is a stop sign. - Check the exact build context and the ignore file that applies to that Dockerfile. Confirm
.env,.env.*, andsecrets/are excluded; do not rely on an ignore file from a different directory. - Inspect every
COPYandADD, including wildcard and multi-stage instructions. A broad copy needs an explicit context review. - Before sharing an already-built image, inspect it locally with
docker history --no-trunc IMAGEanddocker image inspect IMAGE. Do not paste inspection output into an issue or chat; it may disclose values if the image was built unsafely. - If a real key ever entered a build argument, layer, log, or published image, revoke and replace it. A new build does not erase copies already pushed to a registry or cache.
A static scan can catch obvious patterns but cannot prove an image is clean: Dockerfile syntax, build scripts, provenance, caches, multi-stage copies, and secret-manager behavior vary. The audit above deliberately avoids a provider request, a real key, and a Docker build. It checks the boundary before any free-tier quota can be spent.
What a fake-key fixture can verify offline
I prepared two synthetic contexts containing only the placeholder FAKE-CANARY-ONLY-DO-NOT-USE. The risky fixture declares a key-named ARG and ENV, copies .env, and has no context exclusions; the safe fixture keeps the Dockerfile key-free and excludes .env, .env.*, and secrets/. A small exact-name scanner flags six risky conditions in the first and zero in the second. It reads only Dockerfile and ignore-file text; it never reads the .env contents or prints any value. The fixture and checker are retained with the dated research note.
This offline result verifies only those named patterns. It is not a full Docker parser, it does not emulate all .dockerignore rules, and it cannot inspect an image, build cache, or provenance. For a real project, confirm the active context and Dockerfile-specific ignore file, then inspect the built artifact locally before sharing it.
Quick questions
Does a multi-stage build make ARG safe?
No. Multi-stage builds can keep files out of the final stage, but they do not make a secret build argument safe to pass. Build arguments may still be recorded in build metadata or history. Use a BuildKit secret mount for a true build-only need and never pass a model key merely to build the app.
If I delete .env in a later Dockerfile layer, is the image clean?
Do not treat that as cleanup. A prior layer can still contain the copied file. Keep it outside the context before the copy happens; use a fresh credential if a real one was already included.
Is a Compose secret automatically encrypted on my laptop?
No. The Compose file-backed example reads a host file and bind-mounts it into the service. It scopes which service gets the mount, but the source file still needs host protection. For managed production deployment, use that platform's secret manager and runtime injection controls.
Should I call a free LLM API during docker build to precompute responses?
Usually not. It couples a reproducible build to external service availability, may spend the account's free quota, and can put prompt or response data into build output or cache. Keep normal model requests in the running application and test them separately with an offline mock.
Official references
- Docker, Build variables — accessed 2026-11-14.
- Docker, SecretsUsedInArgOrEnv build check — accessed 2026-11-14.
- Docker, Build secrets — accessed 2026-11-14.
- Docker, Build context and
.dockerignore— accessed 2026-11-14. - Docker, Manage secrets securely in Docker Compose — accessed 2026-11-14.