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.
1. Essential Ollama CLI Commands & Model Management
# 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:7bQueries daemon health and inspects which neural network weights are currently resident in system VRAM.
| Command | Arguments | Operational Effect | Practical Example | Copy |
|---|---|---|---|---|
| ollama run <model> | Executes interactive CLI chat session (pulls automatically if absent) | Execution | ollama run llama3.3:70b | |
| ollama pull <model> | Downloads model weights, quantization layers, and manifest | Download | ollama pull deepseek-r1:14b | |
| ollama list | Displays all locally cached models with file size and digest IDs | Inspection | ollama list | |
| ollama ps | Lists actively loaded models with VRAM vs CPU memory offload breakdown | Monitoring | ollama ps | |
| ollama stop <model> | Unloads a model from memory immediately, freeing GPU VRAM | Memory | ollama stop qwen2.5:7b | |
| ollama rm <model> | Permanently deletes cached model weights from local disk storage | Storage | ollama rm mistral:latest | |
| ollama cp <src> <dest> | Clones an existing local model image under a new reference tag | Tagging | ollama cp qwen2.5:7b my-code-ai | |
| ollama show <model> | Inspects model context window, parameter count, and license | Inspection | ollama show --parameters llama3.2:3b |
2. Custom Modelfile Engineering: Fine-Tuning Prompts & Parameters
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.# 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 ./ModelfileGenerates a specialized local coding model with custom context length, sampling parameters, and system constraints.
| Modelfile Directive | Value Type | Default Value | Production Application | Copy |
|---|---|---|---|---|
| FROM <model> | Base model name or GGUF file path | Required | Sets foundation neural network weights | |
| SYSTEM """<text>""" | System instruction string | Configuration | Defines persistent personality, guardrails, and role | |
| PARAMETER temperature | Float (0.0 - 2.0) | Sampling | Set to 0.1-0.3 for code/SQL; 0.7 for general writing | |
| PARAMETER num_ctx | Integer (e.g. 4096, 8192, 32768) | Memory | Configures KV cache memory allocation in VRAM | |
| PARAMETER top_k | Integer (1 - 100) | Sampling | Limits next-token candidate pool (default: 40) | |
| PARAMETER top_p | Float (0.0 - 1.0) | Sampling | Nucleus sampling probability threshold (default: 0.9) | |
| PARAMETER stop "<token>" | String stop pattern | Flow Control | Halts token generation upon encountering target delimiter | |
| TEMPLATE """<tmpl>""" | Go template prompt string | Formatting | Customizes user, assistant, and system turn formatting |
3. Ollama REST API Integration: Streaming & Structured JSON with curl
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.# 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.contentPasses format: "json" to enforce constrained decoding, returning a pristine JSON object.
# 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 Endpoint | HTTP Method | Payload Focus | Primary Production Use Case | Copy |
|---|---|---|---|---|
| /api/chat | POST | Multi-turn conversational messages array | Chatbots, assistants, role-based workflows | |
| /api/generate | POST | Single prompt with streaming or batch options | Document summarization, classification, code review | |
| /api/embeddings | POST | Text input string returning float array | Retrieval-Augmented Generation (RAG), semantic search | |
| /api/tags | GET | Empty body (queries daemon state) | Dynamic model selection dropdowns in web applications | |
| /api/show | POST | Model name payload | Retrieving model metadata, context window, and license info |
4. VRAM Allocation, Quantization & Hardware Acceleration
keep_alive parameters to keep models warm in VRAM for zero-latency responses.# 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 serveTunes server concurrency, prevents repetitive cold-start loading penalties, and activates Flash Attention.
| Quantization Level | Bits per Weight | VRAM Footprint (7B Model) | Perplexity & Quality Retention | Copy |
|---|---|---|---|---|
| Q4_K_M (Recommended) | 4.5 bits/weight | ~4.8 GB VRAM | Optimal balance: >98% accuracy retention, highest speed | |
| Q5_K_M | 5.5 bits/weight | ~5.7 GB VRAM | Near-lossless accuracy: ideal for complex logic and math | |
| Q8_0 | 8.0 bits/weight | ~8.2 GB VRAM | Identical to FP16 floating point: requires high VRAM headroom | |
| FP16 (Unquantized) | 16.0 bits/weight | ~15.5 GB VRAM | Reference precision: rarely necessary for standard inference |
5. Production Systemd Daemon & Network Hardening
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).# 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 ollamaApplies persistent environment variables and automatic restart watchdogs to the production Ollama daemon.
| Security Setting | Default Value | Hardened Recommendation | Threat Mitigated | Copy |
|---|---|---|---|---|
| OLLAMA_HOST | 127.0.0.1:11434 | 127.0.0.1:11434 (or private LAN IP) | Prevents unauthorized public internet prompt injections | |
| OLLAMA_ORIGINS | Allow all (*) | Explicit frontend domain | Mitigates Cross-Origin Resource Sharing (CORS) attacks | |
| Reverse Proxy TLS | None (Plain HTTP) | Nginx / Caddy with HTTPS | Prevents plaintext eavesdropping on LAN network hops | |
| API Authentication | None | Bearer token via Nginx proxy | Restricts model generation access to authorized API clients |
Related Free Online Tools
Put these techniques into practice immediately with our privacy-first browser utilities:
Convert Ollama REST API curl invocations into production Python, Node.js, Go, or Rust code.
Inspect, validate, and beautify structured JSON output schemas returned by Ollama API endpoints.
Build and test extraction regex patterns for parsing raw LLM tokens, stop sequences, and outputs.