# Deploying Open-Source LLMs (Llama 3) on AWS EC2 with Docker

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

**Quick answer:** To deploy Llama 3 on AWS EC2 with Docker, launch a GPU instance such as a g6.xlarge (NVIDIA L4, 24 GB) from the Deep Learning Base GPU AMI, which already has the NVIDIA driver, Docker and the NVIDIA Container Toolkit. Run the vLLM container with meta-llama/Llama-3.1-8B-Instruct and a Hugging Face token, keep its port private, and put an nginx gateway in front with TLS, API keys and per-key rate limits. Your apps then call it with the OpenAI SDK by changing only the base URL.

- **Stack:** EC2 g6.xlarge, Deep Learning Base GPU AMI (Ubuntu 24.04), Docker Compose, vLLM, nginx
- **Model:** meta-llama/Llama-3.1-8B-Instruct: gated, Llama 3.1 Community License, 128k context
- **Memory:** About 16 GB of bf16 weights on a 24 GB GPU leaves about 5.6 GB for the KV cache
- **Cost:** g6.xlarge at $0.8048 an hour: about $588 a month if it runs all the time
- **Tested:** Gateway, keys, limits, streaming and the client run locally against Llama 3.2 1B on Ollama; the AWS scripts are syntax-checked, not run

Running your own copy of Llama gives you a model whose data stays in your AWS account, whose behaviour does not change unless you change it, and whose cost is a fixed hourly price instead of a per-token bill. This tutorial shows how to **deploy Llama 3 with Docker on AWS EC2** in a way you could put in front of real users: the right GPU instance, the gated weights, vLLM in Docker Compose, an HTTPS gateway with API keys and rate limits, and a client that uses the ordinary OpenAI SDK. It is honest about what was tested. The gateway, keys, rate limits, streaming, client and load test were run locally against Llama 3.2 1B on Ollama, in place of vLLM on a GPU; the AWS commands and the boot script were checked for syntax and against AWS's documentation, but this article did not launch a GPU instance, so it gives no GPU speed figures.

## What does it take to self-host Llama 3?

Three things: a GPU with enough memory for the weights plus the conversations in flight, an inference server that batches many requests on that GPU, and a secure front door. For an 8-billion-parameter model in 16-bit precision, the weights alone are about 16 GB (8 billion parameters × 2 bytes), so a 24 GB GPU is the practical minimum. **vLLM** is the inference server here: it serves an OpenAI-compatible API, batches requests continuously and manages the KV cache in pages, which lets one GPU serve several users at once. Meta's newer models (Llama 3.3 70B, Llama 4 Scout and Maverick) need far more GPU memory; the same setup applies with a bigger instance.

## When is self-hosting worth it?

| Self-host on EC2 when | Use a hosted API when |
| --- | --- |
| Data must stay in your AWS account or region | You want the strongest models available |
| Traffic is steady enough to keep a GPU busy | Traffic is low or spiky |
| You need a fixed model version for months | You do not want to run servers |
| You plan to fine-tune or use your own weights | You need very long contexts or tool use at scale |

A GPU costs the same per hour whether it answers one question or thousands, so self-hosting pays off only with steady use. The [fine-tuning vs RAG cost guide](/engineering/fine-tuning-vs-rag-cost-saas/) works through the break-even between a GPU and per-token prices, and the [AI API cost calculator](/tools/ai-api-cost-calculator/) gives the API side of that comparison.

## The architecture

