On vous demande de monter Dify pour donner à l’équipe une plateforme unique pour la génération augmentée par récupération (RAG), les flux d’agents et la gestion de prompts, avec en prime des endpoints compatibles OpenAI. Le démarrage rapide Docker Compose fonctionne, l’équipe importe un jeu de données, le chatbot répond à partir des PDF indexés, la directrice produit est satisfaite. Six mois plus tard, Postgres est lié à 0.0.0.0:5432 parce que le fichier compose a pris la valeur par défaut, la SECRET_KEY de Dify a été régénérée lors d’un redéploiement, donc chaque identifiant de modèle entreposé est désormais du charabia, la collection Qdrant qui appuie le jeu de données n’a aucune clé API, et l’endpoint compatible OpenAI qui sert chaque application Dify est joignable depuis l’Internet public sans authentification.
Ce qui se passe
Un déploiement Dify qui sert réellement un produit LLM demande beaucoup plus que la pile compose amont. PostgreSQL, Redis et le magasin de vecteurs (Qdrant ou Weaviate) doivent rester sur le réseau compose interne — jamais publiés sur l’interface publique de l’hôte. Les conteneurs api et web de Dify s’assoient derrière nginx avec Let’s Encrypt ; l’hôte ne doit publier que :443. La SECRET_KEY de Dify doit être générée une seule fois et persistée pour toujours — c’est la clé symétrique qui scelle chaque clé API de modèle, secret de jeu de données et identifiant d’outil entreposé dans Postgres, et si elle change, ces lignes deviennent du texte chiffré illisible que vous ne pouvez pas récupérer sans ressaisir manuellement chaque secret. Les endpoints compatibles OpenAI sous /v1/chat/completions exigent une clé API d’application Dify à chaque requête, et ce verrou doit aussi être appliqué au proxy inverse, pour qu’un WAF amont puisse limiter le taux avant que le modèle soit invoqué. Le magasin de vecteurs doit exiger sa propre clé API — la pile compose par défaut de Dify laisse Qdrant ouvert à l’intérieur du réseau, mais on veut de la défense en profondeur au cas où une évasion de charge atterrit sur le réseau docker.
Comment vérifier
Après installation, l’hôte ne doit exposer que :443 et :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 sur 5432, Redis sur 6379 et Qdrant sur 6333 ne doivent pas apparaître côté hôte. L’endpoint compatible OpenAI doit rejeter les appels anonymes :
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
Le statut du wizard d’installation doit répondre en HTTPS :
curl -sS https://dify.example.com/console/api/setup | jq .step
# "finished" une fois l'assistant d'installation terminé
Si l’appel chat-messages retourne 200 sans Authorization: Bearer app-..., le verrou de clé d’application est absent — désactivez l’application immédiatement.
Le correctif
Enregistrez le script ci-dessous sous /root/setup-dify-ubuntu22.sh, puis exécutez-le. Il installe Dify sur une VM Ubuntu 22.04 fraîche : mise à jour de base, UFW (SSH + HTTP + HTTPS uniquement), durcissement SSH avec conservation de l’accès clé root, unattended-upgrades, Docker CE + plugin compose, la pile compose officielle de Dify avec PostgreSQL, Redis et Qdrant maintenus sur le réseau interne, SECRET_KEY et INIT_PASSWORD générés aléatoirement et écrits dans /opt/dify/.env en chmod 600, une clé API Qdrant que la pile compose passe à la fois à Qdrant et au worker api de Dify, nginx qui termine TLS pour la console et l’API publique avec HSTS, Let’s Encrypt via le plugin nginx de certbot, et une boucle d’attente qui valide :5001 puis :443 avant de déclarer succès.
#!/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."
Rendez-le exécutable et exécutez-le :
chmod 700 /root/setup-dify-ubuntu22.sh
DIFY_DOMAIN=dify.example.com DIFY_EMAIL=ops@example.com /root/setup-dify-ubuntu22.sh
L’assistant d’installation à https://dify.example.com/install vous demandera le courriel et le mot de passe administrateur ; utilisez DIFY_INIT_PASSWORD de la sortie du script comme « init password » du wizard. Après ça, enregistrez le premier fournisseur de modèle, construisez une application, et vérifiez que les appels à /v1/chat-messages sans Authorization: Bearer app-... retournent 401. Déplacez /opt/dify/.env vers votre gestionnaire de secrets et sauvegardez SECRET_KEY séparément — restaurer une décharge Postgres sans cette clé donne un jeu de données de texte chiffré que vous ne pouvez pas déchiffrer.
Exploitez le Dify de production dans un environnement infogéré par Stack Harbor avec supervision des pics de coûts LLM, alertes d’injection de prompts et escalade Sev-1 : Environnements infogérés.