AI operations
n8n Ollama: Connect a Self-Hosted Workflow with Strict JSON Output
Connect a self-hosted n8n workflow to local Ollama, generate a constrained JSON draft, validate it, and route uncertain results for human review.
Connect the workflow to the endpoint it can actually reach
In self-hosted automation, schema validation belongs after model generation and before any routing decision; keep it visible as its own step in the local LLM workflow.
Self-hosted n8n can orchestrate an internal workflow and call a local Ollama model, but “local” depends on where each process runs. If n8n and Ollama are on one machine, a loopback address may work. If each runs in its own Docker container, localhost inside n8n means the n8n container itself, not the Ollama container. Start by drawing the network path, then make the smallest change that lets the caller reach the model.
This example belongs to the offline LLM automation hub. It builds on the runtime comparison, the GPU planning guide and the endpoint security checklist.
What the current docs establish
n8n documents an Ollama Chat Model node and Ollama credentials. Its credential documentation says the default base URL is http://localhost:11434, and supports an optional API key for an authenticated proxy. It also describes using the Ollama container name as the host when n8n and Ollama run in separate Docker containers on a shared user-defined bridge network. Check the n8n Ollama Chat Model documentation and Ollama credentials page for your installed release.
Ollama documents a local API at http://localhost:11434, structured output through a format value (either JSON or a JSON Schema), and a default local bind address of 127.0.0.1:11434 in its FAQ and structured-output guide. Those details describe the local service; they do not prove every node in an n8n workflow has no outbound connection.
A safe starter topology
For a single-host test, run n8n and Ollama on the same controlled host and configure the credential with the URL that n8n can reach. For separate containers, create a user-defined bridge network, attach both containers to it, and use http://ollama:11434 if the Ollama container is named ollama. Follow n8n's current networking documentation for your deployment method. Avoid broad host exposure just to make a test pass.
Synthetic request source ↓ n8n workflow (fixed input fields, no action credentials) ↓ private container network Ollama API (local model, no external target chosen by model) ↓ Schema parse → deterministic checks → human review queue
Use a health check from the n8n runtime to confirm it can resolve and reach the expected service. Do not assume a URL that works from your laptop also works inside the n8n container. Conversely, if n8n is hosted remotely, localhost points at the remote n8n host or container, not the engineer's computer. Keep DNS, firewall and container network rules limited to required callers.
Define a small output schema
Start with a non-sensitive task such as labelling synthetic incidents. Make allowed values explicit. A minimal schema could look like this:
{ "type": "object", "properties": { "category": {"type": "string", "enum": ["access", "device", "network", "other"]}, "priority": {"type": "string", "enum": ["normal", "urgent", "unknown"]}, "summary": {"type": "string", "maxLength": 300}, "needs_human": {"type": "boolean"} }, "required": ["category", "priority", "summary", "needs_human"], "additionalProperties": false }
The schema is an example contract for workflow validation, not a claim that all model families enforce every JSON Schema feature the same way. Ollama's current structured-output page shows a schema passed through format and recommends validating the returned JSON in application code. In n8n, keep a parser or schema-check step after the model node and reject any output that is malformed, too long, missing a key or uses an unapproved value.
Use fixed mappings after validation. For example, the category access can send an item to a human queue labelled “Access review”; it must not cause the model to construct an API endpoint or choose an account. Keep the first test entirely read-only: store a synthetic result in a test table or output it to a reviewer, with any action node disabled.
Treat workflow input as untrusted data
Support tickets, email bodies, log messages and documents can contain instructions aimed at the model. The prompt should identify the input as data to classify, not instructions to obey. The model should not select tools, recipients, commands, URLs, file paths or the next workflow branch. The prompt-injection support-ticket guide shows a boundary pattern.
Test at least four classes: a normal synthetic request, a request with missing fields, a request that asks for an out-of-scope change, and one that contains text such as “ignore the previous instructions.” Check that the workflow either returns a valid limited result or sends the item to review. Do not interpret a model refusal or an invalid response as success. Keep the reviewer queue available when the model host is down.
Configure the credential carefully
Create an n8n credential for the Ollama endpoint and provide a base URL reachable from the n8n process. n8n's docs show an optional Bearer token field for remote authenticated proxy services. They do not say to paste a token into the node body or prompt. Store any proxy credential in n8n's approved credential store; do not put key text in workflow JSON, source control, screenshots or sample article code.
If the workflow shares the model endpoint with other applications, place it behind network controls. Ollama documents loopback binding by default and an OLLAMA_HOST override to change it. Exposing the service on another interface increases the number of possible callers. Use an authenticated proxy and TLS for remote access, restrict source networks, monitor failed requests, and verify exactly which routes can be called. If the deployment must be isolated, block outbound access and test the whole workflow, not only the generation request.
A workflow shape that is easy to review
- Trigger from a synthetic test input or a fixed internal test queue.
- Set a maximum input length and remove fields the model does not need.
- Pass the prompt and content as separate, labelled data fields.
- Ask the model for the fixed JSON schema, with no action instructions.
- Parse the output and check type, length and allowlisted values.
- If any check fails or the output is uncertain, route it to a human queue.
- Display source, category, short summary and “model draft” label to the reviewer.
- Keep action nodes disabled until the owner has approved a separate design.
For retry handling, make the model call idempotent at the workflow level: use a stable test-item identifier and avoid creating duplicate review records on an automatic retry. Record model name, version, prompt version, workflow version, validation status and elapsed time. Avoid recording raw input content unless a documented purpose requires it. If sample prompts contain sensitive information, the Log Secret Redactor is a lightweight screen, but pattern matching can miss secrets.
Test failure paths before enabling a trigger
Disconnect the model service and confirm n8n leaves the item visible for manual handling. Return invalid JSON, missing keys, a string that exceeds the limit, a wrong enum and a malicious-looking instruction. Test duplicate deliveries and a workflow restart halfway through. Verify that no action runs and that the reviewer sees a useful explanation. When the model becomes reachable again, allow an operator to reprocess an item rather than automatically replaying all failed actions.
If you update n8n or Ollama, replay the test set. Connector node versions, credential fields and schema handling may change. Pin the version during a pilot, retain a known-good configuration export without credentials, and document who owns updates. The AI prompt debugger can help iterate on non-sensitive prompt wording; do not paste real incidents into it without checking its data-handling terms.
What “offline” means here
An offline inference process can still be surrounded by services that require network access. n8n itself may have webhook, identity, update, backup or connector traffic. Model files may have been downloaded earlier. A final destination such as a SaaS ticketing service will receive data by design. Review every workflow node and its credential before using sensitive material. If no network path is allowed, disable connectors that are not part of the approved offline path and test with egress blocked.
Map nodes to trust boundaries
Keep the workflow readable enough for an operator to review. Use separate steps for input validation, minimisation, model request, JSON parsing, deterministic checks and human review. Label the model result as a draft. Keep consequential actions disabled until an approved design defines identity, permissions, duplicate handling, audit and rollback.
Before the model node, reject empty input and cap text length. Remove fields the classifier does not need. Pass content in a clearly named data field and keep fixed instructions in the prompt template. Do not concatenate user-controlled text into a field that becomes workflow configuration.
Parse and check the result
Use the output property documented by the current n8n node or inspect a representative synthetic execution in the installed version. Do not copy an expression from an older tutorial without checking its actual output object. After parsing, verify required keys, types, allowed values and maximum lengths. Convert invalid output into a review state rather than attempting an unconstrained repair call.
If a schema returns a category, route only through a fixed list such as access, device, network and other. A model-provided URL, account name or command must not become the target of an HTTP or shell node. Keep target selection in trusted workflow logic.
Test idempotency and outages
Send the same synthetic item twice and verify that a retry does not create duplicate review records. Stop Ollama mid-request and check the resulting execution state. Restart n8n part-way through and confirm an item is not lost or automatically sent to an action. Decide which failures can be retried and which need an operator to reconcile first.
Bound concurrency to what the host has measured. If the queue grows, return a visible delayed or unavailable state rather than accepting unlimited work. Record workflow and model version, elapsed time, schema result and reviewer decision. Avoid raw input logging by default and set an approved retention period for execution data.
Check the container boundary
From inside the n8n container, verify DNS and connectivity to Ollama on the shared user-defined bridge network. Confirm the host is the intended container name and unrelated containers cannot reach the model port. Check host port mappings; if no host access is needed, do not publish the port broadly. Test again after container restart or network changes.
If n8n and Ollama are on different machines, localhost in the n8n credential points to the n8n machine, not the model host. Use an approved private route with authentication and TLS, restricted to the n8n caller. The n8n credential supports an optional API key for an authenticated proxy; store it in the credential manager, not workflow JSON or a prompt.
The safest first result is a validated draft that changes nothing. Add an action only after the organisation has defined an approver, target-resolution rule, permission boundary, audit record and rollback. OpsPilot is read-only Microsoft 365 review software; it does not configure n8n, run Ollama or execute an action in a tenant.
*Official documentation checked on 24 November 2026: n8n Ollama Chat Model and credential pages, Ollama structured outputs and local FAQ. Confirm exact node labels and network behaviour in the versions you operate.*
Frequently asked questions
Which n8n node connects to Ollama?
The n8n documentation lists an Ollama Chat Model node and an Ollama credential. Check the current node version and credential fields in your installed n8n release before following a tutorial.
Should I use localhost from an n8n Docker container?
Not if Ollama runs in a different container. The n8n docs recommend a shared user-defined Docker bridge network and the Ollama container name as the host. Test the actual network path.
Does JSON mode make the model output safe?
No. It can constrain format but not truth or authorisation. Parse the response, validate types and allowed values, and require human approval before any consequential action.
Does a self-hosted n8n plus Ollama workflow guarantee no cloud traffic?
No. Review credentials, nodes, telemetry, model downloads, backups and destinations. Test egress and disable unused external nodes or connections under your change process.
What should I log?
Capture run status, model and workflow version, validation outcome and approval decision. Minimise or redact raw prompts and personal data, and define a retention period for troubleshooting records.