←Back to Guides
๐Ÿค–Local AI & DevOpsโฑ๏ธ 15 min read•Updated October 2026

Ollama & Local LLM CLI Master Cheat Sheet

A definitive production CLI reference and sysadmin guide for serving open-weight Large Language Models locally with Ollama. Master model pulling, custom Modelfile authoring, REST API integration with curl, VRAM memory offloading, and zero-telemetry private AI pipelines.

#Ollama#LLM#AI#Llama#Qwen#DeepSeek#Local AI#DevOps#Privacy

1. Essential Ollama CLI Commands & Model Management

Ollama streamlines local Large Language Model (LLM) execution across macOS, Linux, and Windows. By packaging model weights, prompt templates, and execution parameters into unified manifests, Ollama allows developers to pull and serve cutting-edge models (such as Llama 3.3, Qwen 2.5, DeepSeek-R1, and Mistral) with single-command efficiency. All models run 100% locally on your bare-metal hardware. Zero prompts, token streams, or context embeddings are ever transmitted across external networks. The following master reference details core lifecycle CLI commands for querying, pulling, testing, and managing local model instances:
Checking Local Ollama Daemon Status and Active VRAM Offload
# Verify the local Ollama server is responding
curl -s http://127.0.0.1:11434/api/version

# List running models currently residing in GPU/CPU memory
ollama ps

# Show detailed architectural parameters and system prompt of a model
ollama show --modelfile qwen2.5:7b

Queries daemon health and inspects which neural network weights are currently resident in system VRAM.

CommandArgumentsOperational EffectPractical ExampleCopy
ollama run <model>Executes interactive CLI chat session (pulls automatically if absent)Executionollama run llama3.3:70b
ollama pull <model>Downloads model weights, quantization layers, and manifestDownloadollama pull deepseek-r1:14b
ollama listDisplays all locally cached models with file size and digest IDsInspectionollama list
ollama psLists actively loaded models with VRAM vs CPU memory offload breakdownMonitoringollama ps
ollama stop <model>Unloads a model from memory immediately, freeing GPU VRAMMemoryollama stop qwen2.5:7b
ollama rm <model>Permanently deletes cached model weights from local disk storageStorageollama rm mistral:latest
ollama cp <src> <dest>Clones an existing local model image under a new reference tagTaggingollama cp qwen2.5:7b my-code-ai
ollama show <model>Inspects model context window, parameter count, and licenseInspectionollama show --parameters llama3.2:3b

2. Custom Modelfile Engineering: Fine-Tuning Prompts & Parameters

Just as Docker uses a Dockerfile to package container environments, Ollama uses a declarative Modelfile to customize model personality, token limits, inference temperature, and response formatting. Through a Modelfile, you can: 1. Enforce strict JSON output schemas: Constrain models to return strictly valid JSON objects without preamble chatter. 2. Inject immutable system prompts: Establish security guardrails, coding style guidelines, or persona instructions. 3. Optimize context windows: Expand or restrict num_ctx (e.g., 8192 or 32768 tokens) to prevent out-of-memory crashes on systems with limited unified memory or VRAM. 4. Tune sampling temperature: Lower temperature (e.g., 0.1 to 0.2) for deterministic programming tasks, or increase it (0.7 to 0.9) for creative text generation.
Creating a Production Modelfile for a Deterministic Code Assistant
# Save the following block into a file named 'Modelfile':
cat << 'EOF' > Modelfile
FROM qwen2.5-coder:7b

# Allocate 16k context window (Requires ~6 GB unified memory / VRAM)
PARAMETER num_ctx 16384

# Low temperature for deterministic, bug-free refactoring
PARAMETER temperature 0.2

# Penalize repetition in long code generation loops
PARAMETER repeat_penalty 1.15
PARAMETER top_p 0.9

# Define strict developer system prompt
SYSTEM """
You are an expert systems engineer. You write concise, production-ready,
and memory-safe code. Always adhere to strict typing, error handling,
and clean code principles. Do not include conversational fluff.
"""
EOF

