Docker, cloud, Kubernetes and CI/CD
Overview
In the previous lesson, you learned how to expose LangGraph applications through FastAPI and connect them to Streamlit or React interfaces. Your agent can now receive requests from users outside a Python script.
However, making an agent accessible is not the same as making it production-ready.
Consider a customer support agent running on your laptop. It works correctly until your laptop shuts down, the Python environment changes, several hundred users arrive simultaneously, or a deployment interrupts an active conversation.
Production deployment addresses these problems by making applications reproducible, available, scalable, secure, and maintainable.
Four technologies are particularly important:
- Docker: Packages your application into a portable container image.
- Cloud infrastructure: Provides remotely accessible computing, networking, storage, and managed services.
- Kubernetes: Coordinates containerized applications across computing resources.
- CI/CD: Automates software validation, packaging, and release.
An LLM-powered application introduces additional operational challenges. Agent executions may involve multiple model calls, external tools, persistent checkpoints, human approvals, and long-running operations. Infrastructure must support these characteristics rather than treating every execution as a simple HTTP request.
A typical production architecture separates the user interface, execution environment, durable state, and external services.
The central principle is that application instances should be replaceable without losing important user data.
This lesson uses two deployment approaches: a custom FastAPI container and the purpose-built LangSmith Agent Server. Understanding their differences will help you select infrastructure appropriate to your application.
Docker containerisation
Images and containers
A Docker image is a packaged application filesystem containing your source code, Python runtime, dependencies, and startup instructions.
A container is an isolated running instance of that image. Containers generally share the host kernel, making them lighter than virtual machines that include separate guest operating systems.
An image can produce multiple identical application instances. Each container has its own writable layer, which must not be treated as reliable long-term storage.
| Concept | Responsibility |
|---|---|
| Dockerfile | Defines image construction |
| Image | Packaged application artifact |
| Container | Running application instance |
| Registry | Stores and distributes images |
| Volume | Provides storage outside a container’s writable layer |
| Docker Compose | Coordinates multiple related containers |
For an agent application, Docker reduces environmental inconsistencies between development, testing, and production.
Step 1: Build a deployable LangGraph application
Create the following project:
support-agent/
├── agent.py
├── api.py
├── requirements.in
├── requirements.txt
├── Dockerfile
├── .dockerignore
├── .env
├── tests/
│ └── test_agent.py
└── .github/
└── workflows/
└── release.ymlDefine direct dependencies in requirements.in.
langgraph>=1,<2
langchain>=1,<2
langchain-openai>=1,<2
fastapi>=0.115,<1
uvicorn>=0.30,<1Install dependencies for local development:
pip install -r requirements.inFor reproducible releases, generate and commit a dependency lock file. The following command resolves dependencies inside a Linux environment matching the example deployment architecture.
docker run --rm --platform linux/amd64 \
-v "$PWD:/work" -w /work \
python:3.12-slim \
sh -c 'pip install pip-tools && pip-compile --generate-hashes -o requirements.txt requirements.in'The resulting requirements.txt contains resolved dependency versions and package hashes.
The following complete graph supports deterministic development behavior and live model execution. Save it as agent.py.
import os
from langchain.chat_models import init_chat_model
from langchain.messages import (
HumanMessage,
AIMessage,
SystemMessage,
)
from langgraph.graph import (
StateGraph,
MessagesState,
START,
END,
)
def build_graph(mode="demo", checkpointer=None):
if mode not in {"demo", "live"}:
raise ValueError("Invalid agent mode")
model = None
if mode == "live":
if not os.environ.get("OPENAI_API_KEY"):
raise RuntimeError("OPENAI_API_KEY is required")
model = init_chat_model(
"openai:gpt-5.4-mini"
)
def respond(state: MessagesState):
if model is not None:
response = model.invoke([
SystemMessage(
content=(
"You are a concise customer support assistant."
)
),
*state["messages"],
])
else:
question = state["messages"][-1].content.lower()
if "refund" in question:
answer = "Please provide your order number."
else:
answer = "How can I help you today?"
response = AIMessage(content=answer)
return {"messages": [response]}
builder = StateGraph(MessagesState)
builder.add_node("respond", respond)
builder.add_edge(START, "respond")
builder.add_edge("respond", END)
return builder.compile(checkpointer=checkpointer)
if __name__ == "__main__":
graph = build_graph()
result = graph.invoke({
"messages": [
HumanMessage(content="I need a refund")
]
})
print(result["messages"][-1].content)Expected output:
Please provide your order number.Deterministic mode allows infrastructure and integration tests to run without API credentials or unpredictable model responses. Live mode must be enabled explicitly.
Step 2: Create a container-friendly API
Save the following application as api.py. It initializes the graph during application startup and exposes separate health endpoints.
import os
from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
from langchain.messages import HumanMessage
from agent import build_graph
@asynccontextmanager
async def lifespan(app: FastAPI):
mode = os.getenv("AGENT_MODE", "demo")
app.state.graph = build_graph(mode=mode)
app.state.ready = True
try:
yield
finally:
app.state.ready = False
app = FastAPI(lifespan=lifespan)
class AgentRequest(BaseModel):
question: str = Field(
min_length=1,
max_length=4000,
)
@app.get("/healthz")
def health():
return {"status": "alive"}
@app.get("/readyz")
def readiness():
if not getattr(app.state, "ready", False):
raise HTTPException(
status_code=503,
detail="Service not ready",
)
return {"status": "ready"}
@app.post("/invoke")
async def invoke_agent(request: AgentRequest):
result = await app.state.graph.ainvoke(
{
"messages": [
HumanMessage(content=request.question)
]
},
config={"recursion_limit": 15},
)
return {
"answer": result["messages"][-1].content
}Start the application:
uvicorn api:app --host 0.0.0.0 --port 8000Test it from another terminal:
curl -X POST http://localhost:8000/invoke \
-H "Content-Type: application/json" \
-d '{"question":"I need a refund"}'Expected response:
{"answer":"Please provide your order number."}This API intentionally handles independent requests. Persistent threads, authentication, authorization, and background execution require additional implementation.
Step 3: Write the Dockerfile
FROM python:3.12-slim
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1 \
PIP_NO_CACHE_DIR=1
WORKDIR /app
COPY requirements.txt .
RUN pip install --require-hashes -r requirements.txt
RUN groupadd --gid 10001 appuser \
&& useradd --uid 10001 --gid 10001 \
--no-create-home appuser
COPY --chown=appuser:appuser agent.py api.py ./
USER 10001:10001
EXPOSE 8000
CMD ["uvicorn", "api:app", "--host", "0.0.0.0", "--port", "8000"]Docker constructs images in layers. Copying dependency declarations before source code allows Docker to reuse the dependency installation layer when only application code changes.
The non-root user reduces the privileges available to an exploited application. The exec-form CMD allows the server process to receive container termination signals directly.
EXPOSE documents the application port; it does not publish that port automatically.
For stricter reproducibility, production teams should pin the base image by digest and periodically rebuild against approved security updates.
Step 4: Exclude unnecessary files
Create .dockerignore:
.env
.env.*
.git
.venv
__pycache__
*.pyc
.pytest_cache
gha-creds-*.json
tests/Also exclude credentials and local environment files from Git.
Never place API keys, database passwords, or cloud credentials in a Dockerfile. Secrets embedded in image layers may remain recoverable even after later layers delete them.
Step 5: Build and run the image
docker build --platform linux/amd64 \
-t support-agent:1.0.0 .
docker run --rm \
--name support-agent \
-p 127.0.0.1:8000:8000 \
-e AGENT_MODE=demo \
support-agent:1.0.0Check readiness:
curl http://localhost:8000/readyzExpected output:
{"status":"ready"}To use a real model, create a local .env file:
AGENT_MODE=live
OPENAI_API_KEY=your-api-key
LANGSMITH_TRACING=true
LANGSMITH_API_KEY=your-langsmith-key
LANGSMITH_PROJECT=support-agentStop the existing container and start another:
docker run --rm \
--env-file .env \
-p 127.0.0.1:8000:8000 \
support-agent:1.0.0The image remains unchanged; only its runtime configuration differs.
Tip: Build an image once and promote that same immutable artifact through testing, staging, and production. Rebuilding separately for each environment introduces unnecessary differences.
Building a LangSmith Agent Server image
If your application follows the Agent Server architecture introduced earlier in this chapter, you do not need to recreate its serving infrastructure using FastAPI.
Install the CLI:
pip install -U "langgraph-cli[inmem]"For the existing graph, create server_graph.py:
import os
from agent import build_graph
graph = build_graph(
mode=os.getenv("AGENT_MODE", "demo")
)Create langgraph.json:
{
"dependencies": ["./requirements.txt"],
"graphs": {
"support_agent": "./server_graph.py:graph"
}
}Then build the Agent Server image:
langgraph build -t support-agent-server:1.0.0This creates an image containing the Agent Server runtime and the registered graph.
Agent Server provides execution APIs, streaming, thread management, checkpoint persistence, and run scheduling. When deploying through Agent Server, allow its infrastructure to manage graph persistence rather than embedding a separate local checkpointer.
Cloud deployment
Selecting a deployment architecture
Cloud platforms provide computing infrastructure without requiring you to maintain physical servers.
Your deployment choice determines how much operational responsibility your engineering team retains.
| Deployment option | Examples | Operational responsibility | Suitable workloads |
|---|---|---|---|
| Virtual machines | AWS EC2, Azure VM | High | Custom infrastructure |
| Managed containers | Cloud Run, Azure Container Apps, ECS Fargate | Medium | Containerized APIs |
| Managed Kubernetes | EKS, AKS, GKE | Medium to high | Complex distributed systems |
| Managed agent hosting | LangSmith Cloud | Lower | Stateful agent workloads |
| Standalone Agent Server | Docker or Kubernetes | High | Infrastructure-controlled agents |
Kubernetes is not a prerequisite for deploying LangGraph. A small team may achieve better operational simplicity using managed containers or managed agent hosting.
Deploying the custom API to Google Cloud Run
Cloud Run illustrates how a containerized HTTP application can be deployed without directly managing a cluster.
The following commands assume you have installed and authenticated the Google Cloud CLI, enabled billing, and obtained the necessary IAM permissions.
Set environment variables and create a container repository:
export PROJECT_ID="your-gcp-project"
export REGION="us-central1"
gcloud config set project "$PROJECT_ID"
gcloud services enable \
run.googleapis.com \
artifactregistry.googleapis.com
gcloud artifacts repositories create agents \
--repository-format=docker \
--location="$REGION"Authenticate Docker and publish the image:
gcloud auth configure-docker \
"$REGION-docker.pkg.dev" --quiet
export IMAGE="$REGION-docker.pkg.dev/$PROJECT_ID/agents/support-agent:1.0.0"
docker tag support-agent:1.0.0 "$IMAGE"
docker push "$IMAGE"Deploy the API:
gcloud run deploy support-agent \
--image="$IMAGE" \
--region="$REGION" \
--port=8000 \
--memory=512Mi \
--cpu=1 \
--concurrency=8 \
--min-instances=0 \
--max-instances=5 \
--timeout=120s \
--set-env-vars=AGENT_MODE=demo \
--no-allow-unauthenticatedThese resource and concurrency settings are illustrative starting points, not universal production sizing recommendations.
Cloud Run creates a service revision and supplies an HTTPS endpoint. An authorized caller can test the private service:
export SERVICE_URL=$(gcloud run services describe \
support-agent \
--region="$REGION" \
--format='value(status.url)')
curl "$SERVICE_URL/invoke" \
-H "Authorization: Bearer $(gcloud auth print-identity-token)" \
-H "Content-Type: application/json" \
-d '{"question":"I need a refund"}'The caller must have permission to invoke the service.
For live execution, configure model credentials through a managed secret service and grant a dedicated application service account permission to access only the required secrets.
Your Streamlit or React application can communicate with this API through an authenticated backend. Model credentials must never be exposed to browser clients.
Deploying through LangSmith Cloud
LangSmith Cloud provides a managed alternative designed specifically for agent execution.
A typical deployment proceeds as follows:
- Validate the application using
langgraph dev. - Commit the graph, dependencies, and
langgraph.jsonto GitHub. - Create an Agent Server deployment in LangSmith.
- Select the repository and deployment reference.
- Configure environment variables and secrets.
- Select an appropriate deployment type.
- Validate the deployed execution APIs and connect the frontend.
The langgraph deploy CLI is another supported deployment route.
LangSmith manages the supporting infrastructure in its cloud environment. Hybrid and self-hosted deployment options provide greater infrastructure control, subject to applicable plans and licensing.
Standalone Agent Server deployments require their own PostgreSQL and Redis services. PostgreSQL provides durable persistence, while Redis supports execution coordination, signaling, and task queue functionality.
Do not deploy a standalone Agent Server as an ordinary scale-to-zero HTTP container. Its background execution architecture requires appropriate worker lifecycle and scaling infrastructure. The maintained Kubernetes Helm chart is the recommended self-hosted production route.
Externalizing persistent state
Suppose a conversation begins on replica A, but the next request reaches replica B. An InMemorySaver on replica A cannot provide replica B with the previous conversation.
A shared PostgreSQL checkpointer solves the persistence problem.
Install the PostgreSQL integration:
pip install langgraph-checkpoint-postgres \
"psycopg[binary,pool]"Start a local demonstration database:
docker run -d --rm \
--name agent-postgres \
-e POSTGRES_USER=agent \
-e POSTGRES_PASSWORD=localdev \
-e POSTGRES_DB=agents \
-p 127.0.0.1:5432:5432 \
postgres:16
export DATABASE_URI="postgresql://agent:localdev@localhost:5432/agents"Wait until PostgreSQL accepts connections before running the next example.
The following Python program demonstrates checkpoint recovery across separately compiled graph instances.
import asyncio
import os
from uuid import uuid4
from langchain.messages import HumanMessage
from langgraph.checkpoint.postgres.aio import (
AsyncPostgresSaver,
)
from agent import build_graph
async def main():
database_uri = os.environ["DATABASE_URI"]
config = {
"configurable": {
"thread_id": str(uuid4())
},
"recursion_limit": 15,
}
async with AsyncPostgresSaver.from_conn_string(
database_uri
) as saver:
await saver.setup()
graph = build_graph(checkpointer=saver)
await graph.ainvoke(
{
"messages": [
HumanMessage(content="I need a refund")
]
},
config,
durability="sync",
)
async with AsyncPostgresSaver.from_conn_string(
database_uri
) as saver:
another_graph = build_graph(checkpointer=saver)
snapshot = await another_graph.aget_state(config)
print("Recovered messages:", len(
snapshot.values["messages"]
))
result = await another_graph.ainvoke(
{
"messages": [
HumanMessage(content="Thank you")
]
},
config,
durability="sync",
)
print("Total messages:", len(result["messages"]))
if __name__ == "__main__":
asyncio.run(main())Expected output:
Recovered messages: 2
Total messages: 4The second graph recovers the conversation from PostgreSQL even though the original checkpointer connection has closed.
In production, run database setup and migrations as a controlled release step. Use appropriate connection pooling, encrypted connections, backups, and thread ownership authorization.
Shared persistence does not automatically make concurrent writes to the same thread safe. Implement per-thread execution coordination or use Agent Server’s run-management capabilities.
Kubernetes deployment concepts
Understanding Kubernetes architecture
Kubernetes is a container orchestration system that continuously reconciles actual infrastructure with a declared desired state.
If you request three application replicas and one crashes, Kubernetes attempts to restore the desired replica count.
Its major abstractions include:
| Resource | Purpose |
|---|---|
| Cluster | Collection of managed computing resources |
| Node | Machine capable of running workloads |
| Pod | Smallest deployable workload unit |
| Deployment | Manages replicated application Pods |
| Service | Provides stable networking for selected Pods |
| Gateway or Ingress | Routes external HTTP traffic |
| ConfigMap | Supplies non-sensitive configuration |
| Secret | Supplies sensitive configuration |
| HorizontalPodAutoscaler | Adjusts workload replica counts |
| Job | Executes finite operational tasks |
A Deployment manages replaceable Pods. A Service provides stable discovery even when individual Pod addresses change.
The following diagram illustrates multiple replicas behind a Kubernetes Service.
In a stateful extension of our API, all replicas would communicate with the shared database instead of storing authoritative conversation state locally.
Creating a Deployment and Service
Save the following manifest as k8s.yaml. It deploys the custom FastAPI application, not the standalone Agent Server.
apiVersion: apps/v1
kind: Deployment
metadata:
name: support-agent
spec:
replicas: 2
selector:
matchLabels:
app: support-agent
strategy:
type: RollingUpdate
rollingUpdate:
maxUnavailable: 0
maxSurge: 1
template:
metadata:
labels:
app: support-agent
spec:
terminationGracePeriodSeconds: 60
automountServiceAccountToken: false
containers:
- name: agent
image: IMAGE_REFERENCE
ports:
- containerPort: 8000
env:
- name: AGENT_MODE
value: demo
resources:
requests:
cpu: 250m
memory: 256Mi
limits:
cpu: "1"
memory: 512Mi
startupProbe:
httpGet:
path: /healthz
port: 8000
periodSeconds: 5
failureThreshold: 30
readinessProbe:
httpGet:
path: /readyz
port: 8000
periodSeconds: 5
livenessProbe:
httpGet:
path: /healthz
port: 8000
periodSeconds: 15
securityContext:
runAsNonRoot: true
runAsUser: 10001
allowPrivilegeEscalation: false
capabilities:
drop:
- ALL
---
apiVersion: v1
kind: Service
metadata:
name: support-agent
spec:
selector:
app: support-agent
ports:
- port: 80
targetPort: 8000
type: ClusterIPWith kubectl configured for an existing cluster, substitute the published image reference and deploy:
export IMAGE_REF="$IMAGE"
sed "s|IMAGE_REFERENCE|$IMAGE_REF|g" k8s.yaml \
| kubectl apply -f -
kubectl rollout status deployment/support-agent
kubectl get pods
kubectl get servicesThe cluster must have permission to pull the image from its registry. Use an immutable image digest for production releases.
Test the internal Service locally:
kubectl port-forward service/support-agent 8080:80From another terminal:
curl http://localhost:8080/healthzExpected response:
{"status":"alive"}A ClusterIP Service is internal to the cluster. External access requires an appropriate Gateway, Ingress controller, or load balancer with TLS and authentication.
Health checks and resource management
Kubernetes probes have distinct responsibilities.
| Probe | Question | Failure consequence |
|---|---|---|
| Startup | Has initialization completed? | Container restart after repeated failures |
| Readiness | Can this instance accept traffic? | Removal from normal Service routing |
| Liveness | Is the process functioning? | Container restart after repeated failures |
Avoid putting expensive LLM requests inside health endpoints. A temporary model-provider outage should not trigger continuous restarts across every replica.
The demonstration readiness endpoint checks application initialization. A stateful production API should additionally check critical dependencies using inexpensive, bounded operations.
Resource requests influence scheduling, while limits constrain resource consumption. An application exceeding its memory limit may be terminated.
Horizontal scaling
A HorizontalPodAutoscaler adjusts replica counts according to observed metrics.
kubectl autoscale deployment support-agent \
--min=2 \
--max=10 \
--cpu-percent=70CPU-based scaling requires a functioning Kubernetes resource metrics pipeline.
However, agent workloads are often network-bound rather than CPU-bound. A Pod waiting for model responses may consume little CPU while handling many concurrent executions.
Better scaling signals can include active requests, execution queue depth, queue waiting time, and available worker capacity.
Scaling must also respect model-provider quotas and database connection limits. Adding replicas cannot increase an external provider’s allowed token throughput.
Note: Kubernetes restarts failed containers, not arbitrary interrupted business operations. Durable checkpoints, idempotent tools, execution coordination, and graceful shutdown remain application or agent-runtime responsibilities.
CI/CD pipelines
Continuous integration and continuous delivery
Continuous integration automatically validates changes whenever developers submit new code.
Continuous delivery prepares validated releases for deployment, potentially requiring approval. Continuous deployment automatically releases changes that satisfy the configured gates.
A dependable agent pipeline typically includes:
- Dependency installation and validation.
- Static analysis and security scanning.
- Deterministic graph tests.
- Persistence and tool integration tests.
- Evaluation against representative agent scenarios.
- Container construction and smoke testing.
- Image publication and deployment.
- Post-deployment verification.
Unlike conventional APIs, agent behavior may vary even when code remains unchanged. Therefore, deterministic software tests and model-based evaluations serve complementary purposes.
Writing automated graph tests
Save this complete example as tests/test_agent.py.
import unittest
from langchain.messages import HumanMessage
from agent import build_graph
class SupportAgentTests(unittest.TestCase):
def setUp(self):
self.graph = build_graph(mode="demo")
def test_refund_request(self):
result = self.graph.invoke({
"messages": [
HumanMessage(content="I need a refund")
]
})
self.assertEqual(
result["messages"][-1].content,
"Please provide your order number.",
)
def test_general_request(self):
result = self.graph.invoke({
"messages": [
HumanMessage(content="Hello")
]
})
self.assertEqual(
result["messages"][-1].content,
"How can I help you today?",
)
def test_invalid_mode(self):
with self.assertRaises(ValueError):
build_graph(mode="unknown")
if __name__ == "__main__":
unittest.main()Run the tests:
python -m unittest discover -s tests -vExpected output:
test_general_request ... ok
test_invalid_mode ... ok
test_refund_request ... ok
Ran 3 tests
OKThese tests verify graph behavior without spending money on model calls.
Separate staging evaluations should exercise the live model using representative inputs, expected tool trajectories, and quality thresholds.
Automating releases with GitHub Actions
The following workflow builds and tests the custom API image, then publishes and deploys the same artifact to Cloud Run when changes reach main.
Save it as .github/workflows/release.yml.
name: Agent CI/CD
on:
pull_request:
push:
branches:
- main
permissions:
contents: read
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- name: Build image
run: |
docker build -t support-agent:${GITHUB_SHA} .
- name: Run graph tests inside image
run: |
docker run --rm \
-v "$PWD/tests:/tests:ro" \
support-agent:${GITHUB_SHA} \
python -m unittest discover -s /tests -v
- name: Container smoke test
run: |
docker run -d --name smoke \
-p 127.0.0.1:8000:8000 \
support-agent:${GITHUB_SHA}
trap 'docker rm -f smoke' EXIT
curl --fail --retry 10 \
--retry-connrefused --retry-delay 2 \
http://localhost:8000/readyz
curl --fail \
-X POST http://localhost:8000/invoke \
-H "Content-Type: application/json" \
-d '{"question":"I need a refund"}' \
| python -c 'import sys,json; assert json.load(sys.stdin)["answer"] == "Please provide your order number."'
- name: Save validated image
if: github.event_name == 'push'
run: |
docker save support-agent:${GITHUB_SHA} \
-o agent-image.tar
- uses: actions/upload-artifact@v4
if: github.event_name == 'push'
with:
name: validated-image
path: agent-image.tar
retention-days: 1
release:
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
needs: test
runs-on: ubuntu-latest
environment: staging
concurrency:
group: agent-staging
cancel-in-progress: false
permissions:
contents: read
id-token: write
env:
PROJECT_ID: ${{ vars.GCP_PROJECT_ID }}
REGION: ${{ vars.GCP_REGION }}
steps:
- uses: actions/checkout@v7
- uses: actions/download-artifact@v4
with:
name: validated-image
- name: Load validated image
run: docker load -i agent-image.tar
- uses: google-github-actions/auth@v3
with:
project_id: ${{ vars.GCP_PROJECT_ID }}
workload_identity_provider: ${{ vars.GCP_WIF_PROVIDER }}
service_account: ${{ vars.GCP_DEPLOY_SERVICE_ACCOUNT }}
- uses: google-github-actions/setup-gcloud@v3
- name: Publish and deploy
run: |
gcloud auth configure-docker \
"$REGION-docker.pkg.dev" --quiet
IMAGE="$REGION-docker.pkg.dev/$PROJECT_ID/agents/support-agent"
docker tag support-agent:${GITHUB_SHA} \
"$IMAGE:${GITHUB_SHA}"
docker push "$IMAGE:${GITHUB_SHA}"
IMMUTABLE_IMAGE=$(docker inspect \
--format='{{index .RepoDigests 0}}' \
"$IMAGE:${GITHUB_SHA}")
gcloud run deploy support-agent-staging \
--image="$IMMUTABLE_IMAGE" \
--region="$REGION" \
--port=8000 \
--service-account="${{ vars.GCP_RUNTIME_SERVICE_ACCOUNT }}" \
--set-env-vars=AGENT_MODE=demo \
--max-instances=5 \
--no-allow-unauthenticated \
--quietBefore running this workflow, provision the Artifact Registry repository, Workload Identity Federation provider, deployment service account, runtime service account, and the referenced GitHub environment variables.
Restrict federation to the intended repository and release references. Grant the deployment identity only the registry and Cloud Run permissions it requires.
The workflow deliberately keeps staging in deterministic mode. Add a protected live-model evaluation environment and production promotion job before releasing a real customer-facing agent.
For hardened pipelines, pin third-party actions to reviewed commit SHAs, add dependency and container vulnerability scans, and generate software supply-chain attestations.
Rolling releases and rollback
For Kubernetes, a validated image can be released using its immutable digest:
kubectl set image deployment/support-agent \
agent="$IMMUTABLE_IMAGE"
kubectl rollout status deployment/support-agentIf the release fails:
kubectl rollout undo deployment/support-agentOther release strategies include blue-green deployment, which switches traffic between two environments, and canary deployment, which gradually introduces a new version to a small portion of traffic.
Infrastructure rollback restores application versions, but it cannot automatically reverse database changes, external tool side effects, or incompatible checkpoint updates.
Production release safeguards
Common deployment failures include storing conversation state inside Pods, exposing unauthenticated agent endpoints, using mutable image tags, allowing unbounded execution concurrency, and treating successful health checks as evidence of correct agent behavior.
Before releasing a real agent, verify that:
- Secrets are injected at runtime.
- User identity and thread ownership are validated.
- External tool operations are idempotent where possible.
- Graph recursion and execution duration are bounded.
- Database migrations and backups are controlled.
- Model evaluations satisfy defined acceptance thresholds.
- Deployment rollback and graceful shutdown have been tested.
The examples in this lesson form a runnable deployment baseline, but the cloud and Kubernetes commands require provisioned infrastructure, and the live-model path requires provider access. They are instructional examples rather than an independently validated production deployment.
Relevant implementation references include the LangSmith deployment documentation, standalone Agent Server guide, Cloud Run container deployment guide, and Kubernetes probe documentation.
For the chapter’s hands-on project, these deployment mechanisms connect the agent API and frontend from the previous lesson to a repeatable cloud release process. The next lesson, Graph versioning, performance, cost and production monitoring, extends this foundation by examining how to evolve deployed graphs safely, preserve checkpoint compatibility, measure operational behavior, and optimize production resource consumption.
Build a Deployment-Ready Agent
Build a LangGraph support agent exposed through a FastAPI endpoint with separate liveness and readiness endpoints. Write automated tests that verify graph execution and API behavior without calling a paid language model. Package the application in a Docker image, verify its endpoints inside a running container, and configure a CI pipeline that executes your tests before publishing the image.
from typing import TypedDict
from fastapi import FastAPI
from pydantic import BaseModel
from langgraph.graph import StateGraph, START, END
class AgentState(TypedDict):
question: str
answer: str
def respond(state: AgentState) -> dict:
# TODO: Implement deterministic support responses.
raise NotImplementedError
def build_graph():
# TODO: Register the node, connect edges and compile.
raise NotImplementedError
class AgentRequest(BaseModel):
question: str
app = FastAPI()
# TODO: Initialize the compiled graph.
# TODO: Implement GET /healthz.
# TODO: Implement GET /readyz.
# TODO: Implement POST /invoke.
# TODO: Write automated tests.# Install:
# pip install "langgraph>=1,<2" fastapi uvicorn httpx pytest
#
# Save as exercise.py
# Run API: uvicorn exercise:app --host 0.0.0.0 --port 8000
# Run tests: pytest -q exercise.py
from contextlib import asynccontextmanager
from typing import TypedDict
from fastapi import FastAPI, HTTPException
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
from langgraph.graph import StateGraph, START, END
class AgentState(TypedDict):
question: str
answer: str
def respond(state: AgentState) -> dict:
question = state["question"].lower()
if "refund" in question:
answer = "Please provide your order number."
elif "shipping" in question:
answer = "Standard shipping takes 3-5 business days."
else:
answer = "How can our support team help you?"
return {"answer": answer}
def build_graph():
builder = StateGraph(AgentState)
builder.add_node("respond", respond)
builder.add_edge(START, "respond")
builder.add_edge("respond", END)
return builder.compile()
@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.graph = build_graph()
app.state.ready = True
try:
yield
finally:
app.state.ready = False
app = FastAPI(lifespan=lifespan)
class AgentRequest(BaseModel):
question: str = Field(min_length=1, max_length=4000)
@app.get("/healthz")
def health():
return {"status": "alive"}
@app.get("/readyz")
def readiness():
if not getattr(app.state, "ready", False):
raise HTTPException(503, "Service not ready")
return {"status": "ready"}
@app.post("/invoke")
async def invoke_agent(request: AgentRequest):
result = await app.state.graph.ainvoke(
{"question": request.question, "answer": ""},
config={"recursion_limit": 10},
)
return {"answer": result["answer"]}
def test_graph():
graph = build_graph()
result = graph.invoke(
{"question": "I need a refund", "answer": ""}
)
assert result["answer"] == "Please provide your order number."
def test_health_endpoints():
with TestClient(app) as client:
assert client.get("/healthz").status_code == 200
assert client.get("/readyz").status_code == 200
def test_invoke():
with TestClient(app) as client:
response = client.post(
"/invoke",
json={"question": "What about shipping?"},
)
assert response.status_code == 200
assert response.json() == {
"answer": "Standard shipping takes 3-5 business days."
}
def test_invalid_input():
with TestClient(app) as client:
response = client.post("/invoke", json={"question": ""})
assert response.status_code == 422Summary
- Docker packages application code, dependencies, and runtime configuration into a portable deployment artifact.
- LangSmith Agent Server provides agent-specific infrastructure, while custom container deployments require application-level operational responsibilities.
- Production agent replicas should keep durable conversational state outside their local container filesystems.
- Kubernetes manages container scheduling, service discovery, scaling, health checks, and rolling deployments.
- Liveness, readiness, and startup probes serve different purposes in maintaining application availability.
- CI/CD pipelines should validate graph behavior, test container images, scan dependencies, and promote immutable deployment artifacts.
- Reliable agent releases require secure secret management, controlled concurrency, checkpoint compatibility, and a tested rollback strategy.