> For the complete documentation index, see [llms.txt](https://doc.anyhk.net/anyhk/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://doc.anyhk.net/anyhk/ddns/zi-jian-ddns-shuo-ming-cloudflare.md).

# 自建DDNS說明-Cloudflare

## 由於網路安全原因，我們停止了免費域名（DDNS）的解析，但用戶仍然可以通過自建DDNS獲取伺服器的外網IP。

## 下面我們將使用您的自有域名通過Cloudflare API及時獲得VPS的公網IP

{% hint style="info" %}
前提條件：

* 自有域名
* 域名已接入Cloudflare
  {% endhint %}

## 1.獲取Global API Key

登入Clooudflare查看：<https://dash.cloudflare.com/profile/api-tokens>

![](/files/tNEYpJyydk03PUC9rcmr)

## 2.設置DDNS域名

在Cloudflare DNS面板中新建 A 記錄，例如 myddns 指向 1.1.1.1 並關閉CF代理開關讓雲朵灰色。

![](/files/0QLCqmnXDLdhiRZOylqx)

## 3.下載cf-ddns腳本

```
wget  -N --no-check-certificate https://raw.githubusercontent.com/yulewang/cloudflare-api-v4-ddns/master/cf-v4-ddns.sh
```

## 4.編輯cf-ddns腳本

```
vi cf-v4-ddns.sh

或者

nano cf-v4-ddns.sh
```

在腳本中填入您的信息

```
# API key, see https://www.cloudflare.com/a/account/my-account,
# incorrect api-key results in E_UNAUTH error
CFKEY=您的Global API Key

# Username, eg: user@example.com
CFUSER=您Cloudflare的賬戶名稱

# Zone name, eg: example.com
CFZONE_NAME=您的域名

# Hostname to update, eg: homeserver.example.com
CFRECORD_NAME=您的二級域名，就是剛剛新建的那個
```

保存並退出編輯界面

## 5.修改cf-ddns腳本權限

```
chmod +x cf-v4-ddns.sh
```

## 6.測試運行腳本

```
./cf-v4-ddns.sh

##如果上面的步驟無誤，您會看到Cloudflare DNS面板中。
##剛才您新建的 A 記錄IP已更新為VPS的公網IP
```

## 7.設定定時任務自動更新ddns的IP

```
crontab -e

##有些系統會提示讓您選擇vi或nano編輯定時腳本，選擇您熟悉的編輯工具即可
##插入下面一下，表示每分鐘更新ddns
*/1 * * * * /root/cf-v4-ddns.sh >/dev/null 2>&1
```

{% hint style="success" %}
打完收工
{% endhint %}
