Back
Featured image of post Expose the Raspberry Pi to Internet with Cloudflare

Expose the Raspberry Pi to Internet with Cloudflare

Configuring DDNS with Cloudflare: learn how to get and configure dynamic domain names using Cloudflare as primary DNS provider and resolver.

Table of Content

Many of us who have a Raspberry Pi want to have access to it even from outside our network. Some use it to publish their blog or personal web page, others want to access a torrent server from which they can add downloads when they are not at home so that they are available when they arrive, and for others it could be a gateway to their entire home automation system, being able to control and monitor the status of their home when they are not at home.

If for any of these or other reasons you want your Raspberry Pi to be accessible from the Internet, I am sure you will find this post very useful.

The steps to access the Raspberry Pi remotely are not too complicated. In most cases we simply have to access the router or the portal that our operator provides us to “tinker” with its configuration and redirect the ports we need to the internal IP of our Raspberry.

Introducing Cloudflare

The online platform Cloudflare does a lot of things that can be useful in different situations (and besides, most of its features are free). Today in this article, we are going to focus on one of them: Cloudflare acting as a DNS server.

As you know, the Internet uses the so-called IPs as addresses of everything connected to it, but when we enter, for example, https://curiousstuff.eu, we do not put any IP in the browser bar, but we type an address. This is due to an invisible “help” that makes the Internet more “human”: the DNS.

Without going into technical “stuff”, we can say that DNS are servers that “know” in which address other servers are located, converting addresses written with alphabet (easier to read and remember for people) in IPs. So, for example, in the case of writing http://google.es in our browser, thanks to the DNS server, we would actually be accessing something like 142.250.74.227.

1
ping google.es
1
2
3
4
5
6
PING google.es (142.250.74.227) 56(84) bytes of data.
64 bytes from par10s40-in-f3.1e100.net (142.250.74.227): icmp_seq=1 ttl=114 time=33.8 ms
^C
--- google.es ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 33.880/33.880/33.880/0.000 ms

Did you notice that ping shows the IP 142.250.74.227 as the IP resolved for google.es?

That is! a DNS uses a kind of conversion table to go from URLs to IPs and CloudFlare allows us, for free, to make these conversions.

Issues of home networking

However, we encounter two problems:

  • In our house, almost 100% of the time we have a dynamic IP, that is, it changes over time and therefore we can not assign in that table of conversions.

  • We do not have a domain. The .com or .es or any other tld domains are paid and their price varies between providers but we can set at 12€ the average annual price of a .com domain.

On this last point, there are free alternatives for the user, so that some well-known companies give us for free a subdomain that is part of their own domain. I, for example, have used a lot noip.com, from where we can create a free subdomain such as rpi-homeland.hopto.org. This option is fine if you don’t have a domain already and you can’t get one, but it has the disadvantage that you will have to renew it every $N$ days (I think I remember it was every month) which in the long run becomes quite tedious.

Having a domain is better

So purchase one and then keep reading. Once we have purchased a domain, we have to point it to our home IP, which is dynamic and therefore changeable. This is where we have to use Clouflare and do a little magic ;).

Configuring Cloudflare as our DDNS

Step 1: define your subdomain in Cloudflare

We log into our Cloudflare account and go to Domains tab. You should see something similar to below image, for your brand new added domain in Cloudflare.

Cloudflare DNS Record registration using dashboard.
Cloudflare DNS Record registration using dashboard.

In the DNS tab click on add an A-record for our current home IP (remember that we are talking about the public IP, i.e. the IP that the router has facing the Internet). You can easily find it out through your Router management website or ISP provider

Note: if you don’t know the IP, just put a valid IPv4 in the field, for example: 185.199.111.153. We’ll take care later in the update process of setting the right value.

Step 2: Obtain a secret token to use Cloudflare v4 API

Once the subdomain is defined, we need to get a token in order to make authenticated API calls. To get this token you must go to Account > Settings > API Tokens. The tab content should be similar to

  1. Now click on Create New Token button

API Tokens tab
API Tokens tab

As you can see, Cloudflare already provides some common used token templates. In this scenario, we can use the template called:

  • Spanish Name: Editar zona de DNS
  • English Name: Edit DNS zone
  1. Use template Edit DNS zone

API Tokens tab
API Tokens tab

Follow the process until you get your token and store it securely. For security reasons, cloudflare will only show you the token once.

Step 3: Log into your Raspberry PI

Using the Cloudflare API, we are going to update this value automatically so that it is always up to date. To do this, we access our Raspberry via SSH in order to get a session.

