在 Ubuntu 24 上自建 Dify.ai 完整教學指南
這份詳細教學將指導您如何在 Ubuntu 24.04 上部署 Dify.ai,並配置 Nginx 反向代理和 SSL 憑證,建立一個安全的生產環境。
系統需求與前置準備
硬體需求
- CPU: 最少 2 核心,建議 4 核心以上
- 記憶體: 最少 4GB,生產環境建議 8GB 以上
- 儲存空間: 最少 50GB,生產環境建議 100GB 以上
- 網路: 需要公開 IP 位址和網域名稱
軟體需求
- Ubuntu 24.04 LTS (Noble Numbat)
- Docker Engine(最新版本)
- Docker Compose V2
- 已指向伺服器 IP 的網域名稱
- Root 或 sudo 權限
Dify 核心元件介紹
Dify 包含 7 個主要服務:
- API 服務 (dify-api):後端 API 和業務邏輯
- Worker 服務 (dify-worker):非同步任務處理
- Web 服務 (dify-web):前端應用程式
- 資料庫 (PostgreSQL):資料持久化
- Redis:快取和會話管理
- 向量資料庫 (Weaviate):知識庫儲存
- Nginx:反向代理和網頁伺服器
第一步:系統更新與基礎套件安裝
首先更新系統並安裝必要的基礎套件:
# 更新系統套件
sudo apt update && sudo apt upgrade -y
# 安裝必要的工具
sudo apt install -y apt-transport-https ca-certificates curl software-properties-common gnupg lsb-release
第二步:安裝 Docker 和 Docker Compose
安裝 Docker Engine
# 新增 Docker 的官方 GPG 金鑰
sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
sudo chmod a+r /etc/apt/keyrings/docker.asc
# 新增 Docker 套件庫
echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu $(. /etc/os-release && echo "$VERSION_CODENAME") stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
# 更新套件索引並安裝 Docker
sudo apt update
sudo apt install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
# 啟用並啟動 Docker 服務
sudo systemctl enable docker
sudo systemctl start docker
# 將當前使用者加入 docker 群組(避免每次都需要 sudo)
sudo usermod -aG docker $USER
newgrp docker
驗證 Docker 安裝
# 檢查 Docker 版本
docker --version
# 測試 Docker 運行
docker run hello-world
第三步:安裝和設定 Dify.ai
下載 Dify 原始碼
# 複製 Dify 儲存庫
git clone https://github.com/langgenius/dify.git
cd dify/docker
# 複製環境設定範本
cp .env.example .env
# 產生密鑰(記下這個密鑰,稍後需要使用)
openssl rand -base64 42
設定環境變數
使用文字編輯器編輯 .env
檔案:
nano .env
重要的環境變數設定:
# 基本設定
SECRET_KEY=your-generated-secret-key # 使用上面產生的密鑰
DEPLOY_ENV=PRODUCTION # 設為生產環境
# 資料庫設定
DB_USERNAME=postgres
DB_PASSWORD=your-secure-password # 設定強密碼
DB_HOST=db
DB_PORT=5432
DB_DATABASE=dify
# Redis 設定
REDIS_HOST=redis
REDIS_PORT=6379
REDIS_PASSWORD=your-redis-password # 設定 Redis 密碼
REDIS_DB=0
# URL 設定(使用您的網域)
CONSOLE_API_URL=https://your-domain.com/console/api
CONSOLE_WEB_URL=https://your-domain.com
SERVICE_API_URL=https://your-domain.com/api
APP_API_URL=https://your-domain.com/api
APP_WEB_URL=https://your-domain.com
# 檔案儲存設定
STORAGE_TYPE=opendal
OPENDAL_SCHEME=fs
OPENDAL_FS_ROOT=storage
# 向量資料庫設定
VECTOR_STORE=weaviate
WEAVIATE_HOST=weaviate
WEAVIATE_PORT=8080
# 檔案上傳限制
UPLOAD_FILE_SIZE_LIMIT=100M
NGINX_CLIENT_MAX_BODY_SIZE=100M
啟動 Dify 服務
# 啟動所有服務
docker compose up -d
# 檢查所有容器是否正常運行
docker compose ps
# 如果需要查看日誌
docker compose logs -f
等待所有服務啟動完成(通常需要 2-3 分鐘)。您可以使用以下命令檢查服務狀態:
# 檢查 API 服務健康狀態
curl http://localhost:5001/health
第四步:安裝和設定 Nginx
安裝 Nginx
# 安裝 Nginx
sudo apt update
sudo apt install -y nginx
# 啟用並啟動 Nginx
sudo systemctl enable nginx
sudo systemctl start nginx
建立 Nginx 站點設定
建立新的站點設定檔:
sudo nano /etc/nginx/sites-available/dify.conf
輸入以下設定(記得替換 your-domain.com
為您的實際網域):
server {
listen 80;
server_name your-domain.com www.your-domain.com;
# 將 HTTP 重新導向到 HTTPS
return 301 https://$server_name$request_uri;
}
server {
listen 443 ssl http2;
server_name your-domain.com www.your-domain.com;
# SSL 設定(稍後由 Certbot 自動添加)
# 安全標頭
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' data:; connect-src 'self' ws: wss:; frame-ancestors 'self';" always;
# 主應用程式
location / {
proxy_pass http://localhost:80;
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 X-Forwarded-Host $server_name;
proxy_buffering off;
proxy_request_buffering off;
}
# API 端點
location /api {
proxy_pass http://localhost:80;
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_buffering off;
proxy_request_buffering off;
proxy_read_timeout 300s;
proxy_send_timeout 300s;
}
# 控制台 API
location /console {
proxy_pass http://localhost:80;
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_buffering off;
proxy_request_buffering off;
}
# WebSocket 支援
location /ws {
proxy_pass http://localhost:80;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
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_cache_bypass $http_upgrade;
}
# 檔案上傳限制
client_max_body_size 100M;
client_body_timeout 120s;
client_header_timeout 120s;
}
啟用站點並重新載入 Nginx
# 建立符號連結以啟用站點
sudo ln -s /etc/nginx/sites-available/dify.conf /etc/nginx/sites-enabled/
# 測試 Nginx 設定
sudo nginx -t
# 重新載入 Nginx
sudo systemctl restart nginx
第五步:設定網域和 SSL 憑證
DNS 設定
在您的網域註冊商或 DNS 服務商處設定以下記錄:
- A 記錄:
your-domain.com
→ 您的伺服器 IP - CNAME 記錄:
www.your-domain.com
→your-domain.com
等待 DNS 傳播(通常需要 5-30 分鐘)。
安裝 Certbot
# 安裝 Certbot 和 Nginx 插件
sudo apt update
sudo apt install -y certbot python3-certbot-nginx
取得 SSL 憑證
# 先測試設定(乾跑)
sudo certbot --nginx --dry-run -d your-domain.com -d www.your-domain.com
# 如果測試成功,取得實際憑證
sudo certbot --nginx -d your-domain.com -d www.your-domain.com
Certbot 會詢問您的電子郵件地址(用於緊急更新通知)並要求您同意服務條款。選擇選項 2 來自動設定 HTTPS 重新導向。
設定自動更新
Let’s Encrypt 憑證有效期為 90 天,Certbot 會自動設定更新排程:
# 測試自動更新
sudo certbot renew --dry-run
# 檢查 cron 任務
sudo crontab -l | grep certbot
第六步:安全性最佳實踐
設定防火牆 (UFW)
# 檢查 UFW 狀態
sudo ufw status
# 設定預設政策
sudo ufw default deny incoming
sudo ufw default allow outgoing
# 允許 SSH(在啟用 UFW 前務必執行)
sudo ufw allow ssh
# 允許 HTTP 和 HTTPS
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
# 啟用 UFW
sudo ufw enable
# 驗證規則
sudo ufw status verbose
加強 Nginx 安全性設定
編輯 Nginx 設定檔,新增更多安全標頭:
sudo nano /etc/nginx/sites-available/dify.conf
在 server 區塊中新增:
# 增強的安全標頭
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Permissions-Policy "camera=(), microphone=(), geolocation=(), interest-cohort=()" always;
保護環境變數
# 設定強密碼
cd ~/dify/docker
SECRET_KEY=$(openssl rand -base64 42)
DB_PASSWORD=$(openssl rand -base64 32)
REDIS_PASSWORD=$(openssl rand -base64 32)
# 限制檔案權限
chmod 600 .env
定期安全更新
建立更新腳本:
nano ~/update-system.sh
#!/bin/bash
# 系統更新腳本
sudo apt update
sudo apt upgrade -y
sudo apt autoremove -y
docker system prune -af
chmod +x ~/update-system.sh
第七步:常見問題排除
問題 1:連接埠衝突
症狀:連接埠 80 或 443 已被使用
解決方案:
# 檢查連接埠使用情況
sudo netstat -tulpn | grep :80
sudo netstat -tulpn | grep :443
# 如果 Apache 正在運行,停用它
sudo systemctl stop apache2
sudo systemctl disable apache2
問題 2:資料庫連線問題
症狀:無法連接到 PostgreSQL
解決方案:
# 檢查資料庫容器日誌
docker compose logs db
# 重新啟動資料庫服務
docker compose restart db
# 驗證資料庫連線
docker exec -it docker-db-1 psql -U postgres -d dify
問題 3:SSL 憑證問題
症狀:HTTPS 無法正常工作
解決方案:
# 檢查憑證狀態
sudo certbot certificates
# 強制更新憑證
sudo certbot renew --force-renewal
# 驗證 Nginx 設定
sudo nginx -t
sudo systemctl restart nginx
問題 4:跨來源資源共享 (CORS) 錯誤
症狀:瀏覽器控制台顯示 CORS 錯誤
解決方案:
確保 .env
檔案中的 URL 設定正確:
CONSOLE_API_URL=https://your-domain.com/console/api
CONSOLE_WEB_URL=https://your-domain.com
SERVICE_API_URL=https://your-domain.com/api
APP_API_URL=https://your-domain.com/api
APP_WEB_URL=https://your-domain.com
重新啟動服務:
docker compose restart
問題 5:檔案上傳失敗
症狀:大檔案無法上傳
解決方案:
- 更新
.env
檔案:
UPLOAD_FILE_SIZE_LIMIT=100M
NGINX_CLIENT_MAX_BODY_SIZE=100M
-
更新 Nginx 設定中的
client_max_body_size
-
重新啟動服務:
docker compose restart
sudo systemctl restart nginx
維護和備份
備份策略
建立備份腳本:
nano ~/backup-dify.sh
#!/bin/bash
# Dify 備份腳本
BACKUP_DIR="/home/backup/dify"
DATE=$(date +%Y%m%d_%H%M%S)
# 建立備份目錄
mkdir -p $BACKUP_DIR
# 停止服務
cd ~/dify/docker
docker compose down
# 備份資料卷
tar -czf $BACKUP_DIR/dify-volumes-$DATE.tar.gz ./volumes/
# 備份資料庫
docker compose up -d db
sleep 10
docker exec docker-db-1 pg_dump -U postgres dify > $BACKUP_DIR/dify-db-$DATE.sql
# 重新啟動所有服務
docker compose up -d
echo "備份完成:$BACKUP_DIR"
chmod +x ~/backup-dify.sh
更新 Dify
cd ~/dify
git pull origin main
cd docker
docker compose down
docker compose pull
docker compose up -d
監控和日誌
# 即時監控容器狀態
docker stats
# 查看應用程式日誌
docker compose logs -f api
docker compose logs -f worker
# 查看 Nginx 日誌
sudo tail -f /var/log/nginx/access.log
sudo tail -f /var/log/nginx/error.log
效能優化建議
系統優化
# 增加檔案描述符限制
echo "* soft nofile 65536" >> /etc/security/limits.conf
echo "* hard nofile 65536" >> /etc/security/limits.conf
# 優化 Docker 日誌
echo '{"log-driver": "json-file", "log-opts": {"max-size": "10m", "max-file": "3"}}' > /etc/docker/daemon.json
sudo systemctl restart docker
資料庫優化
在 PostgreSQL 容器中調整設定:
docker exec -it docker-db-1 bash
echo "shared_buffers = 256MB" >> /var/lib/postgresql/data/pgdata/postgresql.conf
echo "effective_cache_size = 1GB" >> /var/lib/postgresql/data/pgdata/postgresql.conf
exit
docker compose restart db
結語
恭喜!您已經成功在 Ubuntu 24 上部署了 Dify.ai,並設定了安全的 HTTPS 連線。現在您可以:
- 訪問
https://your-domain.com
開始使用 Dify - 使用預設管理員帳號登入(首次登入會要求設定密碼)
- 開始建立您的 AI 應用程式
重要提醒:
- 定期備份您的資料
- 保持系統和 Docker 映像更新
- 監控系統資源使用情況
- 定期檢查安全日誌
如需更多協助,請參考 Dify 官方文件 或加入社群討論。