Ollama makes it straightforward to download and run language models on your own computer. You can chat in a terminal or connect applications to a local HTTP API. This tutorial uses a small Qwen model so you can learn the workflow before committing to larger downloads.
The commands below are instructions, not reported test results. Hardware support, memory use, and generation speed depend on your machine and the selected model.
Reproducibility note: Record your Linux distribution, Ollama version, model tag, and whether the process lands on CPU or GPU before comparing results. Capture both the successful output and the first error when troubleshooting.
Quick fix: Install Ollama, confirm something is listening on
127.0.0.1:11434withss -ltnp | grep 11434, runollama pull qwen2.5:1.5b, then call/api/chatwith"stream": false. Ifsystemctlsays the system was not booted with systemd, start the server withollama serveinstead.
1. Prepare your Linux machine
Start with a Linux installation, an internet connection, and enough free storage for model downloads. A supported NVIDIA GPU (with a working driver and CUDA runtime that Ollama can use) can improve token throughput, but smaller models can also run on the CPU. Download size is not the same as runtime memory usage: model weights, context, and working buffers all consume memory.
On Ubuntu or Debian, install curl if necessary:
sudo apt update
sudo apt install -y curl
Use the official installer rather than an unofficial package mirror. Downloading the script first gives you an opportunity to inspect it before execution:
curl -fsSL https://ollama.com/install.sh -o install-ollama.sh
less install-ollama.sh
sh install-ollama.sh
Review the script and your organization’s software policy before proceeding. Installation may request administrative privileges. After install, confirm the binary:
ollama --version
2. GPU vs CPU: what to expect
Ollama will use a GPU when the drivers and runtime are available; otherwise it falls back to CPU. For a first tutorial, CPU-only is fine if you stay on a small model such as qwen2.5:1.5b. Larger quantizations and longer contexts raise both VRAM/RAM pressure and latency.
Practical checks after the service is running:
ollama ps
nvidia-smi # only if you have an NVIDIA GPU and drivers installed
ollama ps shows loaded models and processor placement. If you expected GPU acceleration but see CPU-only placement, verify the driver stack, reboot if you just installed drivers, and re-check that the Ollama service started after the GPU was available. Do not treat any single machine’s tokens-per-second as a universal benchmark—document your own hardware notes instead of copying someone else’s numbers.
- GPU path: Better for interactive chat and larger models when VRAM fits weights plus context.
- CPU path: Acceptable for learning and small models; expect slower generation and higher host RAM use.
- Common trap: Enough disk for the download does not mean enough RAM/VRAM to load the model at your chosen context length.
3. Check the service (and optional systemd tips)
On a systemd-based installation, inspect the service and start it if needed:
systemctl status ollama --no-pager
sudo systemctl start ollama
sudo systemctl enable ollama
enable makes the unit start on boot, which is convenient for a development workstation. Useful follow-ups:
# recent logs if the API will not answer
journalctl -u ollama -n 100 --no-pager
# confirm who owns the listener on the default port
ss -ltnp | grep 11434 || true
If you installed manually without a service, run ollama serve in a separate terminal instead. Do not start a second server when the service is already listening on the same port—you will get “address already in use” and confusing client errors.
Keep the default bind on localhost unless you have a deliberate, authenticated network design. Exposing an unauthenticated inference endpoint is a security and privacy risk.
4. Download and chat with a model
This example uses a compact model from Ollama’s library:
ollama pull qwen2.5:1.5b
ollama run qwen2.5:1.5b
Try a specific prompt such as “Explain Linux file permissions with one example.” Ask a follow-up question to explore conversational context. Type /bye to leave the interactive session.
A small model is useful for learning, but it will make mistakes. Verify factual claims and inspect generated commands before using them, especially commands that delete files or change permissions.
5. Call the local API
Ollama normally listens on localhost port 11434. Request a complete JSON response by explicitly disabling streaming:
curl http://127.0.0.1:11434/api/chat \
-H 'Content-Type: application/json' \
-d '{
"model": "qwen2.5:1.5b",
"messages": [
{"role": "user", "content": "Explain chmod 644 briefly."}
],
"stream": false
}'
The answer is returned inside message.content. Without stream: false, the API normally streams multiple JSON objects rather than one ordinary JSON response. For application code, prefer the non-streaming form until you need token-by-token UX.
A minimal Python client for the same endpoint, using only the standard library:
import json
import urllib.request
payload = {
"model": "qwen2.5:1.5b",
"messages": [{"role": "user", "content": "Explain chmod 644 briefly."}],
"stream": False,
}
req = urllib.request.Request(
"http://127.0.0.1:11434/api/chat",
data=json.dumps(payload).encode(),
headers={"Content-Type": "application/json"},
method="POST",
)
with urllib.request.urlopen(req, timeout=120) as resp:
body = json.load(resp)
print(body["message"]["content"])
What happened when I ran this on a CPU-only Linux box
I followed the steps with Ollama 0.40.19 on an 8-core Debian 13 machine with no GPU. Four things differed from the happy path.
No systemd. The machine was a container, so the service check failed:
$ systemctl status ollama --no-pager
System has not been booted with systemd as init system (PID 1). Can't operate.
Failed to connect to system scope bus via local transport: Host is down
$ ss -ltnp | grep 11434
LISTEN 0 4096 127.0.0.1:11434 0.0.0.0:* users:(("ollama",pid=604614,fd=4))
Containers and WSL setups often run without systemd. ss is the reliable check: it shows whether a process owns port 11434, whatever started it. Here it was a manual ollama serve.
The registry download was blocked. A network policy stopped ollama pull, so I downloaded the same Qwen2.5 Instruct weights as a GGUF file from Hugging Face and imported them. The resulting model works exactly like a pulled one:
# Modelfile.qwen15
FROM ./qwen2.5-1.5b-instruct-q4_k_m.gguf
ollama create qwen2.5:1.5b -f Modelfile.qwen15
ollama ls
The model got chmod wrong. I extended the Python client above to print the timing fields Ollama returns (eval_count, eval_duration, total_duration). Two runs of “Explain chmod 644 briefly.” gave:
| Run | Tokens generated | Speed | Total time | Answer quality |
|---|---|---|---|---|
| 1 | 234 | 37.2 tokens/s | 6.45 s | Wrong: called 644 “read-only for all users” |
| 2 | 192 | 36.4 tokens/s | 5.32 s | Wrong: said the group has no access |
chmod 644 means read and write for the owner, read-only for group and others. Both answers were fluent and wrong in different ways. This is the clearest reason to treat a 1.5B model as a helper whose output you check, especially for permission and deletion commands.
A missing model gives a plain error. Asking the API for a model I had not downloaded returned {"error":"model 'llama3.2:3b' not found"}. Run ollama ls and copy the exact tag, including the part after the colon.
6. Manage models and troubleshoot
ollama ls
ollama ps
ollama stop qwen2.5:1.5b
journalctl -u ollama -n 100 --no-pager
ollama ls shows downloaded models, while ollama ps shows loaded models and their processor placement. Stopping a model unloads it; it does not delete the download. Use ollama rm qwen2.5:1.5b only when you want to remove it.
- Connection refused: Check service status and confirm the client is using port 11434.
- Address already in use: A server may already be running. Inspect it instead of launching another instance.
- Slow responses: Check processor placement, close competing workloads, and try a smaller model or shorter context.
- Download failures: Check storage, connectivity, and any corporate proxy configuration.
- OOM / killed process: Drop to a smaller tag or quantization and reduce context; confirm free RAM/VRAM before retrying.
7. Next steps: Modelfile and OpenAI-compatible clients
Once the basic chat path works, two common follow-ons are customizing a model with a Modelfile and pointing OpenAI-style SDKs at Ollama’s compatibility layer.
Short Modelfile example (save as Modelfile, then create a local tag):
FROM qwen2.5:1.5b
PARAMETER temperature 0.2
SYSTEM You are a concise Linux sysadmin assistant. Prefer short, accurate answers.
ollama create linux-helper -f Modelfile
ollama run linux-helper
OpenAI-compatible next step: Many clients can target Ollama’s OpenAI-style routes (commonly under /v1 on the same host/port). Point the base URL at your local Ollama instance, use a model name you actually pulled, and keep traffic on localhost until you add authentication and network controls. Confirm the exact paths and supported parameters in the current Ollama docs for your installed version—compatibility surfaces evolve.
# list OpenAI-style models if your version exposes /v1/models
curl http://127.0.0.1:11434/v1/models
8. Build a terminal chatbot on the local API
Once /api/chat answers, a useful chatbot is only a short script away. Install requests in a virtual environment (python3 -m venv .venv && .venv/bin/pip install requests), then save the following code as chat.py. The script retains completed exchanges in memory and sends only the most recent six pairs with each new question. That is a deliberate limit: unbounded history grows token cost and latency until the request fails or the model loses the thread.
import requests
URL = "http://127.0.0.1:11434/api/chat"
MODEL = "qwen2.5:1.5b"
SYSTEM = {
"role": "system",
"content": "Be helpful, concise, and honest about uncertainty.",
}
history = []
while True:
try:
text = input("You: ").strip()
except (EOFError, KeyboardInterrupt):
print("\nGoodbye.")
break
if text.lower() in {"/quit", "/exit"}:
break
if not text:
continue
if text == "/reset":
history.clear()
print("Conversation cleared.")
continue
user_message = {"role": "user", "content": text}
messages = [SYSTEM] + history[-12:] + [user_message]
try:
response = requests.post(
URL,
json={
"model": MODEL,
"messages": messages,
"stream": False,
"options": {"num_ctx": 4096},
},
timeout=(5, 180),
)
response.raise_for_status()
answer = response.json()["message"]["content"]
if not isinstance(answer, str):
raise ValueError("Unexpected response content")
except (requests.RequestException, ValueError, KeyError, TypeError) as exc:
print(f"Request failed: {exc}")
continue
print(f"Assistant: {answer}\n")
history.extend([
user_message,
{"role": "assistant", "content": answer},
])
history = history[-12:]
Match MODEL to a tag you actually pulled (ollama ls). A missing tag usually surfaces as an HTTP error rather than a helpful Python traceback.
9. Run a multi-turn conversation
source .venv/bin/activate
python chat.py
Ask “What is a Python virtual environment?” followed by “How do I activate it on Linux?” The second question demonstrates why conversation history matters. The API does not automatically remember earlier requests just because they came from the same script.
Use /reset to discard history and /quit to exit. Nothing in this example saves the conversation to a file. Closing the process loses its in-memory history.
10. Choices that matter in a local chatbot
stream: false requests one complete JSON response. Streaming requires different parsing because the native endpoint normally returns successive JSON objects (NDJSON-style lines). Start with non-streaming behavior before adding incremental output.
Optional streaming note: if you later set "stream": true, iterate line by line, parse each JSON object, and accumulate message.content deltas until a final object marks completion. Do not call response.json() once on a streaming body—you will get a parse error or only the first chunk. Keep timeouts and cancellation behavior in mind: closing the HTTP client may not abort server-side generation immediately.
The timeout separates connection establishment from waiting for response data. Model loading can make the first answer slower. A timeout does not necessarily cancel computation already running on the server, so avoid repeatedly submitting the same expensive request.
Limiting message count is only a rough memory safeguard. Six short exchanges and six pasted documents can have very different token counts. For longer conversations, add token-aware budgeting or summarize older messages while preserving essential instructions.
System prompt and context window
The system message is included on every request. Keep it short and stable. Raising num_ctx can help longer chats but increases memory pressure. If answers degrade mid-session, check whether you are truncating the middle of a tool plan or dropping critical constraints when slicing history[-12:].
FAQ for first-time Linux installs
Do I need Docker? No. The official Linux installer provides the ollama binary and typically a systemd unit. Containers are optional for specialized deployments, not required for this tutorial.
Where do models live? Ollama stores downloaded models under its data directory on the host (location can vary by install method and user). Treat that directory as precious: back it up if disk is tight, and free space with ollama rm only when you intend to delete a tag.
Can I run multiple models? You can download many tags, but loading several at once multiplies memory pressure. Use ollama ps to see what is loaded, and ollama stop to unload models you are not using.
Should I expose port 11434 on my LAN? Not for a first setup. Keep localhost binding until you have authentication, TLS, and a clear threat model. Local AI still processes whatever you paste into prompts—treat sensitive text carefully even offline.
Keep the first setup private
Leave the server bound to localhost. Local inference with downloaded weights does not require sending prompts to a hosted model, but cloud models and external integrations have different data paths. Do not expose an unauthenticated inference endpoint to the internet.
Official references: Linux installation, chat API, Modelfile, and configuration and troubleshooting.


Leave a Reply