🔒
GCEセルフホストDifyをhttps化する
前提
- GCEでDifyをdocker composeで立ち上げている
- ドメインも設定済みで、
http://my-domain.com
でアクセス可能な状態
概要
difyではcertbotを使ったSSL化がサポートされているので、公式手順に従います。
手順
上記のREADMEを参考に。
環境変数設定
dify/docker/.env
の以下を確認もしくは設定:
# 取得する証明書ファイル名(nginx コンテナ内で参照)
NGINX_SSL_CERT_FILENAME=fullchain.pem # これじゃないとダメ
NGINX_SSL_CERT_KEY_FILENAME=privkey.pem # これじゃないとダメ
# certbot 用チャレンジを有効化
NGINX_ENABLE_CERTBOT_CHALLENGE=true
# Let’s Encrypt 用ドメイン/連絡先メール
CERTBOT_DOMAIN=your_domain.com
CERTBOT_EMAIL=example@your_domain.com
SSL証明書の取得
# アプリを停止
sudo docker compose down
# 古いネットワークをクリア
sudo docker network prune
# Certbot プロファイルでコンテナ起動
sudo docker compose --profile certbot up --force-recreate -d
# 証明書発行スクリプト実行
sudo docker compose exec -it certbot /bin/sh /update-cert.sh
HTTPS(nginx)の有効化
dify/docker/.env
の以下を設定:
NGINX_HTTPS_ENABLED=true
# nginx コンテナのみ再生成して起動
sudo docker compose --profile certbot up -d --no-deps --force-recreate nginx
https:// でアクセスして確認。
自動更新設定
dify/docker/renew-cert.sh
を作成:
#!/usr/bin/env bash
set -e
# プロジェクトディレクトリに移動
cd <プロジェクトルート>/dify/docker
# certbot コンテナで証明書更新(TTY が不要なので -T)
sudo docker compose exec -T certbot sh /update-cert.sh
# nginx コンテナにリロード命令
sudo docker compose exec nginx nginx -s reload
実行権限を与える
chmod +x renew-cert.sh
cronへの登録
sudo crontab -e
で、以下のような設定をする(15日に1回、20:00の場合)
0 20 */15 * * <プロジェクトルート>/dify/docker/renew-cert.sh >> /var/log/renew-cert.log 2>&1
一応sudo <プロジェクトルート>/dify/docker/renew-cert.sh
で動くことを確認しておく。
certbotは、期限が90日で、残り30日以下になるとアップデートされるようになるので、それまでは、実行されてもスキップになる。
以下のような感じのログ:
Certificate exists. Attempting to renew...
Saving debug log to /var/log/letsencrypt/letsencrypt.log
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Processing /etc/letsencrypt/renewal/my.domain.com.conf
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Certificate not yet due for renewal
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
The following certificates are not due for renewal yet:
/etc/letsencrypt/live/my.domain.com/fullchain.pem expires on 2025-07-25 (skipped)
No renewals were attempted.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Certificate operation successful
Please ensure to reload Nginx to apply any certificate changes.
2025/04/26 03:10:03 [notice] 32#32: signal process started
Discussion