# Build and register the customized model into Ollama
ollama create code-expert -f ./Modelfile

Generates a specialized local coding model with custom context length, sampling parameters, and system constraints.

Modelfile DirectiveValue TypeDefault ValueProduction ApplicationCopy
FROM <model>Base model name or GGUF file pathRequiredSets foundation neural network weights
SYSTEM """<text>"""System instruction stringConfigurationDefines persistent personality, guardrails, and role
PARAMETER temperatureFloat (0.0 - 2.0)SamplingSet to 0.1-0.3 for code/SQL; 0.7 for general writing
PARAMETER num_ctxInteger (e.g. 4096, 8192, 32768)MemoryConfigures KV cache memory allocation in VRAM
PARAMETER top_kInteger (1 - 100)SamplingLimits next-token candidate pool (default: 40)
PARAMETER top_pFloat (0.0 - 1.0)SamplingNucleus sampling probability threshold (default: 0.9)
PARAMETER stop "<token>"String stop patternFlow ControlHalts token generation upon encountering target delimiter
TEMPLATE """<tmpl>"""Go template prompt stringFormattingCustomizes user, assistant, and system turn formatting

3. Ollama REST API Integration: Streaming & Structured JSON with curl

Ollama runs a high-performance local HTTP server on port 11434 by default. Applications written in Python, Node.js, Go, Rust, or shell scripts can communicate with local models using standard HTTP requests. The two primary endpoints are: - POST /api/chat: Structured multi-turn conversation endpoint supporting system, user, and assistant message roles. - POST /api/generate: Raw completion endpoint for single-prompt generation or document processing. Convert any of these HTTP curl commands into idiomatic programming language code instantly with our Curl to Code Converter, and format the resulting responses with our JSON Formatter & Validator.
Calling Ollama /api/chat with Non-Streaming Structured JSON Output
# Request guaranteed JSON-formatted output without streaming
curl -s http://127.0.0.1:11434/api/chat -d '{
  "model": "qwen2.5:7b",
  "messages": [
    {
      "role": "system",
      "content": "Extract data into JSON with keys: name, role, language."
    },
    {
      "role": "user",
      "content": "Alice is a DevOps engineer who specializes in Rust."
    }
  ],
  "format": "json",
  "stream": false
}' | jq .message.content

Passes format: "json" to enforce constrained decoding, returning a pristine JSON object.

Generating Text Embeddings via /api/embeddings for Vector Databases
# Generate high-dimensional vector embeddings for RAG pipelines
curl -s http://127.0.0.1:11434/api/embeddings -d '{
  "model": "nomic-embed-text",
  "prompt": "Local in-browser computing ensures complete privacy."
}' | jq '.embedding | length'

Extracts dense vector embeddings locally without sending sensitive internal knowledge to cloud embedding APIs.

API EndpointHTTP MethodPayload FocusPrimary Production Use CaseCopy
/api/chatPOSTMulti-turn conversational messages arrayChatbots, assistants, role-based workflows
/api/generatePOSTSingle prompt with streaming or batch optionsDocument summarization, classification, code review
/api/embeddingsPOSTText input string returning float arrayRetrieval-Augmented Generation (RAG), semantic search
/api/tagsGETEmpty body (queries daemon state)Dynamic model selection dropdowns in web applications
/api/showPOSTModel name payloadRetrieving model metadata, context window, and license info

4. VRAM Allocation, Quantization & Hardware Acceleration