![Architecture: apps call an nginx gateway on port 443 of a g6.xlarge instance; the gateway checks API keys and rate limits and forwards to the vLLM container on an internal port 8000, which serves Llama 3.1 8B from a cached volume; configuration comes from S3, the Hugging Face token from Parameter Store, the certificate from Let's Encrypt over Route 53, and admin access is through SSM Session Manager](https://byshahid.com/blog/img/engineering/deploy-llama-3-docker-aws-ec2/architecture.svg)

*One instance, one open port. The model server is never reachable from the internet.*

Only the gateway is public, and only on port 443. vLLM listens on an internal Docker network. There is no SSH port: administrators connect with AWS Systems Manager Session Manager. The Hugging Face token lives in Parameter Store, not in the image or the user data, and the TLS certificate is issued over DNS so port 80 never opens.

## What do you need?

| Item | Detail | Why |
| --- | --- | --- |
| AWS account with G-instance quota | Request "Running On-Demand G and VT instances" vCPUs if it is 0 | New accounts often cannot start GPU instances |
| Hugging Face account and token | Accept the Llama 3.1 licence on the model page | The weights are gated |
| A domain in Route 53 | For example llm.example.com | HTTPS certificate |
| S3 bucket | Holds compose.yaml, nginx.conf, keys.map, .env | Config without baking secrets into the AMI |
| AWS CLI | On your laptop | Runs the launch script |

## Step 1: Pick the instance

| Instance | GPU | GPU memory | vCPU / RAM | On-demand price |
| --- | --- | --- | --- | --- |
| g6.xlarge | NVIDIA L4 | 24 GB | 4 / 16 GiB | $0.8048 an hour |
| g5.xlarge | NVIDIA A10G | 24 GB | 4 / 16 GiB | $1.006 an hour |
| g6e.xlarge | NVIDIA L40S | 48 GB | 4 / 32 GiB | $1.861 an hour |

![Approximate GPU memory budget for Llama 3.1 8B in bf16 with 90% of memory used: on a 24 GB L4, 16 GB of weights leave about 5.6 GB of KV cache, about five 8,192-token conversations at once; on a 48 GB L40S about 27 GB of KV cache, about 25 conversations](https://byshahid.com/blog/img/engineering/deploy-llama-3-docker-aws-ec2/gpu-memory.svg)

*The weights are fixed; what is left decides how many conversations fit at once.*

Specifications come from AWS's instance pages and prices from Vantage's on-demand Linux listing on 12 November 2026. The memory picture explains the choice. Each token a conversation holds needs 128 KiB of KV cache for Llama 3.1 8B (32 layers × 8 key-value heads × 128 dimensions × 2 for keys and values × 2 bytes), so an 8,192-token conversation needs about 1 GB. On a 24 GB card that leaves room for roughly five full-length conversations at once, which is why the Compose file below caps the context at 8,192 tokens even though the model supports 128k. If you need longer contexts or more users at once, the 48 GB g6e.xlarge is the next step. vLLM prints the real KV cache size when it starts; trust that over this arithmetic.

## Step 2: Get access to the weights

`meta-llama/Llama-3.1-8B-Instruct` is gated on Hugging Face: you must sign in, accept the Llama 3.1 Community License on the model page, and wait for access before a download works. Then create a read-only access token and store it as an encrypted parameter, so it never sits in a file you might commit:

```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
```

## Step 3: Launch the instance

```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
```

The AMI comes from the public SSM parameter AWS documents for the Deep Learning Base OSS Nvidia Driver GPU AMI (Ubuntu 24.04). Its release notes list the NVIDIA driver, Docker with the Compose plugin, the NVIDIA Container Toolkit and the SSM agent. The security group opens only 443. `HttpTokens=required` enforces IMDSv2, and a hop limit of 2 lets containers (certbot) use the instance role. The root volume is 100 GB of encrypted gp3, enough for the image, the weights and logs.

The instance profile `llm-instance` needs the AWS managed policy `AmazonSSMManagedInstanceCore` for Session Manager, plus this narrow policy for its own config, token and DNS record:

```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" }
  ]
}
```

## Step 4: The boot script

```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
```

The script stops at the first failure (`set -euo pipefail`) and logs to `/var/log/llm-setup.log`. It first proves that the GPU is visible on the host and inside a container, so a driver problem fails loudly instead of showing up later as a slow CPU fallback. It installs the AWS CLI only if it is missing, copies the config from S3, appends the token to `.env` with owner-only permissions, gets a certificate and starts the stack. A weekly cron job renews the certificate and reloads nginx.

## Step 5: Run vLLM with Docker Compose

```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:
```

The important lines: `--served-model-name` gives clients a short, stable model name; `--max-model-len=8192` keeps the context within the KV cache budget; `--gpu-memory-utilization=0.90` leaves headroom (vLLM's own default depends on its cache mode, so set it explicitly). `ipc: host` gives the container the shared memory PyTorch needs, as vLLM's Docker guide shows. The weights are cached in a named volume so a restart does not download 16 GB again, and the health check gives the first start ten minutes. Put `VLLM_TAG` in `.env` and pin a version you have tested: an unpinned image can change behaviour on the next restart.

## Step 6: Put an HTTPS gateway in front

```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 maps the whole `Authorization` header to a client name; `map_hash_bucket_size 128` is needed because the keys are longer than nginx's default bucket allows, and without it nginx refuses to start (the local test caught exactly that). An unknown key maps to an empty name and gets a 401 before the model is touched. `limit_req` allows each key 2 requests a second with a burst of 10, keyed by client name, so one noisy app cannot starve the others. `proxy_buffering off` is what makes streaming work: without it nginx collects the whole answer before sending anything. The gateway removes the client's key before forwarding, routes only `/v1/` and `/health`, and logs the client name, status and timings for every request. For more than a handful of clients, move the keys to a database with hashed values, as in the [guide to securing AI APIs](/engineering/secure-llm-api-rate-limiting-prompt-injection/).

## Step 7: Call it from your app

```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?");
}
```

Because vLLM speaks the OpenAI API, any OpenAI SDK works: only `baseURL`, the key and the model name change. The SDK retries 429 and 5xx responses with backoff, which suits the gateway's rate limits. The same client works with [streaming to a React front end](/engineering/react-streaming-llm-responses-sse/) or with [function calling](/engineering/llm-function-calling-nodejs-microservices/), although tool calls in vLLM need extra server flags and a model that handles them well.

## Testing the stack locally

A GPU instance is not needed to test the parts most likely to break: the gateway, keys, limits, streaming and client. The local stack uses the same `nginx.conf` with a self-signed certificate, and Ollama on the CPU in place of vLLM, serving Llama 3.2 1B on the same internal port. Ollama also serves an OpenAI-compatible `/v1/` API, so the requests are the same.

```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
```

Output:

```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
```

The test checks the four things a gateway must do. No key or a wrong key gets a 401, and paths outside `/v1/` get a 404. A streamed answer arrived in 18 pieces, the first after 660 ms of 1,649 ms in total, so nginx is not buffering. Of 20 parallel requests with one key, 11 passed (the burst of 10 plus one) and 9 got a 429. The very first run failed the streaming check because Ollama was still loading the model, which is a useful warning: the first request after a start is slow, so send a warm-up request before the instance takes traffic.

## How fast is it?

```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",
  );
}
```

These are the numbers from the local run: a 1B model on the CPU, inside Docker on a laptop. They say nothing about a GPU, but they show the pattern to look for. With one user, the first token arrived in under a second at 17 tokens a second. With 4 and 8 users at once, total throughput barely grew and people waited between 13 and 31 seconds for their first token, because the requests queued behind each other: a server out of capacity. Times vary between runs on a laptop.

```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
```

Run the same script against the EC2 instance and you get the numbers that matter: time to first token (how long a user waits before text appears) and total output tokens per second at 1, 4 and 8 users. Expect total throughput to grow with users while each user's speed falls, until the KV cache is full and new requests start to queue. Watch the vLLM log for preemption warnings; they mean the cache is too small for the load.

## What does it cost?

![Monthly on-demand cost for one instance running all the time: g6.xlarge about $588, g5.xlarge about $734, g6e.xlarge about $1,359; a g6.xlarge running 12 hours on 22 weekdays costs about $212](https://byshahid.com/blog/img/engineering/deploy-llama-3-docker-aws-ec2/monthly-cost.svg)

*The bill depends on hours running, not on requests served.*

On-demand prices times 730 hours: about $588 a month for a g6.xlarge, $734 for a g5.xlarge and $1,359 for a g6e.xlarge, plus the EBS volume and data transfer. An internal tool used in office hours can stop at night: 12 hours on 22 weekdays brings a g6.xlarge down to about $212. Savings Plans cut the price for steady use; Spot instances are cheaper still but can be reclaimed, so use them only where a restart is acceptable.

## Operating it: updates, monitoring, backups

- **Updates:** change `VLLM_TAG`, run `docker compose pull && docker compose up -d` on a second instance first, compare answers on your test prompts, then switch.

- **Monitoring:** vLLM exposes Prometheus metrics on `/metrics` (keep it internal); track running and waiting requests, KV cache use and time to first token. Alarm on the health check and on GPU memory errors.

- **Logs:** the gateway logs the client, status and timings, not the prompt. Ship them to CloudWatch with the CloudWatch agent.

- **Backups:** there is little state. Keep the config in S3 with versioning; the weights can always be downloaded again.

- **Scaling:** for more traffic, run several instances behind an Application Load Balancer, or move to a larger GPU before adding instances.

## Common mistakes and how to fix them

| Mistake | What happens | Fix |
| --- | --- | --- |
| Port 8000 open to the internet | Anyone can use your GPU | Expose only the gateway on 443 |
| No --max-model-len on a 24 GB GPU | vLLM fails to start or fits only one long conversation | Set --max-model-len=8192 |
| HF token in user data or the image | The token leaks to anyone who can read either | Parameter Store SecureString, read at boot |
| Licence not accepted on Hugging Face | Download fails with 401 or 403 | Accept the Llama 3.1 licence first |
| Proxy buffering left on | Streaming arrives in one block at the end | proxy_buffering off |
| 64-character keys in an nginx map with default settings | nginx will not start: could not build map_hash | map_hash_bucket_size 128 |
| Unpinned vllm-openai:latest | A restart silently changes behaviour | Pin VLLM_TAG |
| Weights not on a volume | Every restart downloads 16 GB again | Mount the Hugging Face cache |
| Instance left running unused | You pay for idle GPU hours | Schedule stop and start for office hours |

## Limitations

One instance is one point of failure; for an uptime promise you need two instances behind a load balancer. An 8B model is much weaker than the best hosted models at reasoning and long, complex tasks, so test it on your own prompts before you rely on it. The memory figures here are arithmetic, not measurements, and this article did not run vLLM on a GPU, so measure speed on your instance with the load-test script. Finally, the Llama licence has its own terms, including an acceptable use policy; read it before you ship a product on it.

## vLLM, Ollama or a managed service?

**vLLM** is built for serving many users on a GPU, with continuous batching and paged KV cache, and is the choice for production. **Ollama** is easier to install and great for a laptop, a single developer or the local test in this article, but it is not designed for high-concurrency serving. A **managed service** such as Amazon Bedrock or SageMaker removes the server work at a different price: you trade control for less operations work. If you are unsure, start with a hosted API, measure your real traffic, and move to your own GPU when the numbers say so.

## Frequently asked questions

### What instance do I need to run Llama 3 8B on AWS?

A GPU with at least 24 GB of memory, such as a g6.xlarge (NVIDIA L4) or g5.xlarge (NVIDIA A10G). The bf16 weights take about 16 GB; the rest holds the KV cache for active conversations.

### How much does it cost to run Llama 3 on EC2?

A g6.xlarge was $0.8048 an hour on demand in November 2026, about $588 a month if it runs all the time. Stopping it outside office hours cuts that to about $212.

### Why use vLLM instead of Ollama in production?

vLLM batches many requests together and manages GPU memory in pages, so one GPU serves several users efficiently. Ollama is simpler and fine for one user or local testing.

### Do I need a Hugging Face token to download Llama 3?

Yes. Llama 3.1 is gated: accept the licence on the model page, then use a read token. Store it in Parameter Store, not in your image or user data.

### Which AMI should I use?

The Deep Learning Base OSS Nvidia Driver GPU AMI (Ubuntu 24.04). Its release notes list the NVIDIA driver, Docker with Compose and the NVIDIA Container Toolkit, and AWS publishes its ID as a public SSM parameter.

### Can I use the OpenAI SDK with a self-hosted Llama?

Yes. vLLM serves an OpenAI-compatible API, so set the SDK's baseURL to your server's /v1 and use one of your own API keys.

### Why limit the context to 8,192 tokens when Llama 3.1 supports 128k?

On a 24 GB GPU, the KV cache left after the weights holds only about 5.6 GB, about 1 GB per 8,192-token conversation. Longer contexts need a bigger GPU.

### How do I secure a self-hosted LLM?

Keep the model port private, put a TLS gateway in front with API keys and per-key rate limits, open only port 443, and use Session Manager instead of SSH.

### Why does streaming not work through nginx?

nginx buffers upstream responses by default. Set proxy_buffering off for the API location.

### Can I run Llama 3 70B on one EC2 GPU?

Not on a 24 or 48 GB card in 16-bit precision: the weights alone are about 140 GB. You need several GPUs or a quantised model.

### How do I update vLLM safely?

Pin the image tag, test a new version on a second instance with your own prompts, then switch traffic.

### Is self-hosting cheaper than an API?

Only with steady traffic. A GPU costs the same per hour at any load, so compare your monthly token bill with the instance price before you move.

## Sources

- [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)

See the related service: https://byshahid.com/ai-app-deployment/
