
Most automation stacks fail for one boring reason: they can’t call an LLM reliably. They leak data. Or they break after an update.
This tutorial shows how to run n8n with Ollama on a VPS using Docker Compose, persistent volumes, and a production-friendly webhook + TLS setup.
You’ll end up with a workflow runner you control. You’ll also get a local LLM endpoint. Your support and DevOps automations can call it over a private network.
This guide assumes you’re comfortable with SSH and editing config files. The target host is Ubuntu Server on a real VPS.
If you don’t have one yet, a HostMyCode VPS fits this stack well. Size RAM/CPU and storage to match your model and automation load.
What you’ll build (and what it can’t do)
You’ll run:
- n8n for workflows and webhooks
- Ollama for local model inference via HTTP
- Nginx as a reverse proxy for TLS and hardened access
This setup shines at practical operator work. Think: summarizing tickets, drafting replies, labeling logs, generating runbooks, transforming JSON, and other “glue” tasks.
What it won’t do well on a CPU-only VPS: high-throughput chat, long-context RAG pipelines, or image generation. You can still build a lot. Plan around latency and limited concurrency.
Resource sizing for Ollama + n8n (CPU, RAM, disk)
Memory is usually the limiting factor. Budget for the model and overhead, not just the download size.
- Small CPU-only starter: 4 vCPU, 16 GB RAM, 80+ GB NVMe. Fine for smaller quantized models, low concurrency, and background workflows.
- Comfortable CPU-only: 8 vCPU, 32 GB RAM, 160+ GB NVMe. Better headroom for larger quantized models and multi-step runs.
- GPU recommended (optional): If you need interactive response times for multiple users, use a GPU box. In that case, evaluate a dedicated server or a larger managed plan.
Disk adds up quickly once you start pulling models and accumulating Docker layers. Keep /var/lib/docker on storage with room to grow.
Also store n8n state in a named volume. That way, container updates don’t wipe credentials.
Quantization note: lower-bit quantization cuts RAM/VRAM needs and speeds downloads. It can also reduce reasoning quality.
If you want to tune that tradeoff, see Quantize Llama models for Ollama on a VPS.
Prerequisites on your VPS
- Ubuntu Server (LTS is fine)
- A domain or subdomain (recommended) pointing to your server
- Docker + Docker Compose plugin
If DNS isn’t in place yet, do that first. It makes TLS issuance painless. HostMyCode domains are here: domains.
Step 1: Prepare the server (Docker, firewall, directories)
SSH into your VPS and update packages:
sudo apt update
sudo apt -y upgrade
Install Docker Engine and the Compose plugin. Using the Docker repo packages is a safe default:
sudo apt -y install ca-certificates curl gnupg
sudo install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg
sudo chmod a+r /etc/apt/keyrings/docker.gpg
echo \
"deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu \
$(. /etc/os-release && echo $VERSION_CODENAME) stable" | \
sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
sudo apt update
sudo apt -y install docker-ce docker-ce-cli containerd.io docker-compose-plugin
Enable Docker and allow your user to run Docker commands:
sudo systemctl enable --now docker
sudo usermod -aG docker $USER
newgrp docker
Create a working directory:
mkdir -p ~/n8n-ollama/{nginx,workflows}
cd ~/n8n-ollama
Firewall basics (SSH + HTTP/HTTPS):
sudo apt -y install ufw
sudo ufw allow OpenSSH
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw enable
If you want better protection against SSH and Nginx brute-force attempts, add Fail2ban.
This tutorial maps cleanly to typical n8n endpoints: Set up Fail2ban for Nginx on Ubuntu VPS.
Step 2: Write a Docker Compose file for n8n + Ollama
This Compose file runs three services:
- ollama: listens on an internal Docker network (not exposed publicly)
- n8n: the workflow engine, reachable only via Nginx
- nginx: reverse proxy with TLS termination
Create docker-compose.yml:
cd ~/n8n-ollama
nano docker-compose.yml
services:
ollama:
image: ollama/ollama:latest
container_name: ollama
restart: unless-stopped
volumes:
- ollama:/root/.ollama
networks:
- internal
n8n:
image: n8nio/n8n:latest
container_name: n8n
restart: unless-stopped
environment:
- TZ=UTC
- N8N_HOST=n8n.example.com
- N8N_PORT=5678
- N8N_PROTOCOL=https
- WEBHOOK_URL=https://n8n.example.com/
- N8N_EDITOR_BASE_URL=https://n8n.example.com/
- N8N_ENCRYPTION_KEY=REPLACE_WITH_A_32+_CHAR_RANDOM_SECRET
- N8N_SECURE_COOKIE=true
- N8N_DIAGNOSTICS_ENABLED=false
- N8N_PERSONALIZATION_ENABLED=false
- N8N_USER_MANAGEMENT_DISABLED=false
- N8N_TEMPLATES_ENABLED=false
- N8N_LOG_LEVEL=info
- N8N_LOG_OUTPUT=console
- NODE_FUNCTION_ALLOW_BUILTIN=*
- NODE_FUNCTION_ALLOW_EXTERNAL=axios,lodash
volumes:
- n8n_data:/home/node/.n8n
networks:
- internal
nginx:
image: nginx:stable
container_name: n8n-nginx
restart: unless-stopped
ports:
- "80:80"
- "443:443"
volumes:
- ./nginx/conf.d:/etc/nginx/conf.d:ro
- ./nginx/ssl:/etc/nginx/ssl:ro
- ./nginx/www:/var/www/certbot:ro
depends_on:
- n8n
networks:
- internal
volumes:
n8n_data:
ollama:
networks:
internal:
driver: bridge
Important: replace n8n.example.com with your real hostname.
Generate a strong encryption key and save it somewhere safe:
openssl rand -base64 48
Paste the output into N8N_ENCRYPTION_KEY. n8n uses this to encrypt stored credentials inside the volume.
If you lose the key later, you may not be able to decrypt existing credentials.
Step 3: Add Nginx reverse proxy config (TLS-ready)
Create Nginx config directories:
mkdir -p ~/n8n-ollama/nginx/{conf.d,ssl,www}
Create ~/n8n-ollama/nginx/conf.d/n8n.conf:
nano ~/n8n-ollama/nginx/conf.d/n8n.conf
server {
listen 80;
server_name n8n.example.com;
location /.well-known/acme-challenge/ {
root /var/www/certbot;
}
location / {
return 301 https://$host$request_uri;
}
}
server {
listen 443 ssl http2;
server_name n8n.example.com;
ssl_certificate /etc/nginx/ssl/fullchain.pem;
ssl_certificate_key /etc/nginx/ssl/privkey.pem;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
ssl_protocols TLSv1.2 TLSv1.3;
client_max_body_size 25m;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
location / {
proxy_pass http://n8n:5678;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 3600;
}
}
This config expects fullchain.pem and privkey.pem in ~/n8n-ollama/nginx/ssl/. Next, you’ll issue a certificate.
Step 4: Get a Let’s Encrypt certificate (simple certbot container)
We’ll use a short-lived certbot container with the webroot challenge. Certbot needs plain HTTP access to the challenge path.
To make that work, bring up Nginx without the 443 block first. The easiest approach is:
- Start with only the port 80 server block
- Get the cert
- Add the 443 block back in
Edit n8n.conf and remove (or comment) the entire 443 block. Then start the stack:
cd ~/n8n-ollama
docker compose up -d
Verify Nginx is answering over HTTP:
curl -I http://n8n.example.com
Run certbot (replace email + domain):
docker run --rm \
-v ~/n8n-ollama/nginx/www:/var/www/certbot \
-v ~/n8n-ollama/nginx/ssl:/etc/letsencrypt \
certbot/certbot certonly \
--webroot -w /var/www/certbot \
-d n8n.example.com \
--email you@example.com \
--agree-tos --no-eff-email
Certbot stores certificates under /etc/letsencrypt/live/.... Copy (or symlink) them into the filenames your Nginx config references:
sudo cp ~/n8n-ollama/nginx/ssl/live/n8n.example.com/fullchain.pem ~/n8n-ollama/nginx/ssl/fullchain.pem
sudo cp ~/n8n-ollama/nginx/ssl/live/n8n.example.com/privkey.pem ~/n8n-ollama/nginx/ssl/privkey.pem
sudo chmod 600 ~/n8n-ollama/nginx/ssl/privkey.pem
Re-edit n8n.conf and restore the 443 server block. Then reload:
docker compose restart nginx
If you prefer wildcard certs or DNS-based validation, follow this guide: Add Let’s Encrypt wildcard SSL with Caddy and DNS. The certificate workflow is the same even if you stick with Nginx.
Step 5: Pull a model in Ollama (and verify local-only access)
Ollama stays on the internal Docker network in this layout. That’s the point. n8n can reach it, and the public internet can’t.
Pull a model from inside the container:
docker exec -it ollama ollama pull llama3
If you want faster CPU inference, start smaller. Either way, you can list installed models like this:
docker exec -it ollama ollama list
Verify the exposure is correct:
curl http://YOUR_SERVER_IP:11434should fail (connection refused / no route).docker exec -it n8n curl -s http://ollama:11434/api/tagsshould return JSON.
If port 11434 answers from the internet, you published it by mistake. Remove any ports: mapping from the Ollama service and restart.
Step 6: Create your first “Support Triage” workflow in n8n
Open https://n8n.example.com and create your admin user. Then build a small workflow:
- accept a webhook
- call Ollama
- return structured JSON to a helpdesk or internal tool
- Webhook node
- HTTP Method: POST
- Path: support/triage
- Response mode: Last node
- Set node (normalize fields)
- Create fields:
subject,body,customer_email - Map them from the webhook JSON
- Create fields:
- HTTP Request node (call Ollama)
- Method: POST
- URL:
http://ollama:11434/api/generate - Send Body: JSON
- JSON Body (example):
{ "model": "llama3", "prompt": "You are a support triage assistant.\n\nReturn JSON with keys: category, urgency, summary, suggested_reply.\n\nTicket subject: {{$json.subject}}\nTicket body: {{$json.body}}\n", "stream": false } - Code node (parse and harden output)
Models sometimes wrap JSON in extra text. Use a Code node to extract JSON defensively.
const text = $json.response || ''; // Try direct parse first try { const obj = JSON.parse(text); return [{ json: obj }]; } catch (e) { // Fallback: find first { ... } block const start = text.indexOf('{'); const end = text.lastIndexOf('}'); if (start !== -1 && end !== -1 && end > start) { const candidate = text.slice(start, end + 1); const obj = JSON.parse(candidate); return [{ json: obj }]; } return [{ json: { error: 'Model did not return JSON', raw: text } }]; } - Respond to Webhook node
- Response Body: JSON
- Body:
{{$json}}
Test the webhook from your laptop:
curl -s https://n8n.example.com/webhook/support/triage \
-H 'Content-Type: application/json' \
-d '{
"subject":"Site is down after plugin update",
"body":"We updated a plugin and now we get a 500 error. Can you help?"
}' | jq
If you hit a timeout, go straight to the logs:
docker logs -f n8n
Keep expectations realistic. If Ollama is slow on CPU, the webhook will be slow too. The usual fixes are a smaller model, more RAM, or a GPU-backed host.
Step 7: Run automations safely (credentials, secrets, and least privilege)
n8n makes credential storage convenient. Treat that as production infrastructure, not a sandbox.
- Use n8n credentials, not hard-coded secrets inside nodes. Keep secrets out of workflow JSON exports.
- Limit who can reach the UI. Use TLS, enforce strong passwords, and add SSO for teams.
- Use dedicated automation tokens (Zendesk, GitHub, etc.), not personal tokens. Scope permissions to the minimum needed.
If you need OAuth and access control in front of the editor, reuse a proven pattern instead of building your own.
This walkthrough is a good template for n8n too: Open WebUI with OAuth2 Proxy on a VPS.
Step 8: Make webhooks production-safe (auth, rate limits, replay protection)
Public webhook endpoints get scanned. Assume bots will find yours. Then build accordingly.
Option A (simple): add a shared secret header
Require a header like X-Automation-Secret. In n8n, add an IF node right after the Webhook node:
- Condition:
{{$json.headers["x-automation-secret"]}}equals your secret
Or validate in a Code node and return early.
Option B (stronger): restrict by IP at Nginx
If only your app servers call the webhook, allowlist their IPs at Nginx. Add this inside the TLS server block:
location /webhook/ {
allow 203.0.113.10;
allow 198.51.100.25;
deny all;
proxy_pass http://n8n:5678;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
This one change eliminates most drive-by abuse.
Step 9: Call Ollama from n8n cleanly (prompts, JSON schemas, and timeouts)
Three habits prevent most workflow failures:
- Set
stream:falsefor automation calls unless you truly need streaming. - Demand a strict output format (specific JSON keys) and validate it in a Code node.
- Keep prompts short. On CPU inference, long prompts cost you twice: longer prefill and longer output.
If your automation needs deeper context (docs, KB, runbooks), you’re moving into retrieval-augmented generation. Keep that separate from this core stack. Then add a vector database such as Qdrant.
This is a solid starting point: Host Qdrant on a VPS for RAG search with Docker.
Step 10: Backups and updates without breaking workflows
n8n state lives in the n8n_data volume. Back it up.
Don’t bet your workflows on “we can just redeploy.”
Quick backup command (volume export)
mkdir -p ~/backups
docker run --rm \
-v n8n-ollama_n8n_data:/data \
-v ~/backups:/backup \
ubuntu bash -c "cd /data && tar czf /backup/n8n_data-$(date +%F).tar.gz ."
Also back up your Compose file and Nginx config:
tar czf ~/backups/n8n-ollama-config-$(date +%F).tar.gz -C ~/n8n-ollama docker-compose.yml nginx
Updates: use controlled pulls
Update containers with a pull + recreate:
cd ~/n8n-ollama
docker compose pull
docker compose up -d
If you want automated image updates, Watchtower can work well. Only use it if you respect backups and maintenance windows. See: Docker Compose auto-updates with Watchtower on a VPS.
After updates, do a quick sanity check:
docker psshows all services healthy- n8n UI loads and webhooks respond
docker exec -it n8n curl -s http://ollama:11434/api/tagsstill works
Troubleshooting: common failure modes and quick fixes
n8n webhooks return 404
- Confirm
WEBHOOK_URLmatches your external URL exactly (https, hostname, trailing slash). - Confirm you’re calling the right path: n8n uses
/webhook/...for production webhooks.
Ollama calls from n8n time out
- Pick a smaller model or reduce output length.
- Add RAM. CPU inference swaps under pressure and becomes unusable.
- Check container logs:
docker logs -f ollama.
Disk usage grows fast
Models, logs, and Docker layers pile up. Start by checking what’s consuming space:
docker system df
sudo du -sh /var/lib/docker/* 2>/dev/null | sort -h
If you want a careful cleanup playbook for low-disk situations, use: Disk full on VPS: find large files and free space safely.
Summary: a practical “operator AI” stack you control
You now have n8n handling webhooks and workflows. Ollama serves a local LLM endpoint that stays off the public internet.
This baseline works well for support triage, incident summaries, and structured transformations. It also avoids sending customer text to third-party APIs.
If you want the same outcome with less day-2 work (patching, monitoring, backups), consider managed VPS hosting.
If you prefer to tune performance yourself, start with a HostMyCode VPS and scale RAM/CPU as your automation footprint grows.
If your automations touch customer data, self-hosting is often the cleanest way to stay in control. Run this stack on a HostMyCode VPS, or hand off server upkeep to managed VPS hosting while you focus on workflows, prompts, and integrations.
FAQ
Should I expose Ollama to the internet?
Usually no. Keep Ollama on a private Docker network and let n8n call it internally. If you must expose it, put it behind TLS, auth, and strict IP allowlists.
Can I run this on shared hosting?
No. n8n and Ollama need Docker (or system services) and persistent volumes. Use a VPS or dedicated server for predictable resources and control.
How do I secure the n8n editor for a team?
Put SSO in front (OAuth2 proxy), enforce TLS, and restrict access by IP or VPN. Also rotate n8n credentials and keep N8N_ENCRYPTION_KEY safe.
What’s the fastest win for better latency?
Choose a smaller model and keep prompts short. If you still need faster responses with multiple concurrent users, move to a GPU-backed server.
How do I migrate this stack to a new VPS?
Back up the n8n_data and ollama volumes, plus your Compose and Nginx configs. Restore volumes on the new host, then bring the stack up with the same hostnames and TLS certs.