You’ve been asked to stand up Dify so the team has a single platform for RAG, agent workflows, and prompt versioning that exposes OpenAI-compatible endpoints. The Docker Compose quickstart works, the team imports a dataset, the chatbot answers from the indexed PDFs, the product manager is happy. Six months later, Postgres is bound to 0.0.0.0:5432 because the compose file did the default, the Dify SECRET_KEY was regenerated on a redeploy so every stored model credential is now garbage, the Qdrant collection backing the dataset has no API key, and the OpenAI-compatible endpoint that fronts every Dify app is reachable without an API key from the public Internet.
What’s happening
A Dify deployment that actually serves an LLM product needs more than the upstream compose. PostgreSQL, Redis, and the vector store (Qdrant or Weaviate) must stay on the internal compose network — never published to the host’s public interface. The Dify api and web containers sit behind nginx with Let’s Encrypt; the host should publish :443 only. The Dify SECRET_KEY must be generated once and persisted forever — it is the symmetric key that seals every stored model API key, dataset secret, and tool credential in Postgres, and if it changes, those rows become unreadable ciphertext you cannot recover without re-entering every secret by hand. The OpenAI-compatible endpoints under /v1/chat/completions require a Dify app API key on every request and that gate must be enforced at the reverse proxy as well, so an upstream WAF can rate-limit before the model is invoked. The vector store has to require its own API key — Dify’s default compose leaves Qdrant open inside the network, but you want defense in depth in case a workload escape lands a process on the docker network.
How to verify
After install, the host should expose only :443 and :22:
ss -lntp | grep -E ':(80|443|5001|5432|6379|6333)\b'
# 0.0.0.0:443 nginx
# 127.0.0.1:5001 dify-api (via compose)
Postgres on 5432, Redis on 6379, Qdrant on 6333 must not appear on the host at all. The OpenAI-compatible endpoint must reject anonymous calls:
curl -sS -o /dev/null -w '%{http_code}\n' \
-X POST https://dify.example.com/v1/chat-messages \
-H 'Content-Type: application/json' -d '{"query":"hi","response_mode":"blocking","user":"test"}'
# 401
The console health endpoint should respond over HTTPS:
curl -sS https://dify.example.com/console/api/setup | jq .step
# "finished" once you've completed the install wizard
If the chat-messages call returns 200 without Authorization: Bearer app-..., the app-key gate is gone — disable the app immediately.
The fix
Save the script below as /root/setup-dify-ubuntu22.sh, then run it. It installs Dify on a fresh Ubuntu 22.04 VM: base update, UFW (SSH + HTTP + HTTPS only), SSH hardening with root key preserved, unattended-upgrades, Docker CE + compose plugin, the official Dify compose stack with PostgreSQL, Redis, and Qdrant kept on the internal network, randomly generated SECRET_KEY and INIT_PASSWORD written to /opt/dify/.env with chmod 600, a Qdrant API key the compose passes to both Qdrant and the Dify api worker, nginx terminating TLS for the console and the public API with HSTS, Let’s Encrypt via the certbot nginx plugin, and a poll loop that waits for :5001 and :443 before declaring success.
#!/usr/bin/env bash
set -euo pipefail
### Ubuntu 22.04 Dify clean VM installer
### Keeps root SSH key login enabled
### Disables SSH password login
### Enables automatic security updates
### Installs and configures Docker + Dify + nginx + Let's Encrypt
### SECRET_KEY persisted; DB and vector store internal-only
### No local backups; assumes VM-level backup
### Reboot remains manual
if [[ "$(id -u)" -ne 0 ]]; then
echo "Run as root."
exit 1
fi
: "${DIFY_DOMAIN:?Set DIFY_DOMAIN=dify.example.com}"
: "${DIFY_EMAIL:?Set DIFY_EMAIL=ops@example.com for Let's Encrypt}"
DIFY_VERSION="${DIFY_VERSION:-0.15.3}"
DIFY_SECRET_KEY="${DIFY_SECRET_KEY:-$(openssl rand -base64 42 | tr -d '\n')}"
DIFY_INIT_PASSWORD="${DIFY_INIT_PASSWORD:-$(openssl rand -hex 16)}"
DIFY_PG_PASSWORD="${DIFY_PG_PASSWORD:-$(openssl rand -hex 24)}"
DIFY_REDIS_PASSWORD="${DIFY_REDIS_PASSWORD:-$(openssl rand -hex 24)}"
DIFY_QDRANT_API_KEY="${DIFY_QDRANT_API_KEY:-$(openssl rand -hex 32)}"
echo
echo "========================================"
echo "Dify Ubuntu 22.04 Setup"
echo "========================================"
echo
echo "==> Updating base OS"
export DEBIAN_FRONTEND=noninteractive
apt-get update
apt-get -y upgrade
echo "==> Installing base packages"
apt-get -y install \
vim curl wget ca-certificates gnupg2 \
chrony fail2ban unattended-upgrades \
ufw lsof tcpdump dnsutils tar gzip \
iproute2 net-tools openssl jq \
software-properties-common
echo "==> Enabling time sync"
systemctl enable --now chrony
timedatectl set-ntp true
echo "==> Applying kernel/network tuning"
cat > /etc/sysctl.d/99-dify.conf <<'SYSCTL'
net.core.default_qdisc = fq
net.ipv4.tcp_congestion_control = bbr
net.core.somaxconn = 4096
net.core.netdev_max_backlog = 250000
net.ipv4.tcp_max_syn_backlog = 8192
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_fin_timeout = 15
net.ipv4.ip_local_port_range = 10240 65535
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv6.conf.all.accept_redirects = 0
net.ipv6.conf.default.accept_redirects = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0
kernel.dmesg_restrict = 1
kernel.kptr_restrict = 2
fs.file-max = 2097152
vm.max_map_count = 262144
SYSCTL
modprobe tcp_bbr || true
echo tcp_bbr > /etc/modules-load.d/bbr.conf
sysctl --system
echo "==> Setting file limits"
cat > /etc/security/limits.d/99-dify.conf <<'LIMITS'
* soft nofile 64000
* hard nofile 64000
root soft nofile 64000
root hard nofile 64000
LIMITS
echo "==> Configuring UFW"
ufw --force reset
ufw default deny incoming
ufw default allow outgoing
ufw allow 22/tcp
ufw allow 80/tcp
ufw allow 443/tcp
ufw --force enable
echo "==> Hardening SSH while keeping root SSH key login enabled"
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak.$(date +%F-%H%M%S)
set_sshd_option() {
local key="$1"
local value="$2"
if grep -qE "^[#[:space:]]*${key}[[:space:]]+" /etc/ssh/sshd_config; then
sed -i "s|^[#[:space:]]*${key}[[:space:]].*|${key} ${value}|" /etc/ssh/sshd_config
else
echo "${key} ${value}" >> /etc/ssh/sshd_config
fi
}
set_sshd_option PermitRootLogin prohibit-password
set_sshd_option PasswordAuthentication no
set_sshd_option PubkeyAuthentication yes
set_sshd_option KbdInteractiveAuthentication no
set_sshd_option ChallengeResponseAuthentication no
set_sshd_option X11Forwarding no
set_sshd_option ClientAliveInterval 300
set_sshd_option ClientAliveCountMax 2
set_sshd_option MaxAuthTries 4
sshd -t
systemctl restart ssh
echo "==> Configuring fail2ban"
mkdir -p /etc/fail2ban/jail.d
cat > /etc/fail2ban/jail.d/sshd.local <<'FAIL2BAN'
[sshd]
enabled = true
port = ssh
backend = systemd
maxretry = 4
findtime = 10m
bantime = 1h
FAIL2BAN
systemctl enable --now fail2ban
echo "==> Configuring unattended-upgrades for security"
cat > /etc/apt/apt.conf.d/20auto-upgrades <<'AUTOUPG'
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";
APT::Periodic::AutocleanInterval "7";
AUTOUPG
echo "==> Installing Docker CE"
install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg \
| gpg --dearmor -o /etc/apt/keyrings/docker.gpg
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 jammy stable" \
> /etc/apt/sources.list.d/docker.list
apt-get update
apt-get -y install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
systemctl enable --now docker
echo "==> Preparing /opt/dify"
mkdir -p /opt/dify/volumes/{app/storage,db/data,redis/data,qdrant/storage,qdrant/snapshots}
chmod 700 /opt/dify
cat > /opt/dify/.env <<ENV
DIFY_VERSION=${DIFY_VERSION}
DIFY_DOMAIN=${DIFY_DOMAIN}
SECRET_KEY=${DIFY_SECRET_KEY}
INIT_PASSWORD=${DIFY_INIT_PASSWORD}
DB_PASSWORD=${DIFY_PG_PASSWORD}
REDIS_PASSWORD=${DIFY_REDIS_PASSWORD}
QDRANT_API_KEY=${DIFY_QDRANT_API_KEY}
ENV
chmod 600 /opt/dify/.env
cat > /opt/dify/docker-compose.yml <<'COMPOSE'
services:
db:
image: postgres:15-alpine
restart: unless-stopped
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: ${DB_PASSWORD}
POSTGRES_DB: dify
PGDATA: /var/lib/postgresql/data/pgdata
volumes:
- /opt/dify/volumes/db/data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 30s
timeout: 5s
retries: 5
start_period: 20s
redis:
image: redis:7-alpine
restart: unless-stopped
command: redis-server --requirepass ${REDIS_PASSWORD} --save 60 1 --loglevel warning
volumes:
- /opt/dify/volumes/redis/data:/data
healthcheck:
test: ["CMD-SHELL", "redis-cli -a ${REDIS_PASSWORD} ping | grep PONG"]
interval: 30s
timeout: 3s
retries: 5
start_period: 20s
qdrant:
image: qdrant/qdrant:v1.12.4
restart: unless-stopped
environment:
QDRANT__SERVICE__API_KEY: ${QDRANT_API_KEY}
QDRANT__TELEMETRY_DISABLED: "true"
volumes:
- /opt/dify/volumes/qdrant/storage:/qdrant/storage
- /opt/dify/volumes/qdrant/snapshots:/qdrant/snapshots
api:
image: langgenius/dify-api:${DIFY_VERSION}
restart: unless-stopped
depends_on:
db:
condition: service_healthy
redis:
condition: service_healthy
environment:
MODE: api
LOG_LEVEL: INFO
SECRET_KEY: ${SECRET_KEY}
INIT_PASSWORD: ${INIT_PASSWORD}
CONSOLE_API_URL: https://${DIFY_DOMAIN}
CONSOLE_WEB_URL: https://${DIFY_DOMAIN}
SERVICE_API_URL: https://${DIFY_DOMAIN}
APP_API_URL: https://${DIFY_DOMAIN}
APP_WEB_URL: https://${DIFY_DOMAIN}
FILES_URL: https://${DIFY_DOMAIN}
MIGRATION_ENABLED: "true"
DB_USERNAME: postgres
DB_PASSWORD: ${DB_PASSWORD}
DB_HOST: db
DB_PORT: "5432"
DB_DATABASE: dify
REDIS_HOST: redis
REDIS_PORT: "6379"
REDIS_PASSWORD: ${REDIS_PASSWORD}
REDIS_USE_SSL: "false"
CELERY_BROKER_URL: redis://:${REDIS_PASSWORD}@redis:6379/1
STORAGE_TYPE: local
STORAGE_LOCAL_PATH: storage
VECTOR_STORE: qdrant
QDRANT_URL: http://qdrant:6333
QDRANT_API_KEY: ${QDRANT_API_KEY}
QDRANT_CLIENT_TIMEOUT: "20"
WEB_API_CORS_ALLOW_ORIGINS: https://${DIFY_DOMAIN}
CONSOLE_CORS_ALLOW_ORIGINS: https://${DIFY_DOMAIN}
SENTRY_DSN: ""
TELEMETRY: "false"
volumes:
- /opt/dify/volumes/app/storage:/app/api/storage
ports:
- "127.0.0.1:5001:5001"
ulimits:
nofile:
soft: 64000
hard: 64000
worker:
image: langgenius/dify-api:${DIFY_VERSION}
restart: unless-stopped
depends_on:
db:
condition: service_healthy
redis:
condition: service_healthy
environment:
MODE: worker
LOG_LEVEL: INFO
SECRET_KEY: ${SECRET_KEY}
DB_USERNAME: postgres
DB_PASSWORD: ${DB_PASSWORD}
DB_HOST: db
DB_PORT: "5432"
DB_DATABASE: dify
REDIS_HOST: redis
REDIS_PORT: "6379"
REDIS_PASSWORD: ${REDIS_PASSWORD}
CELERY_BROKER_URL: redis://:${REDIS_PASSWORD}@redis:6379/1
STORAGE_TYPE: local
STORAGE_LOCAL_PATH: storage
VECTOR_STORE: qdrant
QDRANT_URL: http://qdrant:6333
QDRANT_API_KEY: ${QDRANT_API_KEY}
TELEMETRY: "false"
volumes:
- /opt/dify/volumes/app/storage:/app/api/storage
web:
image: langgenius/dify-web:${DIFY_VERSION}
restart: unless-stopped
environment:
CONSOLE_API_URL: https://${DIFY_DOMAIN}
APP_API_URL: https://${DIFY_DOMAIN}
SENTRY_DSN: ""
ports:
- "127.0.0.1:3000:3000"
COMPOSE
echo "==> Starting Dify stack"
docker compose --env-file /opt/dify/.env -f /opt/dify/docker-compose.yml up -d
echo "==> Waiting for Dify api on 127.0.0.1:5001"
for i in {1..120}; do
if ss -lntp | grep -q '127.0.0.1:5001'; then
break
fi
sleep 2
done
if ! ss -lntp | grep -q '127.0.0.1:5001'; then
echo "Dify api failed to listen on 127.0.0.1:5001"
docker compose -f /opt/dify/docker-compose.yml logs --tail=200 api || true
exit 1
fi
echo "==> Installing nginx and certbot"
apt-get -y install nginx certbot python3-certbot-nginx
cat > /etc/nginx/sites-available/dify <<NGINX
upstream dify_api {
server 127.0.0.1:5001;
keepalive 32;
}
upstream dify_web {
server 127.0.0.1:3000;
keepalive 32;
}
server {
listen 80;
listen [::]:80;
server_name ${DIFY_DOMAIN};
return 301 https://\$host\$request_uri;
}
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name ${DIFY_DOMAIN};
client_max_body_size 200M;
proxy_read_timeout 600s;
proxy_send_timeout 600s;
proxy_connect_timeout 60s;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Content-Type-Options nosniff always;
add_header X-Frame-Options SAMEORIGIN always;
add_header Referrer-Policy strict-origin-when-cross-origin always;
location /console/api/ {
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_http_version 1.1;
proxy_pass http://dify_api;
}
location /api/ {
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_http_version 1.1;
proxy_pass http://dify_api;
}
location /v1/ {
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_http_version 1.1;
proxy_pass http://dify_api;
}
location /files/ {
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_http_version 1.1;
proxy_pass http://dify_api;
}
location / {
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_http_version 1.1;
proxy_pass http://dify_web;
}
}
NGINX
ln -sf /etc/nginx/sites-available/dify /etc/nginx/sites-enabled/dify
rm -f /etc/nginx/sites-enabled/default
nginx -t
systemctl enable --now nginx
systemctl reload nginx
echo "==> Requesting Let's Encrypt certificate"
certbot --nginx --non-interactive --agree-tos \
-m "${DIFY_EMAIL}" -d "${DIFY_DOMAIN}" --redirect
systemctl enable --now certbot.timer
echo "==> Waiting for HTTPS listener"
for i in {1..30}; do
if ss -lntp | grep -q ':443'; then
break
fi
sleep 1
done
echo "==> Final package update"
apt-get -y upgrade
echo
echo "========================================"
echo "DONE"
echo "========================================"
echo
echo "Kernel:"
uname -r
echo
echo "SSH effective settings:"
sshd -T | grep -E '^(permitrootlogin|passwordauthentication|pubkeyauthentication) ' || true
echo
echo "Listeners:"
ss -lntp | grep -E ':(80|443|3000|5001|5432|6379|6333)\b' || true
echo
echo "Containers:"
docker compose -f /opt/dify/docker-compose.yml ps
echo
echo "Services:"
systemctl is-active docker nginx fail2ban chrony || true
echo
echo "Console setup status:"
curl -sS "https://${DIFY_DOMAIN}/console/api/setup" | jq . || true
echo
echo "Secrets written to /opt/dify/.env (mode 600). Move them to your secrets manager and remove the file from this host before going live."
echo "SECRET_KEY persistence is non-negotiable — losing it means every stored model API key, dataset secret, and tool credential becomes unreadable ciphertext."
echo
echo "First admin bootstrap password (used on first wizard step):"
echo " ${DIFY_INIT_PASSWORD}"
echo
echo "Web UI:"
echo "https://${DIFY_DOMAIN}/install"
echo
echo "First steps:"
echo "1. Open /install, create the admin email/password using the bootstrap password above."
echo "2. Add a model provider (OpenAI, Anthropic, Azure, local LLM)."
echo "3. Build the first app, generate its app API key, restrict CORS origins."
echo "4. Confirm /v1/chat-messages without Authorization returns 401."
Make it executable and run it:
chmod 700 /root/setup-dify-ubuntu22.sh
DIFY_DOMAIN=dify.example.com DIFY_EMAIL=ops@example.com /root/setup-dify-ubuntu22.sh
The install wizard at https://dify.example.com/install will ask for the admin email and password; use DIFY_INIT_PASSWORD from the script output as the wizard’s “init password”. After that, register the first model provider, build an app, and verify that calls to /v1/chat-messages without Authorization: Bearer app-... return 401. Move /opt/dify/.env into your secrets manager and back up SECRET_KEY separately — restoring a Postgres dump without that key is a dataset of ciphertext you cannot decrypt.
Run the production Dify on a Stack Harbor-managed environment with monitoring on LLM cost spikes, prompt-injection alerts, and Sev-1 escalation: Managed Cloud Ops.