
您需要一个容器化应用程序,该程序可以与DeepSeek V4通信,在您的笔记本电脑和生产的虚拟机上运行相同,并且不会将API密钥泄露到Git历史记录中。这正是本DeepSeek Docker部署指南所涵盖的内容——具体的Dockerfile、可工作的`docker-compose.yml`文件以及人们容易出错的地方(GPU直通用于本地蒸馏、秘密处理、健康检查和成本控制的代理模式)。
我每天在容器中运行V4-Flash和V4-Pro,同时使用内部LiteLLM代理。以下模式是在接触真实流量后幸存下来的,不是玩具示例。到结束时,您将有两个场景的可重复设置:一个Python服务调用DeepSeek托管API,以及一个自托管蒸馏模型位于OpenAI兼容端点之后。
What you will build

两种部署方式,均为生产型:
- 场景A — 托管API客户端。 一个容器中的小型FastAPI服务,使用OpenAI SDK调用DeepSeek的托管端点。无需GPU。适用于V4-Flash和V4-Pro。
POST /chat/completions场景B — 自托管蒸馏。 - 两种场景共享相同的带有配置文件的compose文件,因此您可以独立启动它们。 一个vLLM容器在您的GPU盒子上为DeepSeek R1蒸馏模型提供支持,该模型位于OpenAI兼容的API之后,并使用NVIDIA容器工具包。当您需要离线推理或严格的数据驻留时非常有用。
插件 (
Prerequisites
- 插件 ( and the 插件 ( ,不是
,不是, notdocker-compose). - A DeepSeek API key 从开发者控制台——查看 get a DeepSeek API key 如果您尚未生成一个。
- 对于场景B:至少24GB VRAM的NVIDIA GPU(用于14B蒸馏的fp16)以及安装在主机上的NVIDIA容器工具包。 NVIDIA容器工具包 已安装。
- Linux、macOS或Windows操作系统,并支持WSL2。其中大部分在这些操作系统之间是相同的;GPU直通是Linux优先。
- 熟悉环境变量以及基本的Python或Node服务。如果您对API接口本身还不熟悉,可以快速浏览一下。 DeepSeek API getting started 指南。
您将使用的模型ID
DeepSeek V4(发布于2026年4月24日)以两个开源的MoE模型的形式提供,遵循MIT许可: deepseek-v4-pro (1.6T total / 49B active parameters, frontier tier) and deepseek-v4-flash (284B / 13B 活跃,成本效益型层)。两者都提供1,000,000个token的上下文,输出最多可达384,000个token。
思考模式是一个请求参数,不是一个单独的模型ID——设置为最大努力。旧版ID reasoning_effort="high" with extra_body={"thinking": {"type": "enabled"}}, or "max" 旧版ID deepseek-chat and deepseek-reasoner still work but route to deepseek-v4-flash他们退休后 2026-07-24 at 15:59 UTC. Migrating is a one-line model= swap; base_url 并不会改变。关于家庭生活的完整背景仍然存在 DeepSeek V4 page.
项目布局
这里是我们将要构建的目录:
deepseek-stack/
├── .env # never committed
├── .env.example
├── docker-compose.yml
├── api-client/
│ ├── Dockerfile
│ ├── requirements.txt
│ └── app.py
└── proxy/
└── litellm.config.yaml # optional, for Scenario A+
步骤 1 — 编写API客户端镜像

场景A是一个Python 3.12服务。创建 api-client/requirements.txt 包含两个固定的依赖项:
openai==1.54.0
fastapi==0.115.4
uvicorn[standard]==0.32.0
然后 api-client/app.py ——一个最小的端点,它将提示代理到DeepSeek。注意明确的 base_url; chat requests hit POST /chat/completions, the OpenAI-compatible endpoint:
import os
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from openai import OpenAI
client = OpenAI(
base_url="https://api.deepseek.com",
api_key=os.environ["DEEPSEEK_API_KEY"],
)
app = FastAPI()
class Ask(BaseModel):
prompt: str
thinking: bool = False
@app.get("/healthz")
def healthz():
return {"ok": True}
@app.post("/ask")
def ask(body: Ask):
kwargs = {
"model": "deepseek-v4-flash",
"messages": [{"role": "user", "content": body.prompt}],
"temperature": 1.3, # general conversation
"max_tokens": 1024,
}
if body.thinking:
kwargs["reasoning_effort"] = "high"
kwargs["extra_body"] = {"thinking": {"type": "enabled"}}
try:
resp = client.chat.completions.create(**kwargs)
except Exception as e:
raise HTTPException(status_code=502, detail=str(e))
msg = resp.choices[0].message
return {
"content": msg.content,
"reasoning_content": getattr(msg, "reasoning_content", None),
}
API是无状态的——每个请求都必须携带完整 messages 数组以实现多轮上下文。网页聊天会保留会话历史;API不会。当启用思考功能时,响应会返回将所有内容串联起来的信息。 reasoning_content alongside the final content.
现在 api-client/Dockerfile使用精简基础镜像,以非root用户运行,并复制 requirements.txt 在源代码之前,以便层缓存能够在代码编辑后继续工作:
FROM python:3.12-slim AS base
docker history PYTHONDONTWRITEBYTECODE=1
PYTHONUNBUFFERED=1
PIP_NO_CACHE_DIR=1
RUN useradd --create-home --uid 1000 app
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app.py .
RUN chown -R app:app /app
USER app
EXPOSE 8000
HEALTHCHECK --interval=30s --timeout=5s --retries=3
CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/healthz')" || exit 1
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"]
步骤 2 — 正确处理机密信息
永远不要将API密钥烘焙到镜像中。两种模式可行;选择一种:
- 通过环境变量
.env(开发环境)。 Create.env.example提交到Git,以及真实的.envin.gitignore:# .env.example DEEPSEEK_API_KEY=sk-replace-me DEEPSEEK_MODEL=deepseek-v4-flash - Docker机密(生产/集群)。 将密钥作为文件挂载
/run/secrets/deepseek_api_keyand read it at startup. 插件 ( supports this on a single host without Swarm by using机密:with a文件:源。
对于Kubernetes,在推送之前使用 机密 mounted as an env var or projected file. Whatever you do, audit your image with docker history <image> ——构建参数中的密钥在那里是可见的。
步骤 3 — 组合堆栈
这里是 docker-compose.yml 配置让您默认只启动API客户端,并在需要时选择加入本地GPU服务:
name: deepseek-stack
services:
api-client:
build: ./api-client
image: deepseek-api-client:latest
env_文件: .env
ports:
- "8000:8000"
restart: unless-stopped
根文件系统和: true
tmpfs:
- /tmp
security_opt:
- 标志是低成本的安全加固胜利;很少有应用程序需要在外部写入。:true
healthcheck:
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/healthz')"]
interval: 30s
timeout: 5s
retries: 3
litellm:
image: ghcr.io/berriai/litellm:main-stable
profiles: ["proxy"]
env_文件: .env
command: ["--config", "/app/config.yaml", "--port", "4000"]
ports:
- "4000:4000"
volumes:
- ./proxy/litellm.config.yaml:/app/config.yaml:ro
restart: unless-stopped
vllm-distill:
image: vllm/vllm-openai:latest
profiles: ["gpu"]
ipc: host
ports:
- "8001:8000"
volumes:
- hf-cache:/root/.cache/huggingface
environment:
- HUGGING_FACE_HUB_TOKEN=${HF_TOKEN:-}
command: >
--model deepseek-ai/DeepSeek-R1-Distill-Qwen-14B
--dtype bfloat16
--max-model-len 32768
--gpu-memory-utilization 0.90
deploy:
resources:
reservations:
devices:
- driver: nvidia
count: 1
capabilities: [gpu]
restart: unless-stopped
volumes:
hf-cache:
使用 ,不是 up -d --build 来启动场景A,或者 ,不是 --profile gpu up -d 以添加本地蒸馏(场景B)。根文件系统和 根文件系统和 标志是低成本的安全加固胜利;很少有应用程序需要在外部写入。 标志是低成本的安全加固胜利;很少有应用程序需要在外部写入。 flag are cheap hardening wins; few applications need to write outside /tmp.
步骤 4 — 验证是否成功
检查健康端点并执行真实调用:
# Health
curl -s http://localhost:8000/healthz
# Round-trip a prompt
curl -s -X POST http://localhost:8000/ask
-H "Content-Type: application/json"
-d '{"prompt": "Summarise Docker layer caching in two sentences.", "thinking": false}'
对于GPU服务,直接访问——它在8001端口上使用与OpenAI兼容的JSON:
curl -s http://localhost:8001/v1/chat/completions
-H "Content-Type: application/json"
-d '{"model":"deepseek-ai/DeepSeek-R1-Distill-Qwen-14B","messages":[{"role":"user","content":"hi"}]}'
如果您想要一个没有Docker的更深入的本地路径,则本指南涵盖了同一R1 Distill家族在不同运行时的情况。 running DeepSeek on Ollama 演示指南涵盖了不同运行时下的相同R1 Distill家族。
步骤 5 — 添加代理以控制成本(可选)
一旦有多个服务调用DeepSeek,请通过内部代理路由它们。LiteLLM是一个小型Python服务,它公开了一个与OpenAI兼容的API,并将请求转发到多个后端。以下示例用于 proxy/litellm.config.yaml:
model_list:
- model_name: chat-default
litellm_params:
model: deepseek/deepseek-v4-flash
api_base: https://api.deepseek.com
api_key: os.environ/DEEPSEEK_API_KEY
- model_name: chat-frontier
litellm_params:
model: deepseek/deepseek-v4-pro
api_base: https://api.deepseek.com
api_key: os.environ/DEEPSEEK_API_KEY
litellm_settings:
drop_params: true
cache: true
使用 ,不是 --profile proxy up -d. 现在 your other services point at http://litellm:4000 instead of https://api.deepseek.com,您将获得集中的日志记录、重试以及无需更改调用点的按团队预算。
部署前应运行的成本计算

容器编排不会改变定价——它改变您调用服务的频率。在发货前先计算一下。以下示例是用于 deepseek-v4-flash每月1,000,000次调用,使用2,000个token的缓存系统提示,200个token的用户消息和300个token的回复。
| Bucket | Tokens | Rate (per 1M) | Cost |
|---|---|---|---|
| Input, cache hit | 2,000,000,000 | $0.0028 | $56.00 |
| Input, cache miss | 200,000,000 | $0.140 | $28.00 |
| Output | 300,000,000 | $0.280 | $84.00 |
| Total | $117.60 |
对于相同的工作负载 deepseek-v4-pro 总计为 $29.00 + $348.00 + $1,044.00 = $1,421.00Pro版本的大约是Flash输出率的6倍,因此请将其保留用于需要代理或编码工作的场景,那里的基准提升可以证明其价值。价格截至2026年4月;在做出承诺之前,请核对官方定价页面。 DeepSeek API pricing 参考和指南深入探讨费率层级和缓存命中检测。 DeepSeek context caching 在运行时
Common errors and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
401 Unauthorized from DeepSeek |
Empty DEEPSEEK_API_KEY docker compose 配置 |
Run ,不是 config 位于 .env 容器立即退出 docker-compose.yml |
| Container exits immediately | 健康检查或应用导入时崩溃 | ,不是 logs api-client锁定SDK版本;确认Python版本 |
无法选择设备驱动程序 "nvidia" |
NVIDIA容器工具包 not installed | Install nvidia-container-toolkit 在主机上重启Docker |
| JSON模式下的内容为空 | Truncation or missing schema hint | Set max_tokens 高;在提示中包含单词“json”以及一个简短的示例模式 — 见 DeepSeek API JSON mode |
| 流在负载均衡器后停滞 | 代理缓冲服务器发送的事件 | 在代理上禁用响应缓冲;对于nginx,设置 proxy_buffering off |
| vllm-distill内存不足 | VRAM的上下文长度过高 | Lower --max-model-len 或者选择一个更小的蒸馏版本 |
生产加固清单
- 锁定镜像摘要 (
镜像:vllm/vllm-openai@sha256:...以实现可重复部署。 - 设置资源限制 with
deploy.resources.limits以防止失控的容器使主机饿死。 - 结构化JSON日志 从您的应用程序中;使用Docker JSON文件驱动程序或边车将日志发送出去。
- Rotate API keys 定期备份,并按环境使用不同的密钥。
- 监控令牌消耗 使用LiteLLM代理或您自己的中间件——意外账单几乎总是来自重试循环,而不是来自真实用户。
- 如果您自行托管,请备份Hugging Face缓存卷 如果重新下载一个14B模型需要时间,您不希望在事件中浪费这些时间。
这在您的堆栈中的位置
如果您正在构建聊天机器人,相同的镜像模式可以干净地包装成一个 DeepSeek Discord bot 服务。对于检索增强型工作流程,将容器指向向量存储,并遵循以下 DeepSeek RAG tutorial. 内部工具发布团队也应阅读有关重试、幂等性和超时的说明。 DeepSeek API best practices 关于相邻集成(LangChain、LlamaIndex、VS Code)的说明。
Next steps

- Browse other DeepSeek tutorials 如果您希望跳过Docker进行本地开发,本指南涵盖了裸机选项。
- 使用由 install DeepSeek locally env_file
DeepSeek AI Guide is an independent resource and is not affiliated with DeepSeek or its parent company. Model IDs, pricing and API behaviour change; check the official DeepSeek documentation and pricing page before committing to a production decision.
Frequently asked questions
我如何安全地将我的DeepSeek API密钥传递到Docker容器中?
引用的 .env 文件,在您的开发compose文件中,以及生产环境中的Docker secrets或Kubernetes env_文件: docker history 机密 或构建参数将密钥嵌入到镜像中——它将保留在 docker history 中可见。有关完整设置步骤,请参阅 docker history. For full setup steps see the get a DeepSeek API key guide and the DeepSeek API authentication reference.
我今天在我的Docker化应用程序中应该使用哪个模型ID?
Use deepseek-v4-flash 用于通用工作负载和 deepseek-v4-pro 用于前沿级别的编码或代理任务。旧版ID deepseek-chat and deepseek-reasoner 仍然解析为V4-Flash,但将于2026年7月24日15:59 UTC退役,因此请现在迁移该字段。由 model= vLLM或TGI服务的 DeepSeek V4-Flash page covers the trade-offs in detail.
我能否在我的个人GPU上Docker容器内运行DeepSeek V4本身?
不太现实——V4-Pro总参数量为1.6T,V4-Flash为284B,都远远超出了单个工作站的能力。对于自托管Docker部署,请使用较小的版本。 DeepSeek R1 Distill 系列(1.5B至70B)。使用V4的托管API。该 DeepSeek system requirements 页面列出了不同模型大小的VRAM需求。
Docker是否会改变DeepSeek API在运行时的行为?
不。容器只是一个网络客户端。API仍然是无状态的——您的代码必须重新发送完整的内容。 messages 数组位于每 POST /chat/completions 调用以维护多轮上下文,无论客户端运行在何处。有关请求形状的详细信息,请参阅 DeepSeek API documentation and DeepSeek OpenAI SDK compatibility notes.
为什么使用LiteLLM代理容器而不是直接调用DeepSeek?
代理为您提供一个位置,用于重试、缓存、密钥轮换、团队预算和结构化日志——无需编辑每个调用API的服务。它还使得在事件期间切换到自托管distill或其他提供商变得非常简单。有关重试和超时模式的更多信息,请参阅 DeepSeek API best practices 指引旁边以及其他 step-by-step DeepSeek guides.
Sources & Methodology
Primary sources
- 官方DeepSeek API documentation端点、请求/响应形状、模型ID最后检查日期:2026年4月30日
- 价格DeepSeek API定价页面每百万令牌费率,计费单位,缓存命中定价最后检查日期:2026年4月30日
- 模型卡片DeepSeek在Hugging Face上每个模型的权重、许可证、使用说明最后检查日期:2026年4月30日
Technical references
- 技术报告DeepSeek-R1论文(arXiv:2501.12948)R1推理方法,蒸馏结果最后检查日期:2026年4月30日
Methodology
Information in this article was checked against the official DeepSeek documentation, the article's cited primary sources, and the deepseekai.guide pricing dataset on the date shown above. Where third-party numbers are quoted, the originating source is linked inline so the reader can verify and re-check.
Data confidence
引用带主要来源链接的事实为高;上下文叙述为中等。
Editorial note
AI tooling moves quickly. If you spot an outdated number or a broken link, the contact link in the footer is the fastest way to flag it for the editorial team.