Cloudflared on Docker Compose

Cloudflared Client on Docker Compose

Spread the love

When you create a Zero Trust tunnel in Cloudflare, the simplest and easiest way to install the tunnel (cloudflared) client on your machine is to run the command Cloudflare provided to you on the Networks -> Tunnels page. Usually it looks like the following (sample for Linux Debian):

curl -L --output cloudflared.deb && \
sudo dpkg -i cloudflared.deb && \
sudo cloudflared service install <your_tunnel_token>

But if you need to run the Cloudflared client as a docker container, the following instruction will help you to make it possible.

Cloudflared Tunnel Login

First you need to generate the Cloudflare Authentication certificate file (cert.pem) and put it somewhere on your host machine (i.e. /data/secrets/cert.pem) so then it could be used for the next (tunnel token –cred-file) command. Run the following commands:

sudo chmod 777 -fR /data/secrets && \
sudo docker run -v /data/secrets:/home/nonroot/.cloudflared cloudflare/cloudflared:latest tunnel login

You will see the URL which you will need to copy and open in your browser and perform Login to your Cloudflare account. Once it’s done, cloudflared client will generate cert.pem file in your docker container folder /home/nonroot/.cloudflared and hence in your mounted host machine folder (in my sample /data/secrets).

Change the permission for your mounted folder (especially if it’s secrets folder):

sudo chmod 644 -fR /data/secrets

Cloudflared Tunnel Credentials

Next step would be to generate the credentials file in JSON (or YAML) format, for this command you will need to mount the folder on your host machine with the cert.pem file to /home/nonroot/.cloudflared folder on docker container, run the following command:

sudo docker run -v /data/secrets:/home/nonroot/.cloudflared cloudflare/cloudflared:latest tunnel token --cred-file /home/nonroot/.cloudflared/cf-tunnel-creds.json <your_tunnel_name>

As a result you should find cf-tunnel-creds.json file in your mounted host machine folder (along with the cert.pem file).

You don’t need cert.pem file anymore so it can be deleted:

sudo rm /data/secrets/cert.pem

Cloudflared Tunnel Client in Docker Compose

Now you should be able to add the following section to your compose.yaml file and run Cloudflared Tunnel Client securely, not exposing your tunnel token in compose.yaml file:

# Your Compose.yaml file
    image: cloudflare/cloudflared:latest
    container_name: cloudflared
    command: tunnel --no-autoupdate run --cred-file /run/secrets/cf-tunnel-creds.json <your_tunnel_name>
      - source: cf-tunnel-creds
        target: cf-tunnel-creds.json
    network_mode: host
    restart: always
    file: /data/secrets/cf-tunnel-creds.json

To run your Cloudflared Docker Container in detached (background) mode – run the following command:

sudo docker compose -f <your_compose_file_path> up -d cloudflared

That’s it. Enjoy!