Some of us use dynamic IPs at home and want to serve a web server, a security cam or a VPN server at home. IP addresses keep changing on connection resets or power cuts. This is a big problem and we should update DNS records according to the changes.

I personally use CloudFlare DNS services for almost anything related to my servers and I want the CF to keep protecting my home servers as well. I thought I could write a tool which checks current machine’s IP address and the IP address defined at CloudFlare, then updates CloudFlare DNS’s A record if both addresses do not match.

What you need?

  • A Linux distro running a SystemD as init system(I am using Ubuntu 16.04)
  • A CloudFlare account
  • Ruby or Docker installed on your server

I prefer the Docker way to run applications on my Linux servers because, neither I want to pollute my servers with different versions of software nor mutate the current states of the servers. Anyway, you can install latest Ruby version and run the application as you wish.

I wrote a small CloudFlare API Client in order to purge caches programmatically for a while ago, I used it as a base for my project. I admit that, it is a bit dirty code, but it works like a charm.

Code

For the code you can visit. https://github.com/turhn/cloudflare-client

git clone https://github.com/turhn/cloudflare-client.git`
cd cloudflare-client
docker build -t cloudflare .

And create a file at /etc/systemd/system/docker-dns and paste the content below. (Do not forget to change and sections.)

[Unit]
Description=Docker Application Service
Requires=docker.service
After=docker.service

[Service]
Restart=always
ExecStart=/usr/bin/docker run --rm -e "CLOUD_FLARE_API_KEY=<API KEY>" -e "CLOUD_FLARE_EMAIL=<EMAIL>" --name cloudflare cloudflare:latest bin/update_dns example.com test
ExecStop=/usr/bin/docker stop -t 2 cloudflare
ExecStopPost=/usr/bin/docker rm -f cloudflare

[Install]
WantedBy=default.target
sudo systemctl daemon-reload
sudo systemctl enable docker-dns
sudo service start docker-dns

Thus you created a system service that is running in the background.

When we check the Docker processes with docker ps, we should see that our service is running. By default, it should check IP addresses every minute. If you wish to change the default interval value, i.e. you can add -e INTERVAL=120 variable in ExecStart section for 120 seconds.

You can easily create an upstart script for upstart using distros.

I hope this helps you.