Large Language Model inference is memory-bandwidth bound. To maximize generation throughput (measured in tokens per second), understanding how model weights map across system RAM and dedicated GPU VRAM is essential. Key hardware allocation principles: 1. Quantization: Open-weight models are typically quantized using GGUF formats (e.g. Q4_K_M, Q5_K_M, Q8_0). A 4-bit quantized model (Q4) requires approximately 0.7 GB of VRAM per billion parameters, retaining over 98% of full FP16 perplexity while quadrupling inference speed on consumer hardware. 2. GPU Layer Offloading: Ollama automatically offloads as many layers as possible to available GPU VRAM (via Apple Metal on macOS, NVIDIA CUDA on Linux/Windows, or AMD ROCm). Any remaining layers spill into slower system RAM. 3. Concurrent Model Limits: By default, Ollama unloads inactive models after 5 minutes of idle time. You can customize this with keep_alive parameters to keep models warm in VRAM for zero-latency responses.
Configuring Daemon Concurrency and Memory Retention via Environment Variables
# Linux / macOS: Configure Ollama daemon for multi-user concurrency and warm VRAM retention
export OLLAMA_NUM_PARALLEL=4          # Handle 4 parallel requests concurrently
export OLLAMA_MAX_LOADED_MODELS=2     # Retain up to 2 models resident in VRAM
export OLLAMA_KEEP_ALIVE="24h"        # Keep models loaded in memory for 24 hours
export OLLAMA_FLASH_ATTENTION=1       # Enable Flash Attention for lower VRAM overhead

# Start the Ollama server with customized parameters
ollama serve

Tunes server concurrency, prevents repetitive cold-start loading penalties, and activates Flash Attention.

Quantization LevelBits per WeightVRAM Footprint (7B Model)Perplexity & Quality RetentionCopy
Q4_K_M (Recommended)4.5 bits/weight~4.8 GB VRAMOptimal balance: >98% accuracy retention, highest speed
Q5_K_M5.5 bits/weight~5.7 GB VRAMNear-lossless accuracy: ideal for complex logic and math
Q8_08.0 bits/weight~8.2 GB VRAMIdentical to FP16 floating point: requires high VRAM headroom
FP16 (Unquantized)16.0 bits/weight~15.5 GB VRAMReference precision: rarely necessary for standard inference

5. Production Systemd Daemon & Network Hardening

When deploying Ollama on production Linux servers (such as Ubuntu 24.04 or Debian 12), the daemon should run under a dedicated unprivileged system user managed by systemd. By default, Ollama binds strictly to localhost (127.0.0.1:11434). If you need to access Ollama across a private local network (LAN) or behind an Nginx reverse proxy with TLS encryption: - Never expose port 11434 directly to the public internet without an authenticating reverse proxy (Ollama has no native authentication). - Bind to private network interfaces using OLLAMA_HOST=0.0.0.0:11434 only when protected by strict firewall rules (UFW or iptables).
Hardened Production Systemd Service Unit Override for Linux
# Open the systemd override editor for the Ollama service
sudo systemctl edit ollama.service

# Add the following configuration block:
[Service]
Environment="OLLAMA_HOST=0.0.0.0:11434"
Environment="OLLAMA_ORIGINS=https://my-internal-dashboard.example.com"
Environment="OLLAMA_FLASH_ATTENTION=1"
Environment="OLLAMA_KEEP_ALIVE=1h"
Restart=always
RestartSec=3

# Reload systemd and restart the daemon
sudo systemctl daemon-reload
sudo systemctl restart ollama

Applies persistent environment variables and automatic restart watchdogs to the production Ollama daemon.

Security SettingDefault ValueHardened RecommendationThreat MitigatedCopy
OLLAMA_HOST127.0.0.1:11434127.0.0.1:11434 (or private LAN IP)Prevents unauthorized public internet prompt injections
OLLAMA_ORIGINSAllow all (*)Explicit frontend domainMitigates Cross-Origin Resource Sharing (CORS) attacks
Reverse Proxy TLSNone (Plain HTTP)Nginx / Caddy with HTTPSPrevents plaintext eavesdropping on LAN network hops
API AuthenticationNoneBearer token via Nginx proxyRestricts model generation access to authorized API clients

๐ŸŽ“Explore More Guides

โœจ