UbuntuにCloudflaredをインストール
Cloudflare(https://dash.cloudflare.com)にアカウントを持ち、ドメイン(以下ではexample.com
)をアカウントに追加していることを前提としています。
Cloudflared を使用することにより、固定の Public IP を用意したり、ポートを開いたりせずにサイトを公開することが可能です。
インストール
sudo mkdir -p --mode=0755 /usr/share/keyringscurl -fsSL https://pkg.cloudflare.com/cloudflare-main.gpg | sudo tee /usr/share/keyrings/cloudflare-main.gpg >/dev/null
echo "deb [signed-by=/usr/share/keyrings/cloudflare-main.gpg] https://pkg.cloudflare.com/cloudflared any main" | sudo tee /etc/apt/sources.list.d/cloudflared.list
sudo apt-get update && sudo apt-get install cloudflared
認証
sudo cloudflared tunnel login
Please open the following URL and log in with your Cloudflare account:
https://dash.cloudflare.com/argotunnel?aud=&callback=https%3A%2F%2Flogin.cloudflareaccess.org%2FXXXXXXXXXXXX%3D
Leave cloudflared running to download the cert automatically.20XX-XX-XXTXX:XX:XXZ INF You have successfully logged in.If you wish to copy your credentials to a server, they have been saved to:/root/.cloudflared/cert.pem
設定
sudo cloudflared tunnel create your-tunnel-service
出力から ID(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
)を得られます。
Tunnel credentials written to /root/.cloudflared/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.json. cloudflared chose this file based on where your origin certificate was found. Keep this file secret. To revoke these credentials, delete the tunnel.
Created tunnel your-tunnel-service with id xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
以下でも ID を確認可能です。
sudo cloudflared tunnel list
/etc/cloudflared/config.yml
を編集します。
tunnel: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxcredentials-file: /root/.cloudflared/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.json
ingress: - hostname: example.com service: http://localhost:80 - hostname: api.example.com service: http://localhost:8888 - service: http_status:404
上記では、http://localhost:80
をexample.com
として、http://localhost:8888
をapi.example.com
として公開しています。
以下のコマンドで、上記の ingress ルールを検証します。
sudo cloudflared tunnel ingress validate
Validating rules from /etc/cloudflared/config.ymlOK
DNS 設定
sudo cloudflared tunnel route dns your-tunnel-service example.comsudo cloudflared tunnel route dns your-tunnel-service api.example.com
実行
sudo cloudflared tunnel run your-tunnel-service
サービス
sudo cloudflared service installsudo systemctl start cloudflared
設定変更後
sudo systemctl restart cloudflared