
Dify fills the gap between “I can run an LLM” and “my team can use this safely in a real workflow.” If you want that control without shipping prompts to a third party, you can self-host Dify with Ollama on your own VPS. This keeps traffic, logs, and model files on infrastructure you manage.
This walkthrough builds a production-leaning stack on Ubuntu. You’ll run Dify and its required services, Ollama as the local model runtime, and an Nginx reverse proxy with HTTPS plus light hardening.
The result is a clean baseline you can upgrade, migrate, and back up without drama.
What you’ll build (and what you won’t)
- Dify running on your VPS (web UI + API) with persistent data volumes.
- Ollama running locally as your model runtime (CPU-first; GPU is optional).
- Nginx reverse proxy in front with TLS (Let’s Encrypt) and sane headers.
- Access control: firewall rules and optional IP allow-listing.
Limitations to be aware of:
- CPU-only inference is fine for smaller models and light concurrency. If you expect multiple users chatting at once, plan for more RAM/CPU or a GPU box.
- Dify’s full feature set depends on its internal services (PostgreSQL/Redis). Don’t “simplify” them away unless you enjoy debugging.
- This guide assumes one VPS and one public domain. Multi-node scaling is a different problem.
Prerequisites and resource sizing for a VPS
Any standard Linux VPS will work. If you’re sizing a new instance, these starting points are realistic:
- Minimum (testing): 4 vCPU, 8 GB RAM, 60+ GB SSD/NVMe.
- Comfortable (1–5 users): 6–8 vCPU, 16 GB RAM, 100+ GB NVMe.
- Disk: model files can grow fast. Budget 20–80 GB depending on what you pull with Ollama.
On CPU-only hosts, responsiveness depends on model size and quantization. Small, quantized models can feel snappy enough for internal tools.
Large models will crawl, especially with concurrent users. If you outgrow CPU inference, move Ollama to a GPU machine later. You can keep Dify on the same VPS.
For infrastructure, a straightforward option is a HostMyCode VPS. It gives you control over networking, storage, and Docker without shared-host limitations.
If you’d rather not handle patching and OS hardening, managed VPS hosting is the lower-maintenance route.
Step 1: Prepare DNS, OS packages, and a non-root workflow
Pick a hostname for Dify, such as dify.example.com. Create an A record pointing to your VPS public IP.
If you prefer to keep domain and DNS in one place, use HostMyCode Domains.
SSH into the server and bring packages up to date:
sudo apt update
sudo apt -y upgrade
Install Docker Engine and the Compose plugin from Ubuntu’s packages. This is a solid default.
If you already use Docker’s official repository, stick with your usual approach.
sudo apt -y install ca-certificates curl gnupg
sudo apt -y install docker.io docker-compose-plugin
sudo systemctl enable --now docker
Create a deployment user and grant it access to Docker:
sudo adduser dify
sudo usermod -aG docker dify
Log out and back in as dify (or run newgrp docker) so the group change applies.
Step 2: Create the directory layout and persistent volumes
Put Compose files and state under a single, predictable path. This makes backups, restores, and audits much easier.
sudo mkdir -p /opt/dify
sudo chown -R dify:dify /opt/dify
cd /opt/dify
Create subfolders so you can back up (or exclude) specific pieces later:
mkdir -p data/postgres data/redis data/storage data/ollama
Notes:
data/postgresholds Dify’s database. Back it up.data/storagewill hold uploaded files and assets.data/ollamaholds pulled models. It can be large; decide whether to back it up or re-pull.
Step 3: Write a Docker Compose file for Dify + Ollama
Create /opt/dify/docker-compose.yml:
cd /opt/dify
nano docker-compose.yml
Paste the following Compose file. It keeps services on an internal Docker network.
Only Nginx is exposed publicly.
services:
nginx:
image: nginx:stable
container_name: dify-nginx
depends_on:
- dify-api
- dify-web
ports:
- "80:80"
- "443:443"
volumes:
- ./nginx/conf.d:/etc/nginx/conf.d:ro
- ./nginx/letsencrypt:/etc/letsencrypt:ro
- ./nginx/www:/var/www/certbot:ro
restart: unless-stopped
certbot:
image: certbot/certbot
container_name: dify-certbot
volumes:
- ./nginx/letsencrypt:/etc/letsencrypt
- ./nginx/www:/var/www/certbot
entrypoint: sh -c "trap exit TERM; while :; do sleep 12h & wait $${!}; certbot renew --webroot -w /var/www/certbot --quiet; done"
restart: unless-stopped
postgres:
image: postgres:16
container_name: dify-postgres
environment:
POSTGRES_DB: dify
POSTGRES_USER: dify
POSTGRES_PASSWORD: change-me-strong-db-password
volumes:
- ./data/postgres:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U dify -d dify"]
interval: 10s
timeout: 5s
retries: 10
restart: unless-stopped
redis:
image: redis:7
container_name: dify-redis
command: ["redis-server", "--appendonly", "yes"]
volumes:
- ./data/redis:/data
restart: unless-stopped
ollama:
image: ollama/ollama
container_name: dify-ollama
volumes:
- ./data/ollama:/root/.ollama
restart: unless-stopped
dify-api:
image: langgenius/dify-api:latest
container_name: dify-api
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_started
environment:
# Core
MODE: api
LOG_LEVEL: INFO
SECRET_KEY: change-me-long-random-string
# URLs (set these to your domain)
CONSOLE_WEB_URL: https://dify.example.com
SERVICE_API_URL: https://dify.example.com
APP_WEB_URL: https://dify.example.com
# Database
DB_USERNAME: dify
DB_PASSWORD: change-me-strong-db-password
DB_HOST: postgres
DB_PORT: 5432
DB_DATABASE: dify
# Redis
REDIS_HOST: redis
REDIS_PORT: 6379
# Storage (local)
STORAGE_TYPE: local
LOCAL_STORAGE_PATH: /app/api/storage
# Allow Dify to reach Ollama over the Docker network
OLLAMA_BASE_URL: http://ollama:11434
volumes:
- ./data/storage:/app/api/storage
restart: unless-stopped
dify-web:
image: langgenius/dify-web:latest
container_name: dify-web
depends_on:
- dify-api
environment:
CONSOLE_API_URL: https://dify.example.com
APP_API_URL: https://dify.example.com
restart: unless-stopped
Change these values before you start:
dify.example.com→ your real domain.POSTGRES_PASSWORDand the matchingDB_PASSWORD→ strong password.SECRET_KEY→ generate a long random string.
Generate a good secret:
openssl rand -hex 32
Step 4: Add Nginx reverse proxy config (HTTPS-ready)
Create the Nginx config directories:
mkdir -p /opt/dify/nginx/conf.d /opt/dify/nginx/www
Create /opt/dify/nginx/conf.d/dify.conf:
nano /opt/dify/nginx/conf.d/dify.conf
Use this config (replace the server_name):
server {
listen 80;
server_name dify.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 dify.example.com;
ssl_certificate /etc/letsencrypt/live/dify.example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/dify.example.com/privkey.pem;
# Basic hardening headers
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;
client_max_body_size 25m;
# Web UI
location / {
proxy_pass http://dify-web:3000;
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;
}
# API routes (keep this simple; Dify uses /api)
location /api {
proxy_pass http://dify-api:5001;
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;
}
}
If you’ve run Open WebUI before, this flow will look familiar. If not, the reverse-proxy pattern and TLS lifecycle are the same as in our guide on running Open WebUI with HTTPS on a VPS.
We use Nginx here because it’s a common default on hosting servers.
Step 5: Obtain a Let’s Encrypt certificate
Start Nginx without TLS first. This makes the ACME challenge endpoint reachable.
After the certificate is issued, you’ll restart the stack.
cd /opt/dify
docker compose up -d nginx
Run Certbot once to request the certificate. Replace the email and domain:
docker compose run --rm certbot certonly \
--webroot -w /var/www/certbot \
-d dify.example.com \
--email you@example.com \
--agree-tos --no-eff-email
Bring the full stack up:
docker compose up -d
Verify containers:
docker ps
Then open https://dify.example.com. If you see a 502, check the logs immediately:
docker logs --tail=200 dify-nginx
docker logs --tail=200 dify-api
docker logs --tail=200 dify-web
Step 6: Pull a model in Ollama (CPU-friendly first)
Before you wire up Dify, confirm Ollama runs and pull a model. On CPU VPS instances, start small and work up.
docker exec -it dify-ollama ollama pull llama3
If that’s too heavy for your box, pick a smaller model or a more aggressively quantized build.
Smaller or quantized models respond faster and use less RAM. The trade-off is accuracy, instruction-following, and depth.
Quick health check:
docker exec -it dify-ollama ollama list
docker exec -it dify-ollama ollama run llama3 "Say hello in one sentence."
If you want tighter control over model size on constrained servers, see quantizing Llama models for Ollama on a VPS for an operator-focused view of the size/quality trade-offs.
Step 7: Connect Dify to Ollama
Log into the Dify console. On first run, you’ll be prompted to create an admin account.
Then:
- Go to Settings → Model Provider (the label can vary slightly by version).
- Select Ollama as the provider.
- Set the base URL to
http://ollama:11434(internal Docker network). - Select the model name exactly as Ollama lists it (for example
llama3). - Run the provider test if available.
If the UI insists on an external URL and rejects the internal hostname, try http://dify-ollama:11434 (the container name).
You can also expose Ollama only to localhost and proxy it internally. In most cases, avoid exposing Ollama to the public internet.
Step 8: Make persistence real (backup plan you can execute)
Your “can’t lose it” data lives in PostgreSQL and Dify’s storage directory. Model files are usually re-downloadable.
You may still back up models if bandwidth is expensive or slow.
Here’s a straightforward PostgreSQL backup you can run from the host:
mkdir -p /opt/dify/backups
docker exec -t dify-postgres pg_dump -U dify -d dify | gzip > /opt/dify/backups/dify-postgres-$(date +%F).sql.gz
And a simple storage backup:
tar -czf /opt/dify/backups/dify-storage-$(date +%F).tar.gz -C /opt/dify data/storage
If you already back up other services on this VPS, add these to the existing job.
Don’t create a parallel system unless you need it.
For general storage hygiene (including “why is my disk full?” moments), keep this close: how to find large files and free space safely.
Step 9: Lock down the endpoint (firewall + optional allow-list)
Dify is an application platform. Treat it like one.
Expose only what you need, and be explicit about access.
sudo apt -y install ufw
sudo ufw allow OpenSSH
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw --force enable
sudo ufw status
If Dify is internal-only, restrict access to your office IP or VPN egress IP. Nginx can enforce an allow-list:
# Add inside the 443 server block:
# allow 203.0.113.10;
# deny all;
If your server gets constant credential stuffing and scanners, add automated blocking. CrowdSec fits well on VPS hosts: install CrowdSec to block bruteforce on Ubuntu.
Step 10: Validate performance and avoid common failure modes
Two checks prevent most “it was fine yesterday” issues: memory pressure and disk growth.
- RAM: If the box swaps heavily, token generation gets unpredictable. Check with
free -handvmstat 1. - Disk: Ollama models and logs add up quickly. Watch
df -handdocker system df.
Useful commands:
# See container resource usage
docker stats
# Follow Dify API logs
docker logs -f dify-api
# Confirm Ollama is reachable from the Dify API container
docker exec -it dify-api sh -lc "apk add --no-cache curl || true; curl -s http://ollama:11434/api/tags"
If responses feel slow, model size (or quantization) is the first lever.
The next lever is expectations. A single VPS has real concurrency limits.
Operational notes: upgrades, restarts, and safe changes
Compose makes upgrades repeatable. Do them during a quiet window:
cd /opt/dify
docker compose pull
docker compose up -d
docker image prune -f
Take a database dump before you upgrade. If you need to roll back images, you’ll still have your data.
Also version your reverse proxy config, even in a small private Git repo.
One typo in Nginx can masquerade as a Dify outage.
Where to go next (practical extensions)
- SSO in front of the UI: If Dify is internal, an auth proxy is often cleaner than relying only on app-level logins. The patterns are similar to Open WebUI with OAuth2 Proxy.
- Add RAG for your docs: Dify can call tools and data sources; many teams pair it with a vector store. If your stack already includes Open WebUI, the pgvector approach in Open WebUI RAG with pgvector is a solid reference architecture.
- Split inference to a GPU node: Keep Dify on a general VPS and run model inference on a GPU dedicated server. This separation makes scaling and cost control simpler.
If you care about predictable performance for a self-hosted AI app builder, start with a VPS that gives you dedicated resources and full control over Docker and networking. A HostMyCode VPS is a solid baseline, and managed VPS hosting is a good fit if you’d rather spend time building in Dify than maintaining the underlying OS.
FAQ: Dify + Ollama on a VPS
Can I run Dify and Ollama on the same VPS without a GPU?
Yes. For light usage, CPU-only works. Keep model size modest and expect slower generation under load.
Should I expose Ollama to the public internet?
Usually no. Keep Ollama on the internal Docker network and only expose Dify via HTTPS. If you must expose it, add authentication and strict firewall rules.
What do I need to back up?
Back up PostgreSQL and data/storage. Model files in data/ollama are optional; you can often re-pull them.
How do I move this setup to a bigger server later?
Restore the PostgreSQL dump and copy data/storage to the new host. Then bring the stack up with the same environment values and domain config.
If you want help moving production services, HostMyCode offers migration help so you can shift with less downtime.
Summary
You now have a working deployment where you can self-host Dify with Ollama on a VPS using Docker Compose, persistent storage, and an HTTPS reverse proxy. This baseline is enough for internal AI tools, support workflows, or prototypes that shouldn’t leave your infrastructure.
If usage grows, the next step is to move inference to a larger machine (often GPU-backed). You can keep Dify and its database on stable hosting.
For that foundation layer, a HostMyCode VPS remains an easy building block.