1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

cloudflareコンテナのみでトンネルを構成しサービスを公開する

Last updated at Posted at 2025-12-06

cloudflare公式イメージのコンテナ内コマンドのみでトンネルを構成します。ここでの目標は:

  • ホストにCloudflareデーモンをインストールしない。
  • CloudflareのWeb UIを使わない。
  • コンテナ内のサービスを外部から見えるようにする。

あらかじめ、コマンドで作成するCloudflaredトンネル名、デプロイするサービスのホスト名を決めます。今回は、vm-test-dwhoami.example.net で行きます。

作業の結果、ホストのディレクトリは次のようになります。

  • /etc/cloudflared:資格情報;cert.pem<tunnel_id>.json
  • ~/stacks/cloudflared:トンネル構成;compose.yamlconfigs/config.yml

方法は、次の通りです。対話的に進めてください。

sudo -i bash
mkdir -p /etc/cloudflared

# URLを開きcloudflareからcert.pemを受け取る
docker run --rm -it \
  --name cloudflared \
  --user 0:0 \
  -v /etc/cloudflared:/root/.cloudflared \
  cloudflare/cloudflared:latest \
  login

# 証明書を使いトンネルを作成。jsonが生成
docker run --rm -it \
  --name cloudflared \
  --user 0:0 \
  -v /etc/cloudflared:/root/.cloudflared \
  cloudflare/cloudflared:latest \
  tunnel create "vm-test-d"
  
# DNSレコードを登録
hostname=whoami.example.net
docker run --rm -it \
  --name cloudflared \
  --user 0:0 \
  -v /etc/cloudflared:/root/.cloudflared \
  cloudflare/cloudflared:latest \
  tunnel route dns $(basename /etc/cloudflared/*.json .json) $hostname

# Cloudflaredのルーティングを構成
mkdir -p ~/stacks/cloudflared/configs
cd ~/stacks/cloudflared
cat << EOF > configs/config.yml 
tunnel: $(basename /etc/cloudflared/*.json .json)
credentials-file: $(ls /etc/cloudflared/*.json)
ingress:
  - hostname: $hostname
    service: http://whoami:80
  - service: http_status:404
EOF

# composeファイルを作成
cat << EOF > compose.yaml 
name: cloudflared
services:
  cloudflared:
    container_name: cloudflared
    image: cloudflare/cloudflared:latest
    user: "0:0"
    command: tunnel --config /etc/cloudflared/config.yml run
    restart: unless-stopped
    volumes:
      - /etc/cloudflared:/etc/cloudflared
      - ./configs/config.yml:/etc/cloudflared/config.yml:ro
    networks:
      - br
  whoami:
    image: traefik/whoami:latest
    container_name: whoami
    expose: [80]
    networks:
      - br
networks:
  br: {}
EOF

# コンテナを起動し、ブラウザでwhoami.example.netにアクセス。
docker compose up

公開したいサービスを追加したい場合は、DNSレコードを登録し、config.ymlにhostnameとserviceを追加するだけです。

config.ymlの最後にservice: http_status:404を忘れないでください。コンテナの再起動も忘れないでください。

以上です。ありがとうございました。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?