This is a required step, in order to execute following steps.

Usually, to log in, you should use a command like

1
ssh pi@rpi.local

In the previous command, pi is the username you defined and rpi.local is the device name. you can also use the IP address to log in, of course.

Step 4: Download a Cloudflare DDNS updater

Download a DDNS updater in order to report the active device IP to Cloudflare.

Note: source code of DDNS updater can be found at https://github.com/zerjioang/ddns-cloudflare

1
2
3
4
5
cd /opt
wget https://github.com/zerjioang/ddns-cloudflare/releases/download/0.3.1/ddns-cloudflare_0.3.1_Linux_$(arch).tar.gz
tar -xf ddns-cloudflare_0.3.1_Linux_$(arch).tar.gz --one-top-level
rm -rf ddns-cloudflare_0.3.1_Linux_$(arch).tar.gz
cd ddns-cloudflare_0.3.1_Linux_$(arch)/bin/

After executing previous commands, you should have a DDNS updater ready to be used and installed in your raspberry pi. Check the application exists with ls command.

1
2
total 6,1M
-rwxr-xr-x 1 root root 6,1M oct 21 16:29 ddns-cloudflare

Configure the DDNS-Updater

In order to update your specific DNS record of your registered DNS domain, there are some things you need to configure. In this example, the 3 environment variables used by the ddns-updater are persisted to $HOME/.bashrc so that all session can have available those variables with their right content.

To write variable content to our .bashrc file

1
2
3
echo 'export X_CF_AGENT_TOKEN=yourtoken' >> $HOME/.bashrc
echo 'export X_CF_AGENT_ZONE=example.com' >> $HOME/.bashrc
echo 'export X_CF_AGENT_DNS_A_RECORD=rpi' >> $HOME/.bashrc

to launch the DDNS updater

1
/opt/ddns-cloudflare/bin/ddns-cloudflare update

Previous command will try to update the DNS A Record of rpi.example.com with the host actual public IP

Adding a cron job

In order to refresh the current device IP every specific time window, we can use crontab for example.

Access to your cron file with crontab -e and add the following content. For example, in order to update the device IP eery 10 minutes you need to add

1
2
# run a Cloudflare DDNS updater each 10 minutes
*/10 * * * * /opt/ddns-cloudflare/bin/ddns-cloudflare update

You can verify the content of the crontab file with crontab -l. Your new crontab file should look like

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# Edit this file to introduce tasks to be run by cron.
# 
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
# 
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').
# 
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
# 
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
# 
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
# 
# For more information see the manual pages of crontab(5) and cron(8)
# 
# m h  dom mon dow   command

# run a Cloudflare DDNS updater each 10 minutes
*/10 * * * * /opt/ddns-cloudflare/bin/ddns-cloudflare update

I need to understand better how crontab settings are configured, I recommend you to use https://crontab.guru/ if you want to easily learn how to configure the crontab timing.

A success execution

If everything went like planned, a success execution should generate following logs.

1
2
3
4
5
6
7
8
9
2021/10/21 20:23:17 Updating device IP. Please wait...
2021/10/21 20:23:17 Requesting IP check for:  rpi.curiousstuff.eu
2021/10/21 20:23:17 Reading current device IP. Please wait...
2021/10/21 20:23:17 Readed IP:  A.B.C.D
2021/10/21 20:23:17 Connecting with Cloudflare services...
2021/10/21 20:23:19 Cloudflare ZONE ID:  705614125y14y234724565285723
2021/10/21 20:23:20 Cloudflare DNS RECORD found:  1 records
2021/10/21 20:23:20 Update successful
2021/10/21 20:23:20 cloudflare DDNS-updater took 2.478195385s

After a success execution, you can go to your CloudFlare user dashboard and verify that the IP has indeed been updated.

Conclusion

And now we have ready, and permanently, an address to point from the Internet to our router, which in turn, it will be redirecting the traffic to our Raspberry if we have configured it well.

I hope this post has been useful. Now you can easily access your music, your printer or your devices taking advantage of your domain and, if you have followed these steps, it will not have taken you more than 10 minutes all the configuration.



💬 Share this post in social media

Thanks for checking this out and I hope you found the info useful! If you have any questions, don't hesitate to write me a comment below. And remember that if you like to see more content on, just let me know it and share this post with your colleges, co-workers, FFF, etc.

You are free to use the content, but mention the author (@MrSergioAnguita) and link the post!
Last updated on Oct 21, 2021 20:59 CEST
Please, don't try to hack this website servers. Guess why...