# 用 Docker 在 AWS EC2 上部署开源大模型（Llama 3）

URL: https://byshahid.com/zh/engineering/deploy-llama-3-docker-aws-ec2/
Author: Muhammad Shahid, Senior AI Software Engineer & Full Stack Developer (https://byshahid.com/)
Published: 2026-11-12

**快速解答:** 要用 Docker 在 AWS EC2 上部署 Llama 3，用 Deep Learning Base GPU AMI 启动一台 g6.xlarge（NVIDIA L4，24 GB）等 GPU 实例，这个 AMI 已经带有 NVIDIA 驱动、Docker 和 NVIDIA Container Toolkit。用 Hugging Face 令牌运行加载 meta-llama/Llama-3.1-8B-Instruct 的 vLLM 容器，让它的端口保持私有，并在前面放一个带 TLS、API 密钥和按密钥限流的 nginx 网关。你的应用用 OpenAI SDK 调用它，只需修改 base URL。

- **技术栈:** EC2 g6.xlarge、Deep Learning Base GPU AMI（Ubuntu 24.04）、Docker Compose、vLLM、nginx
- **模型:** meta-llama/Llama-3.1-8B-Instruct：受限访问，Llama 3.1 Community License，128k 上下文
- **显存:** 24 GB GPU 上约 16 GB 的 bf16 权重，剩下约 5.6 GB 给 KV cache
- **成本:** g6.xlarge 每小时 0.8048 美元：全天运行每月约 588 美元
- **测试:** 网关、密钥、限流、流式输出和客户端在本地对接 Ollama 上的 Llama 3.2 1B 运行；AWS 脚本只做了语法检查，未实际运行

自己运行一份 Llama，意味着数据留在你的 AWS 账户里，模型行为只有你改它才会变，成本是固定的按小时价格而不是按 token 计费。本教程介绍如何**用 Docker 在 AWS EC2 上部署 Llama 3**，并且做到可以面向真实用户：合适的 GPU 实例、受限的模型权重、Docker Compose 中的 vLLM、带 API 密钥和限流的 HTTPS 网关，以及使用普通 OpenAI SDK 的客户端。文章如实说明测试范围：网关、密钥、限流、流式输出、客户端和压测都在本地对接 Ollama 上的 Llama 3.2 1B 运行过，代替 GPU 上的 vLLM；AWS 命令和启动脚本做了语法检查并对照了 AWS 文档，但本文没有启动 GPU 实例，所以不给出 GPU 速度数据。

## 自托管 Llama 3 需要什么？

三样东西：一块显存足够放下权重和正在进行的对话的 GPU，一个能在这块 GPU 上批量处理大量请求的推理服务器，以及一个安全的入口。80 亿参数的模型用 16 位精度时，仅权重就约 16 GB（80 亿参数 × 2 字节），所以 24 GB 的 GPU 是实际可用的最低配置。这里的推理服务器是 **vLLM**：它提供 OpenAI 兼容 API，持续批处理请求，并按页管理 KV cache，让一块 GPU 同时服务多个用户。Meta 更新的模型（Llama 3.3 70B、Llama 4 Scout 和 Maverick）需要多得多的显存；同样的方案换用更大的实例即可。

## 什么时候值得自托管？

| 适合在 EC2 上自托管的情况 | 适合使用托管 API 的情况 |
| --- | --- |
| 数据必须留在你的 AWS 账户或区域内 | 你需要最强的模型 |
| 流量稳定，足以让 GPU 保持忙碌 | 流量很小或波动很大 |
| 需要几个月固定不变的模型版本 | 不想运维服务器 |
| 计划微调或使用自己的权重 | 需要超长上下文或大规模工具调用 |

无论回答一个问题还是几千个问题，GPU 每小时的费用都一样，所以只有在使用稳定时自托管才划算。[微调与 RAG 成本指南](/zh/engineering/fine-tuning-vs-rag-cost-saas/)计算了 GPU 与按 token 计费之间的盈亏平衡点，[AI API 成本计算器](/zh/tools/ai-api-cost-calculator/)则给出对比中 API 一侧的费用。

## 架构

![架构：应用调用 g6.xlarge 实例 443 端口上的 nginx 网关；网关检查 API 密钥和限流后转发给内部 8000 端口的 vLLM 容器，后者从缓存卷加载并服务 Llama 3.1 8B；配置来自 S3，Hugging Face 令牌来自 Parameter Store，证书通过 Route 53 从 Let's Encrypt 获取，管理访问通过 SSM Session Manager](https://byshahid.com/blog/img/engineering/deploy-llama-3-docker-aws-ec2/architecture.svg)

*一台实例，一个开放端口。模型服务器永远不会暴露在互联网上。*

只有网关是公开的，而且只开放 443 端口。vLLM 监听内部 Docker 网络。没有 SSH 端口：管理员通过 AWS Systems Manager Session Manager 连接。Hugging Face 令牌存放在 Parameter Store，而不是镜像或 user data 中；TLS 证书通过 DNS 验证签发，所以 80 端口从不开放。

## 需要准备什么？

| 项目 | 说明 | 原因 |
| --- | --- | --- |
| 有 G 系列实例配额的 AWS 账户 | 如果 "Running On-Demand G and VT instances" 的 vCPU 配额为 0，先申请 | 新账户通常无法启动 GPU 实例 |
| Hugging Face 账户和令牌 | 在模型页面接受 Llama 3.1 许可证 | 权重是受限访问的 |
| Route 53 中的域名 | 例如 llm.example.com | HTTPS 证书 |
| S3 存储桶 | 存放 compose.yaml、nginx.conf、keys.map、.env | 不把密钥打进 AMI 的配置方式 |
| AWS CLI | 在你的电脑上 | 运行启动脚本 |

## 步骤 1：选择实例

| 实例 | GPU | 显存 | vCPU / 内存 | 按需价格 |
| --- | --- | --- | --- | --- |
| g6.xlarge | NVIDIA L4 | 24 GB | 4 / 16 GiB | 每小时 0.8048 美元 |
| g5.xlarge | NVIDIA A10G | 24 GB | 4 / 16 GiB | 每小时 1.006 美元 |
| g6e.xlarge | NVIDIA L40S | 48 GB | 4 / 32 GiB | 每小时 1.861 美元 |

![使用 90% 显存时 bf16 Llama 3.1 8B 的显存估算：在 24 GB 的 L4 上，16 GB 权重之后剩约 5.6 GB KV cache，约可同时容纳 5 个 8,192 token 的对话；在 48 GB 的 L40S 上约 27 GB KV cache，约 25 个对话](https://byshahid.com/blog/img/engineering/deploy-llama-3-docker-aws-ec2/gpu-memory.svg)

*权重是固定的；剩下的显存决定能同时容纳多少对话。*

规格来自 AWS 实例页面，价格来自 Vantage 在 2026 年 11 月 12 日的 Linux 按需价格列表。显存分配说明了为什么这样选。Llama 3.1 8B 中，对话保存的每个 token 需要 128 KiB 的 KV cache（32 层 × 8 个键值头 × 128 维 × 2（键和值）× 2 字节），所以一个 8,192 token 的对话约需 1 GB。在 24 GB 的卡上，大约能同时容纳 5 个满长度对话，这就是为什么下面的 Compose 文件把上下文限制在 8,192 token，尽管模型支持 128k。如果需要更长的上下文或更多并发用户，下一步是 48 GB 的 g6e.xlarge。vLLM 启动时会打印真实的 KV cache 大小，以它为准，而不是这里的估算。

## 步骤 2：获取权重访问权限

`meta-llama/Llama-3.1-8B-Instruct` 在 Hugging Face 上是受限访问的：需要登录、在模型页面接受 Llama 3.1 Community License 并等待授权，之后才能下载。然后创建一个只读访问令牌，存为加密参数，这样它就不会出现在可能被提交的文件中：

```bash
read -rs -p "Hugging Face token: " HF_TOKEN   # not echoed, not saved in shell history
aws ssm put-parameter --region us-east-1 --name /llm/hf-token --type SecureString --value "$HF_TOKEN"
unset HF_TOKEN
```

## 步骤 3：启动实例

```bash
#!/bin/bash
# Run from your laptop with the AWS CLI. Creates an HTTPS-only security group and one g6.xlarge (NVIDIA L4, 24 GB).
set -euo pipefail
REGION=us-east-1
VPC_ID=vpc-0123456789abcdef0
SUBNET_ID=subnet-0123456789abcdef0      # a public subnet

AMI_ID=$(aws ssm get-parameter --region "$REGION" \
  --name /aws/service/deeplearning/ami/x86_64/base-oss-nvidia-driver-gpu-ubuntu-24.04/latest/ami-id \
  --query Parameter.Value --output text)

SG_ID=$(aws ec2 create-security-group --region "$REGION" --vpc-id "$VPC_ID" \
  --group-name llm-gateway --description "HTTPS only" --query GroupId --output text)
aws ec2 authorize-security-group-ingress --region "$REGION" --group-id "$SG_ID" \
  --protocol tcp --port 443 --cidr 0.0.0.0/0      # no port 22: use SSM Session Manager instead of SSH

aws ec2 run-instances --region "$REGION" \
  --image-id "$AMI_ID" --instance-type g6.xlarge \
  --subnet-id "$SUBNET_ID" --security-group-ids "$SG_ID" \
  --iam-instance-profile Name=llm-instance \
  --metadata-options HttpTokens=required,HttpPutResponseHopLimit=2 \
  --block-device-mappings 'DeviceName=/dev/sda1,Ebs={VolumeSize=100,VolumeType=gp3,Encrypted=true}' \
  --user-data file://user-data.sh \
  --tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=llm-llama-3-1-8b}]' \
  --query 'Instances[0].InstanceId' --output text
```

AMI 来自 AWS 为 Deep Learning Base OSS Nvidia Driver GPU AMI（Ubuntu 24.04）公布的公共 SSM 参数。它的发布说明列出了 NVIDIA 驱动、带 Compose 插件的 Docker、NVIDIA Container Toolkit 和 SSM agent。安全组只开放 443。`HttpTokens=required` 强制使用 IMDSv2，hop limit 设为 2 让容器（certbot）可以使用实例角色。根卷为 100 GB 加密 gp3，足够放镜像、权重和日志。

实例配置文件 `llm-instance` 需要 AWS 托管策略 `AmazonSSMManagedInstanceCore`（用于 Session Manager），再加上下面这个只覆盖自身配置、令牌和 DNS 记录的窄权限策略：

```json
{
  "Version": "2012-10-17",
  "Statement": [
    { "Sid": "ReadConfig", "Effect": "Allow", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::my-llm-config/llm/*" },
    { "Sid": "ListConfig", "Effect": "Allow", "Action": "s3:ListBucket", "Resource": "arn:aws:s3:::my-llm-config", "Condition": { "StringLike": { "s3:prefix": "llm/*" } } },
    { "Sid": "ReadToken", "Effect": "Allow", "Action": "ssm:GetParameter", "Resource": "arn:aws:ssm:us-east-1:*:parameter/llm/*" },
    { "Sid": "CertbotDns", "Effect": "Allow", "Action": ["route53:ListHostedZones", "route53:GetChange"], "Resource": "*" },
    { "Sid": "CertbotRecord", "Effect": "Allow", "Action": "route53:ChangeResourceRecordSets", "Resource": "arn:aws:route53:::hostedzone/Z0123456789EXAMPLE" }
  ]
}
```

## 步骤 4：启动脚本

```bash
#!/bin/bash
# EC2 user data: runs once, as root, on the first boot of the
# "Deep Learning Base OSS Nvidia Driver GPU AMI (Ubuntu 24.04)", which already ships the NVIDIA driver,
# Docker with the Compose plugin and the NVIDIA Container Toolkit.
set -euo pipefail
exec > >(tee -a /var/log/llm-setup.log) 2>&1

REGION=us-east-1
BUCKET=my-llm-config             # holds llm/compose.yaml, nginx.conf, keys.map and .env (no secrets)
DOMAIN=llm.example.com           # a Route 53 record pointing at this instance's Elastic IP

# 1. The GPU works on the host and inside containers
nvidia-smi
docker run --rm --gpus all ubuntu:24.04 nvidia-smi -L

# 2. Config from S3, the Hugging Face token from Parameter Store (never baked into the AMI or user data)
command -v aws >/dev/null || snap install aws-cli --classic
mkdir -p /opt/llm/certs
cd /opt/llm
aws s3 cp "s3://$BUCKET/llm/" . --recursive --region "$REGION"
HF_TOKEN=$(aws ssm get-parameter --region "$REGION" --name /llm/hf-token --with-decryption \
  --query Parameter.Value --output text)
echo "HF_TOKEN=$HF_TOKEN" >> .env
chmod 600 .env keys.map

# 3. TLS certificate from Let's Encrypt, proved over DNS (Route 53), so port 80 never has to open
docker run --rm -v /etc/letsencrypt:/etc/letsencrypt certbot/dns-route53 certonly \
  --dns-route53 -d "$DOMAIN" --non-interactive --agree-tos -m "admin@$DOMAIN"
cp -L "/etc/letsencrypt/live/$DOMAIN/fullchain.pem" "/etc/letsencrypt/live/$DOMAIN/privkey.pem" certs/

# 4. Start. The first start downloads the weights (about 16 GB) into the hf-cache volume.
docker compose up -d

# 5. Renew the certificate weekly and reload nginx without dropping connections
cat > /etc/cron.weekly/llm-cert <<CRON
#!/bin/bash
docker run --rm -v /etc/letsencrypt:/etc/letsencrypt certbot/dns-route53 renew --dns-route53 --quiet
cp -L /etc/letsencrypt/live/$DOMAIN/fullchain.pem /etc/letsencrypt/live/$DOMAIN/privkey.pem /opt/llm/certs/
docker compose -f /opt/llm/compose.yaml exec gateway nginx -s reload
CRON
chmod +x /etc/cron.weekly/llm-cert
```

脚本遇到第一个错误就停止（`set -euo pipefail`），并把日志写入 `/var/log/llm-setup.log`。它首先确认 GPU 在主机和容器内都可见，这样驱动问题会明确报错，而不是之后悄悄退化成缓慢的 CPU 运行。它只在缺少 AWS CLI 时才安装，从 S3 复制配置，以仅所有者可读的权限把令牌追加到 `.env`，获取证书并启动服务。每周的 cron 任务会续期证书并重新加载 nginx。

## 步骤 5：用 Docker Compose 运行 vLLM

```yaml
# /opt/llm/compose.yaml on the EC2 instance
services:
  llm:
    image: vllm/vllm-openai:${VLLM_TAG}        # pin a tested version in .env, never "latest" in production
    command:
      - --model=meta-llama/Llama-3.1-8B-Instruct
      - --served-model-name=llama-3.1-8b
      - --max-model-len=8192                  # fits the KV cache in 24 GB next to 16 GB of weights
      - --gpu-memory-utilization=0.90
    environment:
      - HF_TOKEN                              # read from .env: needed once to download the gated weights
    volumes:
      - hf-cache:/root/.cache/huggingface     # weights survive container restarts
    ipc: host
    deploy:
      resources:
        reservations:
          devices:
            - driver: nvidia
              count: all
              capabilities: [gpu]
    expose: ["8000"]                          # reachable only from the gateway, never from the internet
    healthcheck:
      test: ["CMD", "python3", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"]
      interval: 15s
      timeout: 5s
      retries: 3
      start_period: 600s                      # first start downloads about 16 GB
    restart: unless-stopped

  gateway:
    image: nginx:1.27
    ports: ["443:443"]
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf:ro
      - ./keys.map:/etc/nginx/keys.map:ro
      - ./certs:/etc/nginx/certs:ro
    depends_on:
      llm:
        condition: service_healthy
    restart: unless-stopped

volumes:
  hf-cache:
```

关键配置：`--served-model-name` 给客户端一个简短稳定的模型名；`--max-model-len=8192` 让上下文控制在 KV cache 预算内；`--gpu-memory-utilization=0.90` 留出余量（vLLM 自身的默认值取决于缓存模式，所以要显式设置）。`ipc: host` 为容器提供 PyTorch 需要的共享内存，正如 vLLM 的 Docker 指南所示。权重缓存在命名卷中，重启时不必再下载 16 GB；健康检查给首次启动留出十分钟。把 `VLLM_TAG` 写进 `.env` 并固定为测试过的版本：未固定的镜像可能在下次重启时改变行为。

## 步骤 6：在前面加一个 HTTPS 网关

```nginx
# The only public entry point: TLS, API keys, per-key rate limits, streaming.
events {}

http {
  map_hash_bucket_size 128;               # keys are long: "Bearer " + 64 hex characters
  # "Bearer <key>" -> client name. Unknown or missing keys map to "".
  map $http_authorization $client {
    default "";
    include /etc/nginx/keys.map;
  }

  limit_req_zone $client zone=perkey:10m rate=2r/s;
  limit_req_status 429;
  log_format llm '$time_iso8601 $client $status $request_time $upstream_response_time "$request"';
  access_log /dev/stdout llm;

  server {
    listen 443 ssl;
    http2 on;
    ssl_certificate     /etc/nginx/certs/fullchain.pem;
    ssl_certificate_key /etc/nginx/certs/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;

    client_max_body_size 1m;

    location = /health {
      proxy_pass http://llm:8000/health;
    }

    location /v1/ {
      if ($client = "") {
        return 401 '{"error":"invalid API key"}';
      }
      limit_req zone=perkey burst=10 nodelay;

      proxy_pass http://llm:8000;
      proxy_http_version 1.1;
      proxy_set_header Authorization "";     # the model server never sees client keys
      proxy_buffering off;                    # stream tokens as they are generated
      proxy_read_timeout 300s;
    }

    location / {
      return 404;
    }
  }
}
```

```text
# One line per client: the full Authorization header, then a name used for limits and logs.
# Generate keys with: openssl rand -hex 32
"Bearer 4f9c...replace-me...e21a" "web-app";
"Bearer 7b02...replace-me...91cd" "batch-jobs";
```

nginx 把整个 `Authorization` 头映射成客户端名称；需要设置 `map_hash_bucket_size 128`，因为密钥比 nginx 默认的桶大小更长，不设置的话 nginx 会拒绝启动（本地测试正好发现了这个问题）。未知密钥映射为空名称，在请求到达模型之前就返回 401。`limit_req` 按客户端名称允许每个密钥每秒 2 个请求、突发 10 个，这样一个高频应用不会挤占其他应用。`proxy_buffering off` 是流式输出能工作的关键：没有它，nginx 会先收完整个回答再发送。网关在转发前移除客户端密钥，只路由 `/v1/` 和 `/health`，并记录每个请求的客户端名称、状态和耗时。客户端多于几个时，把密钥移到数据库并存储哈希值，做法见 [AI API 安全指南](/zh/engineering/secure-llm-api-rate-limiting-prompt-injection/)。

## 步骤 7：在应用中调用

```ts
// Call your own Llama server with the OpenAI SDK: only the base URL and the key change.
import OpenAI from "openai";

export const llm = new OpenAI({
  baseURL: process.env.LLM_URL ?? "https://llm.example.com/v1",
  apiKey: process.env.LLM_KEY!, // one of the keys in keys.map, not an OpenAI key
  timeout: 120_000,
  maxRetries: 2, // retries 429 and 5xx with backoff
});
export const MODEL = process.env.LLM_MODEL ?? "llama-3.1-8b"; // --served-model-name

export async function ask(question: string) {
  const stream = await llm.chat.completions.create({
    model: MODEL,
    stream: true,
    max_tokens: 300,
    temperature: 0.2,
    messages: [
      { role: "system", content: "You are a concise assistant for a software team." },
      { role: "user", content: question },
    ],
  });
  let text = "";
  for await (const chunk of stream) {
    const delta = chunk.choices[0]?.delta?.content ?? "";
    text += delta;
    process.stdout.write(delta);
  }
  process.stdout.write("\n");
  return text;
}

if (import.meta.url === "file://" + process.argv[1]) {
  await ask(process.argv[2] ?? "In one sentence, what is a Docker volume?");
}
```

vLLM 使用 OpenAI API 协议，所以任何 OpenAI SDK 都能用：只需修改 `baseURL`、密钥和模型名。SDK 会对 429 和 5xx 响应进行退避重试，正好配合网关的限流。同一个客户端也可以用于[向 React 前端流式输出](/zh/engineering/react-streaming-llm-responses-sse/)或[函数调用](/zh/engineering/llm-function-calling-nodejs-microservices/)，不过 vLLM 中的工具调用需要额外的服务器参数，以及能很好处理工具调用的模型。

## 在本地测试整套服务

测试最容易出问题的部分不需要 GPU 实例：网关、密钥、限流、流式输出和客户端。本地环境使用同一个 `nginx.conf` 和自签名证书，用 CPU 上的 Ollama 代替 vLLM，在同一个内部端口上提供 Llama 3.2 1B。Ollama 同样提供 OpenAI 兼容的 `/v1/` API，所以请求完全一样。

```yaml
# Local stand-in for the EC2 stack: the same gateway config, with Ollama on CPU in place of vLLM on a GPU.
services:
  llm:
    image: ollama/ollama:latest
    environment:
      - OLLAMA_HOST=0.0.0.0:8000
    volumes:
      - ollama:/root/.ollama
    expose: ["8000"]
  gateway:
    image: nginx:1.27
    ports: ["8443:443"]
    volumes:
      - ../deploy/nginx.conf:/etc/nginx/nginx.conf:ro
      - ./keys.map:/etc/nginx/keys.map:ro
      - ./certs:/etc/nginx/certs:ro
    depends_on: [llm]
volumes:
  ollama:
```

```ts
// Checks the gateway in front of the model: keys, rate limits, streaming, and nothing else exposed.
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";

const BASE = "https://localhost:8443";
const KEY = readFileSync(new URL("../local/testkey", import.meta.url), "utf8").trim();
const MODEL = process.env.LLM_MODEL ?? "llama3.2:1b";
const auth = (k: string) => ({ Authorization: "Bearer " + k, "Content-Type": "application/json" });

// 1) No key, wrong key: 401 before the model is touched
assert.equal((await fetch(BASE + "/v1/models")).status, 401);
assert.equal((await fetch(BASE + "/v1/models", { headers: auth("x".repeat(64)) })).status, 401);
// 2) Only /v1/ and /health are routed
assert.equal((await fetch(BASE + "/api/tags", { headers: auth(KEY) })).status, 404);
console.log("gateway: 401 without or with a wrong key, 404 outside /v1/");

// 3) A real answer, streamed through nginx without buffering
const t0 = performance.now();
const res = await fetch(BASE + "/v1/chat/completions", {
  method: "POST",
  headers: auth(KEY),
  body: JSON.stringify({ model: MODEL, stream: true, max_tokens: 60, temperature: 0, messages: [{ role: "user", content: "Name three Linux distributions." }] }),
});
assert.equal(res.status, 200);
const reader = res.body!.getReader();
const dec = new TextDecoder();
let first = 0, reads = 0, text = "";
for (;;) {
  const { done, value } = await reader.read();
  if (done) break;
  if (!first) first = performance.now() - t0;
  reads++;
  text += dec.decode(value, { stream: true });
}
const total = performance.now() - t0;
const content = text.split("\n").filter((l) => l.startsWith("data: {")).map((l) => JSON.parse(l.slice(6)).choices[0]?.delta?.content ?? "").join("");
assert.ok(reads > 5, "tokens should arrive in many pieces, not one buffered block");
assert.ok(first < total / 2);
console.log("streaming: first bytes after", Math.round(first), "ms, done after", Math.round(total), "ms, in", reads, "reads:", JSON.stringify(content.trim().slice(0, 80)));

// 4) Rate limit: 2 requests/s with a burst of 10 per key
const statuses = await Promise.all(Array.from({ length: 20 }, () => fetch(BASE + "/v1/models", { headers: auth(KEY) }).then((r) => r.status)));
const ok = statuses.filter((s) => s === 200).length;
const limited = statuses.filter((s) => s === 429).length;
assert.equal(ok + limited, 20);
assert.ok(ok >= 11 && ok <= 12, "burst of 10 plus the current slot");
console.log("rate limit: 20 parallel requests, " + ok + " allowed, " + limited + " got 429");
console.log("ALL GATEWAY TESTS PASS");
```

```bash
cd local
openssl req -x509 -newkey rsa:2048 -nodes -days 7 -subj "/CN=localhost" \
  -addext "subjectAltName=DNS:localhost" -keyout certs/privkey.pem -out certs/fullchain.pem
KEY=$(openssl rand -hex 32); echo "$KEY" > testkey; printf '"Bearer %s" "test-client";\n' "$KEY" > keys.map
docker compose up -d && docker compose exec llm ollama pull llama3.2:1b
cd .. && NODE_EXTRA_CA_CERTS=local/certs/fullchain.pem npx tsx test/gateway.test.ts
```

输出：

```text
gateway: 401 without or with a wrong key, 404 outside /v1/
streaming: first bytes after 660 ms, done after 1649 ms, in 18 reads: "Here are three Linux distributions:\n\n1. Ubuntu\n2. Fedora\n3. Debian"
rate limit: 20 parallel requests, 11 allowed, 9 got 429
ALL GATEWAY TESTS PASS
```

测试检查网关必须做到的四件事。没有密钥或密钥错误返回 401，`/v1/` 以外的路径返回 404。一个流式回答分 18 次到达，总共 1,649 毫秒，第一段在 660 毫秒时到达，说明 nginx 没有缓冲。同一个密钥的 20 个并行请求中，11 个通过（突发 10 个加 1 个），9 个返回 429。最开始的一次运行在流式检查上失败了，因为 Ollama 还在加载模型，这是个有用的提醒：启动后的第一个请求很慢，所以在实例接收流量前先发一个预热请求。

## 速度有多快？

```ts
// Load test: N users at once, each streaming one answer. Reports time to first token and output speed.
import { llm, MODEL } from "./chat";

async function one(prompt: string) {
  const t0 = performance.now();
  let first = 0;
  let chunks = 0;
  let tokens = 0;
  const stream = await llm.chat.completions.create({
    model: MODEL,
    stream: true,
    stream_options: { include_usage: true },
    max_tokens: 128,
    temperature: 0,
    messages: [{ role: "user", content: prompt }],
  });
  for await (const chunk of stream) {
    if (chunk.choices[0]?.delta?.content) {
      if (!first) first = performance.now();
      chunks++;
    }
    if (chunk.usage) tokens = chunk.usage.completion_tokens;
  }
  const end = performance.now();
  return { ttft: first - t0, total: end - t0, tokens: tokens || chunks };
}

const pct = (xs: number[], p: number) => [...xs].sort((a, b) => a - b)[Math.min(xs.length - 1, Math.floor(p * xs.length))];

for (const users of (process.env.USERS ?? "1,4,8").split(",").map(Number)) {
  const t0 = performance.now();
  const runs = await Promise.all(
    Array.from({ length: users }, (_, i) => one("Explain container image layers in about 100 words. Variant " + i + ".")),
  );
  const wall = (performance.now() - t0) / 1000;
  const tokens = runs.reduce((n, r) => n + r.tokens, 0);
  console.log(
    users + " at once: TTFT p50 " + Math.round(pct(runs.map((r) => r.ttft), 0.5)) + " ms, p95 " +
      Math.round(pct(runs.map((r) => r.ttft), 0.95)) + " ms | " + Math.round(tokens / wall) + " output tokens/s in total, " +
      Math.round(tokens / users / wall) + " per user",
  );
}
```

这是本地运行的数据：在笔记本电脑的 Docker 中用 CPU 运行 1B 模型。它们不能说明 GPU 上的情况，但展示了需要关注的规律。一个用户时，第一个 token 在一秒内到达，速度为每秒 17 个 token。4 个和 8 个用户同时请求时，总吞吐几乎没有增长，用户要等 13 到 31 秒才看到第一个 token，因为请求在排队：这是服务器容量不足的表现。笔记本上每次运行的时间会有差异。

```text
1 at once: TTFT p50 960 ms, p95 960 ms | 17 output tokens/s in total, 17 per user
4 at once: TTFT p50 23480 ms, p95 30673 ms | 13 output tokens/s in total, 3 per user
8 at once: TTFT p50 12853 ms, p95 20721 ms | 19 output tokens/s in total, 2 per user
```

对 EC2 实例运行同一个脚本，就能得到真正重要的数据：首 token 时间（用户看到文字前要等多久），以及 1、4、8 个用户时的总输出 token 速度。预期总吞吐会随用户增加而增长，而每个用户的速度下降，直到 KV cache 占满、新请求开始排队。注意 vLLM 日志中的 preemption 警告：它们说明缓存对当前负载来说太小了。

## 成本是多少？

![一台实例全天运行的按需月成本：g6.xlarge 约 588 美元，g5.xlarge 约 734 美元，g6e.xlarge 约 1,359 美元；g6.xlarge 只在 22 个工作日每天运行 12 小时约 212 美元](https://byshahid.com/blog/img/engineering/deploy-llama-3-docker-aws-ec2/monthly-cost.svg)

*账单取决于运行时长，而不是请求数量。*

按需价格乘以 730 小时：g6.xlarge 每月约 588 美元，g5.xlarge 约 734 美元，g6e.xlarge 约 1,359 美元，另加 EBS 卷和数据传输费用。只在工作时间使用的内部工具可以在夜间停机：22 个工作日每天运行 12 小时，g6.xlarge 降到约 212 美元。Savings Plans 能降低稳定使用的价格；Spot 实例更便宜，但可能被回收，只在可以接受重启的地方使用。

## 运维：更新、监控、备份

- **更新：**修改 `VLLM_TAG`，先在第二台实例上运行 `docker compose pull && docker compose up -d`，用测试提示词对比回答，然后再切换。

- **监控：**vLLM 在 `/metrics` 暴露 Prometheus 指标（保持内部访问）；关注运行中和排队的请求、KV cache 使用率和首 token 时间。为健康检查和 GPU 显存错误设置告警。

- **日志：**网关记录客户端、状态和耗时，不记录提示词。用 CloudWatch agent 发送到 CloudWatch。

- **备份：**需要保存的状态很少。把配置放在开启版本控制的 S3 中；权重随时可以重新下载。

- **扩展：**流量更大时，在 Application Load Balancer 后面运行多台实例，或者先换更大的 GPU 再增加实例。

## 常见错误及修复方法

| 错误 | 后果 | 修复 |
| --- | --- | --- |
| 8000 端口对互联网开放 | 任何人都能使用你的 GPU | 只通过 443 暴露网关 |
| 24 GB GPU 上没有设置 --max-model-len | vLLM 无法启动或只能容纳一个长对话 | 设置 --max-model-len=8192 |
| HF 令牌写在 user data 或镜像里 | 能读取其中之一的人都能拿到令牌 | Parameter Store SecureString，启动时读取 |
| 未在 Hugging Face 接受许可证 | 下载失败，返回 401 或 403 | 先接受 Llama 3.1 许可证 |
| 没有关闭代理缓冲 | 流式输出在最后一次性到达 | proxy_buffering off |
| nginx map 中使用 64 个字符的密钥但保持默认设置 | nginx 无法启动：could not build map_hash | map_hash_bucket_size 128 |
| 未固定 vllm-openai:latest | 重启后行为悄悄改变 | 固定 VLLM_TAG |
| 权重不在卷上 | 每次重启都重新下载 16 GB | 挂载 Hugging Face 缓存 |
| 实例闲置但一直运行 | 为空闲的 GPU 时间付费 | 按工作时间计划启停 |

## 局限

一台实例就是单点故障；要承诺可用性，需要两台实例和负载均衡。8B 模型在推理和复杂长任务上远弱于最强的托管模型，所以在依赖它之前要用自己的提示词测试。这里的显存数据是计算结果而不是实测，本文也没有在 GPU 上运行 vLLM，所以请用压测脚本在你的实例上测量速度。最后，Llama 许可证有自己的条款，包括可接受使用政策；在此基础上发布产品之前请先阅读。

## vLLM、Ollama 还是托管服务？

**vLLM** 为在 GPU 上服务大量用户而设计，具备持续批处理和分页 KV cache，是生产环境的选择。**Ollama** 安装更简单，非常适合笔记本、个人开发者或本文的本地测试，但它不是为高并发服务设计的。Amazon Bedrock 或 SageMaker 这样的**托管服务**以另一种价格省去服务器工作：用控制权换取更少的运维。如果不确定，先用托管 API，测量真实流量，等数据表明值得时再换成自己的 GPU。

## 常见问题

### 在 AWS 上运行 Llama 3 8B 需要什么实例？

至少 24 GB 显存的 GPU，例如 g6.xlarge（NVIDIA L4）或 g5.xlarge（NVIDIA A10G）。bf16 权重约占 16 GB，其余用于活动对话的 KV cache。

### 在 EC2 上运行 Llama 3 要多少钱？

2026 年 11 月 g6.xlarge 按需价格为每小时 0.8048 美元，全天运行每月约 588 美元。非工作时间停机可降到约 212 美元。

### 生产环境为什么用 vLLM 而不是 Ollama？

vLLM 把大量请求一起批处理并按页管理显存，一块 GPU 就能高效服务多个用户。Ollama 更简单，适合单用户或本地测试。

### 下载 Llama 3 需要 Hugging Face 令牌吗？

需要。Llama 3.1 是受限访问的：先在模型页面接受许可证，再使用读取令牌。把它存放在 Parameter Store，不要放进镜像或 user data。

### 应该使用哪个 AMI？

Deep Learning Base OSS Nvidia Driver GPU AMI（Ubuntu 24.04）。它的发布说明列出了 NVIDIA 驱动、带 Compose 的 Docker 和 NVIDIA Container Toolkit，AWS 以公共 SSM 参数发布它的 ID。

### 自托管的 Llama 能用 OpenAI SDK 调用吗？

可以。vLLM 提供 OpenAI 兼容 API，把 SDK 的 baseURL 设为你服务器的 /v1，并使用你自己的 API 密钥。

### Llama 3.1 支持 128k，为什么把上下文限制在 8,192 token？

在 24 GB GPU 上，权重之后剩下的 KV cache 只有约 5.6 GB，每个 8,192 token 的对话约需 1 GB。更长的上下文需要更大的 GPU。

### 如何保护自托管的大模型？

让模型端口保持私有，前面放一个带 API 密钥和按密钥限流的 TLS 网关，只开放 443 端口，用 Session Manager 代替 SSH。

### 为什么通过 nginx 时流式输出不起作用？

nginx 默认会缓冲上游响应。在 API 路径中设置 proxy_buffering off。

### 能在一块 EC2 GPU 上运行 Llama 3 70B 吗？

在 16 位精度下，24 或 48 GB 的卡都不行：仅权重就约 140 GB。需要多块 GPU 或量化模型。

### 如何安全地升级 vLLM？

固定镜像标签，在第二台实例上用自己的提示词测试新版本，然后再切换流量。

### 自托管比 API 便宜吗？

只有在流量稳定时才是。GPU 在任何负载下每小时的费用都一样，所以迁移前先把每月的 token 账单和实例价格对比一下。

## 来源

- [AWS: Amazon EC2 G6 instances (NVIDIA L4)](https://aws.amazon.com/ec2/instance-types/g6/)
- [AWS: Amazon EC2 G5 instances (NVIDIA A10G)](https://aws.amazon.com/ec2/instance-types/g5/)
- [AWS: Amazon EC2 G6e instances (NVIDIA L40S)](https://aws.amazon.com/ec2/instance-types/g6e/)
- [Vantage: g6.xlarge on-demand pricing](https://instances.vantage.sh/aws/ec2/g6.xlarge)
- [AWS Docs: Deep Learning Base GPU AMI (Ubuntu 24.04)](https://docs.aws.amazon.com/dlami/latest/devguide/aws-deep-learning-x86-base-gpu-ami-ubuntu-24-04.html)
- [vLLM Docs: Using Docker](https://docs.vllm.ai/en/latest/deployment/docker.html)
- [vLLM Docs: Engine arguments](https://docs.vllm.ai/en/latest/configuration/engine_args/)
- [Hugging Face: meta-llama/Llama-3.1-8B-Instruct](https://huggingface.co/meta-llama/Llama-3.1-8B-Instruct)
- [AWS Docs: Session Manager](https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager.html)
- [nginx: limit_req module](https://nginx.org/en/docs/http/ngx_http_limit_req_module.html)
- [nginx: map module](https://nginx.org/en/docs/http/ngx_http_map_module.html)
- [Docker Hub: ollama/ollama](https://hub.docker.com/r/ollama/ollama)

查看相关服务: https://byshahid.com/zh/ai-app-deployment/
