This guide explains how to set up dynamic DNS with Cloudflare using Bash inside a Docker container. Before you start, you need to have a domain name that's set up to use Cloudflare's nameservers.
- Prerequisites
- Create a Subdomain
- Set Up the .env File
- Create the API Token
- Obtain Necessary Information
- Docker Setup
- A domain name set up to use Cloudflare's nameservers.
- Docker installed on your server.
- Log in to your Cloudflare account and select your domain.
- Go to the DNS settings.
- Click "Add Record".
- Choose "A" as the type.
- Enter your desired subdomain in the "Name" field.
- Enter your current public IP address in the "IPv4 address" field.
- Save the record.
Create a .env file to store your ZONE_ID, RECORD_ID, EMAIL, and API_TOKEN. Your file should look like this:
ZONE_ID=your_zone_id
RECORD_ID=your_record_id
EMAIL=your_email
API_KEY=your_api_token
SUBDOMAIN=your_subdomain
In order to run the docker container you need to gatter some information and save them in the .env file.
- Log in to your Cloudflare account.
- Go to the "My Profile" page.
- Click on "API Tokens".
- Click on "Create Token".
- From here, you can use a template or create a custom token. For updating DNS records, you could use the "Edit Zone DNS" template.
- To get the record ID your token need to have "Read Zone DNS" permission too, you can enable it while configuring this script them remove the permission later.
- Select the specific zone (your domain) you want this token to have access to.
- Once you've set all the permissions, click "Continue to Summary", and then "Create Token".
- You'll then see the token once, and this is the only time you'll see it. Make sure to copy it somewhere safe. If you lose it, you'll have to create a new token.
The Zone ID is on the right-hand side of the overview page, at the bottom of the API section.
The Record ID is not visible in the Cloudflare dashboard. You will need to retrieve it via the Cloudflare API. Use the following curl
command, replacing <email>
, <api_key>
, and <zone_id>
with your actual email, API key, and Zone ID:
Without two auth factor enabled:
curl -X GET "https://api.cloudflare.com/client/v4/zones/<zone_id>/dns_records" \
-H "X-Auth-Email: <email>" \
-H "X-Auth-Key: <api_key>" \
-H "Content-Type: application/json"
With two auth factor enabled:
curl -X GET "https://api.cloudflare.com/client/v4/zones/<zone_id>/dns_records" \
-H "Authorization: Bearer <api_token>" \
-H "Content-Type: application/json"
This command will return a list of all DNS records for the zone. Find your DNS record in the list and note down its id - this is the Record ID.
| If you want a better experience searching / reading JSON output in a CLI we recommand the usage of jq