Create a Tunnel with the name provided and associate it with a UUID. The relationship between the UUID and the name is persistent. The command will not create a connection at this point.
The created Tunnel can serve traffic for multiple hostnames in your Cloudflare account and send traffic to multiple services available to cloudflared, including SSH, RDP, and most arbitrary TCP connections.
Query Postgres from Workers using a database connector. Retrieve data in your Cloudflare Workers applications from a PostgreSQL database using Postgres database connector
Set up a tunnel locally (CLI setup)
1.Downloadandinstallcloudflared
.debinstall
.rpminstall2.Authenticatecloudflared3.Createatunnelandgiveitaname4.Createaconfigurationfile5.Startroutingtraffic6.Runthetunnel7.Checkthetunnel1.Overview2.Basicprojectscaffolding3.CloudflareTunnelauthentication4.StartandpreparePostgresdatabase4.1. StartthePostgresserver4.2. Importexampledataset5.EditWorkerandqueryPagiladataset5.1. Databaseconnectionsettings5.2. QueryPagiladataset6.Workerdeployment6.1. Setsecrets6.2. TesttheWorker7.Cleanuphttps://github.com/coding-to-music/postgres-cloudflare-docker
By Cloudflare Documentation
gitinitgitadd .
gitremoteremoveorigingitcommit -m"first commit"gitbranch -Mmaingitremoteaddorigingit@github.com:coding-to-music/postgres-cloudflare-docker.gitgitpush -uoriginmaincloudflared will automatically look for a config.yaml or config.yml file in the default cloudflared directory .
You can give your configuration file a custom name and store it in any directory. However, when running tunnel, make sure to add the --config flag and specify the new path.
cloudflaredtunnel --config /path/your-config-file.yamlruntunnel-namehttps://dev.to/realchaika/how-to-setup-a-cloudflare-tunnel-on-linux-40d9
Cloudflare Tunnels use Cloudflared, a tunneling daemon to proxy the traffic from Cloudflare, and also to provide a CLI interface to make and manage tunnels.
wget -qhttps://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64.deb && sudo dpkg -i cloudflared-linux-amd64.debwget -qhttps://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-x86_64.rpm && sudo rpm -i cloudflared-linux-x86_64.rpm cloudflaredtunnelloginThis command should give you the link to sign into Cloudflare, and select a zone (website) to create tunnels on.
When done, it will download an account certificate (cert.pem file in the default cloudflared directory). This cert will be used to authorize future API Requests to create and manage tunnels. Once your tunnel is up and running, it will use its own credentials file, and you can safely delete this unless you want to keep managing/creating/deleting tunnels from this machine.
cloudflaredtunnelcreate <name>This command will create a named tunnel based on the name entered. It will generate a new tunnel, this includes generating a UUID for the tunnel, a tunnel credentials file in the default cloudflared directory, and a subdomain of .cfargotunnel.com that you can use to route requests to.
In this example, I'll be naming my tunnel "frontpage".
Throughout the past two steps, after logging in and creating the account cert, and making a tunnel, generating the tunnel cert, cloudflared has listed the path to your .cloudflared directory, which is most likely based off your home directory.
Somethinglike"~/.cloudflared"or"/home/{username}/.cloudflared"Navigate to that folder now. You should see cert.pem (your account cert) and a .json file named off the UUID of your tunnel.
Create a new file in the same directory, config.yml, and open it using your preferred text editor.
url: http://localhost:80tunnel: <Tunnel-UUID>
credentials-file: /home/{username}/.cloudflared/<Tunnel-UUID>.jsonThe URL line corresponds to the internal service you wish to expose. It's not necessary to use https://, the connection between Cloudflare Tunnel and Cloudflare's datacenter is already encrypted. This is just the tunnel connecting locally to the web server.
The Tunnel UUID is a 36 character value that corresponds with your named tunnel. It was displayed when you made the tunnel. You can also find it by going to your .cloudflared directory and looking for the newly created json credentials file for the tunnel you made. It should be named {Tunnel-UUID}.json.
You just create a CNAME Record to route traffic to your tunnel. You can do so easily using the cloudflared cli
cloudflaredtunnelroutedns <TunnelUUIDorName> <Hostname>For example, my tunnel is named frontpage and I wanted it to be accessible via example.chaika.dev. So
I did
cloudflaredtunnelroutednsfrontpageexample.chaika.devFinally, you can test out your tunnel.
cloudflaredtunnelrun <UUIDorName>You can also specify a specific configuration file to run
cloudflaredtunnel --configpath/config.yamlrunOnce your tunnel is live, try accessing it via the hostname you routed it to. It may take a few seconds for the tunnel to be fully live/accessible. If something is wrong, the tunnel running in the CLI should tell you more information about errors.
Running your tunnel manually will work, but isn't the best. It won't automatically start if your machine reboots, have to ensure its open/running, etc.
Luckily, cloudflared supports installing itself as a service very easily.
sudocloudflaredserviceinstallYou may need to manually specify config location. In my case, I did have to specify it.
For example,
sudocloudflared --config /home/{username}/.cloudflared/config.ymlserviceinstallNote that you specify the config argument before the 'service install' command parameters.
The configuration will be copied over to /etc/cloudflared
I would recommend copying over the tunnel credentials file ({Tunnel-UUID}.json) over to there as well.
Then, just launch the service and set it to start on boot
sudosystemctlenablecloudflaredsudosystemctlstartcloudflaredEnsure your tunnel started/is running fine:
sudosystemctlstatuscloudflaredTest out your tunnel by visting the hostname you routed it to.
https://gist.github.com/joejordanbrown/b63f82a298da208a5e4780c2200af8fb
- https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup
- https://hub.docker.com/r/cloudflare/cloudflared
- https://github.com/cloudflare/cloudflared/
- Authenticate with Cloudflare -> cloudflared tunnel login
sudo docker run -it --rm --name=cloudflared -v /root/.cloudflared:/home/nonroot/.cloudflared cloudflare/cloudflared:2022.2.0 tunnel login- Create tunnel -> cloudflared tunnel create
<tunnel-name>
sudo docker run -it --rm --name=cloudflared -v /root/.cloudflared:/home/nonroot/.cloudflared cloudflare/cloudflared:2022.2.0 tunnel create example-tunnel- Add DNS route internal.example.com to tunnel -> cloudflared tunnel route dns
<tunnel-name><route-hostname>
sudo docker run -it --rm --name=cloudflared -v /root/.cloudflared:/home/nonroot/.cloudflared cloudflare/cloudflared:2022.2.0 tunnel route dns example-tunnel internal.example.com- Add DNS route app1.example.com to tunnel -> cloudflared tunnel route dns
<tunnel-name><route-hostname>
sudo docker run -it --rm --name=cloudflared -v /root/.cloudflared:/home/nonroot/.cloudflared cloudflare/cloudflared:2022.2.0 tunnel route dns example-tunnel app1.example.com- Run tunnel in detached docker container -> cloudflared tunnel run
sudo docker run -it --rm --name=cloudflared --network="host" -d -v /root/.cloudflared:/home/nonroot/.cloudflared cloudflare/cloudflared:2022.2.0 tunnel run/root/.cloudflared/config.yml
tunnel: *******************credentials-file: /root/.cloudflared/***-*-*-*-****.jsoningress:
- hostname: internal.example.comservice: https://127.0.0.1:8443originRequest:
noTLSVerify: true
- hostname: app1.example.comservice: http://192.168.1.10:8990
- service: http_status:404References this article: https://ilayk.com/2021/03/25/cloudflared
TheDockerdocsshouldalsocovertheconfig.ymlmore.
Forthoseofyouwhostumbleaccrossthisissueinthefuture, hereismyDockerclicommandforcreatingthecontainer. Notethatyouwillhavetotunnelloginandtunnelcreatetunnel_name_herebeforerunningthetunnel.
Command:
dockerrun -d \
--namecloudflared \
-v ~/.config/cloudflared:/home/nonroot/.cloudflared/ \
cloudflare/cloudflared:2021.11.0-amd64 \
tunnelrunubuntuconfig.ymltunnel: tunnel_id_goes_here # outputtoterminal when runningtunnellogincredentials-file: /home/nonroot/.cloudflared/credential_file_here.jsoningress:
- hostname: mywebsite.com # yourdomaingoeshereservice: http://localhost:8080 # service you want to expose
- service: http://localhost:404 # backup service that will return 404 error from CloudflareAnother example of a config.yml
tunnel: TunnelIDcredentials-file: /home/leon/.cloudflared/TunnelID.jsoningress:
- hostname: leonnunes.devservice: http://localhost:8080
#Catch-allrule, whichjustrespondswith404iftrafficdoesn't match any of
# # theearlierrules
- service: http_status:404NAME:
cloudflaredtunnel - UseCloudflareTunneltoexposeprivateservicestotheInternetortoCloudflareconnectedprivateusers.
USAGE:
cloudflaredtunnelcommand [commandoptions] DESCRIPTION:
CloudflareTunnelallowstoexposeprivateserviceswithoutopeninganyingressportonthismachine. Itcanexpose:
A) LocallyreachableHTTP-basedprivateservicestotheInternetonDNSwithCloudflareasauthority (whichyoucanthenprotectwithCloudflareAccess).
B) LocallyreachableTCP/UDP-basedprivateservicestoCloudflareconnectedprivateusersinthesameaccount, e.g.,
thoseenrolledtoaZeroTrustWARPClient.
YoucanmanageyourTunnelsviadash.teams.cloudflare.com. ThisapproachwillonlyrequireyoutorunasinglecommandlaterineachmachinewhereyouwishtorunaTunnel.
Alternatively, youcanmanageyourTunnelsviathecommandline. Beginbyobtainingacertificatetobeabletodoso:
$cloudflaredtunnelloginWithyourcertificateinstalledyoucanthengetstartedwithTunnels:
$cloudflaredtunnelcreatemy-first-tunnel$cloudflaredtunnelroutednsmy-first-tunnelmy-first-tunnel.mydomain.com$cloudflaredtunnelrun --hello-worldmy-first-tunnelYoucannowaccessmy-first-tunnel.mydomain.comandbeservedanexamplepagebyyourlocalcloudflaredprocess.
ForexposinglocalTCP/UDPservicesbyIPtoyourprivatelyconnectedusers, checkout:
$cloudflaredtunnelrouteip --helpSeehttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/tunnel-guide/ for more info.COMMANDS:
loginGenerateaconfigurationfilewithyourlogindetailscreateCreateanewtunnelwithgivennamerouteDefinewhichtrafficroutedfromCloudflareedgetothistunnel: requeststoaDNShostname, toaCloudflareLoadBalancer, ortrafficoriginatingfromCloudflareWARPclientsvnetConfigureandqueryvirtualnetworkstomanageprivateIProuteswithoverlappingIPs.
runProxyalocalwebserverbyrunningthegiventunnellistListexistingtunnelsinfoListdetailsabouttheactiveconnectorsforatunneldeleteDeleteexistingtunnelbyUUIDornamecleanupCleanuptunnelconnectionstokenFetchthecredentialstokenforanexistingtunnel (bynameorUUID) thatallowstorunithelp, hShowsalistofcommandsorhelpforonecommandOPTIONS:
--configvalueSpecifiesaconfigfileinYAMLformat.
--origincertvaluePathtothecertificategeneratedforyourorigin when youruncloudflaredlogin. [$TUNNEL_ORIGIN_CERT]
--autoupdate-freqvalueAutoupdatefrequency. Defaultis24h0m0s. (default: 24h0m0s)
--no-autoupdateDisableperiodiccheckforupdates, restartingtheserverwiththenewversion. (default: false) [$NO_AUTOUPDATE]
--metricsvalueListenaddressformetricsreporting. (default: "localhost:") [$TUNNEL_METRICS]
--pidfilevalueWritetheapplication's PID to this file after first successful connection. [$TUNNEL_PIDFILE]
--urlURLConnecttothelocalwebserveratURL. (default: "http://localhost:8080") [$TUNNEL_URL]
--hello-worldRunHelloWorldServer (default: false) [$TUNNEL_HELLO_WORLD]
--socks5 --urlspecifyifthistunnelisrunningasaSOCK5ServerThisflagonlytakeseffectifyoudefineyouroriginwith --urlandifyoudonotuseingressrules. Therecommendedwayistorelyoningressrulesanddefinethispropertyunder `originRequest` asperhttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/configuration/configuration-file/ingress (default: false) [$TUNNEL_SOCKS]
--proxy-connect-timeout --urlHTTPproxytimeoutforestablishinganewconnectionThisflagonlytakeseffectifyoudefineyouroriginwith --urlandifyoudonotuseingressrules. Therecommendedwayistorelyoningressrulesanddefinethispropertyunder `originRequest` asperhttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/configuration/configuration-file/ingress (default: 30s)
--proxy-tls-timeout --urlHTTPproxytimeoutforcompletingaTLShandshakeThisflagonlytakeseffectifyoudefineyouroriginwith --urlandifyoudonotuseingressrules. Therecommendedwayistorelyoningressrulesanddefinethispropertyunder `originRequest` asperhttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/configuration/configuration-file/ingress (default: 10s)
--proxy-tcp-keepalive --urlHTTPproxyTCPkeepalivedurationThisflagonlytakeseffectifyoudefineyouroriginwith --urlandifyoudonotuseingressrules. Therecommendedwayistorelyoningressrulesanddefinethispropertyunder `originRequest` asperhttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/configuration/configuration-file/ingress (default: 30s)
--proxy-no-happy-eyeballs --urlHTTPproxyshoulddisable"happy eyeballs"forIPv4/v6fallbackThisflagonlytakeseffectifyoudefineyouroriginwith --urlandifyoudonotuseingressrules. Therecommendedwayistorelyoningressrulesanddefinethispropertyunder `originRequest` asperhttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/configuration/configuration-file/ingress (default: false)
--proxy-keepalive-connections --urlHTTPproxymaximumkeepaliveconnectionpoolsizeThisflagonlytakeseffectifyoudefineyouroriginwith --urlandifyoudonotuseingressrules. Therecommendedwayistorelyoningressrulesanddefinethispropertyunder `originRequest` asperhttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/configuration/configuration-file/ingress (default: 100)
--proxy-keepalive-timeout --urlHTTPproxytimeoutforclosinganidleconnectionThisflagonlytakeseffectifyoudefineyouroriginwith --urlandifyoudonotuseingressrules. Therecommendedwayistorelyoningressrulesanddefinethispropertyunder `originRequest` asperhttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/configuration/configuration-file/ingress (default: 1m30s)
--proxy-connection-timeoutvalueDEPRECATED. Nolongerhasanyeffect. (default: 1m30s)
--proxy-expect-continue-timeoutvalueDEPRECATED. Nolongerhasanyeffect. (default: 1m30s)
--http-host-header --urlSetstheHTTPHostheaderforthelocalwebserver. Thisflagonlytakeseffectifyoudefineyouroriginwith --urlandifyoudonotuseingressrules. Therecommendedwayistorelyoningressrulesanddefinethispropertyunder `originRequest` asperhttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/configuration/configuration-file/ingress [$TUNNEL_HTTP_HOST_HEADER]
--origin-server-name --urlHostnameontheoriginservercertificate. Thisflagonlytakeseffectifyoudefineyouroriginwith --urlandifyoudonotuseingressrules. Therecommendedwayistorelyoningressrulesanddefinethispropertyunder `originRequest` asperhttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/configuration/configuration-file/ingress [$TUNNEL_ORIGIN_SERVER_NAME]
--unix-socketvaluePathtounixsockettouseinsteadof --url [$TUNNEL_UNIX_SOCKET]
--origin-ca-pool --urlPathtotheCAforthecertificateofyourorigin. ThisoptionshouldbeusedonlyifyourcertificateisnotsignedbyCloudflare. Thisflagonlytakeseffectifyoudefineyouroriginwith --urlandifyoudonotuseingressrules. Therecommendedwayistorelyoningressrulesanddefinethispropertyunder `originRequest` asperhttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/configuration/configuration-file/ingress [$TUNNEL_ORIGIN_CA_POOL]
--no-tls-verify --urlDisablesTLSverificationofthecertificatepresentedbyyourorigin. Willallowanycertificatefromtheorigintobeaccepted. Note: TheconnectionfromyourmachinetoCloudflare's Edge is still encrypted. This flag only takes effect if you define your origin with --url and if you do not use ingress rules. The recommended way is to rely on ingress rules and define this property under `originRequest` as per https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/configuration/configuration-file/ingress (default: false) [$NO_TLS_VERIFY]
--no-chunked-encoding --urlDisableschunkedtransferencoding; usefulifyouarerunningaWSGIserver. Thisflagonlytakeseffectifyoudefineyouroriginwith --urlandifyoudonotuseingressrules. Therecommendedwayistorelyoningressrulesanddefinethispropertyunder `originRequest` asperhttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/configuration/configuration-file/ingress (default: false) [$TUNNEL_NO_CHUNKED_ENCODING]
--bastionRunsasjumphost (default: false) [$TUNNEL_BASTION]
--proxy-addressvalueListenaddressfortheproxy. (default: "127.0.0.1") [$TUNNEL_PROXY_ADDRESS]
--proxy-portvalueListenportfortheproxy. (default: 0) [$TUNNEL_PROXY_PORT]
--loglevelvalueApplicationlogginglevel {debug, info, warn, error, fatal}. AtdebuglevelcloudflaredwilllogrequestURL, method, protocol, contentlength, aswellas, allrequestandresponseheaders. Thiscanexposesensitiveinformationinyourlogs. (default: "info") [$TUNNEL_LOGLEVEL]
--transport-loglevelvalue, --proto-loglevelvalueTransportlogginglevel(previouslycalledprotocollogginglevel) {debug, info, warn, error, fatal} (default: "info") [$TUNNEL_PROTO_LOGLEVEL, $TUNNEL_TRANSPORT_LOGLEVEL]
--logfilevalueSaveapplicationlogtothisfileforreportingissues. [$TUNNEL_LOGFILE]
--log-directoryvalueSaveapplicationlogtothisdirectoryforreportingissues. [$TUNNEL_LOGDIRECTORY]
--trace-outputvalueNameoftraceoutputfile, generated when cloudflaredstops. [$TUNNEL_TRACE_OUTPUT]
--proxy-dnsRunaDNSoverHTTPSproxyserver. (default: false) [$TUNNEL_DNS]
--proxy-dns-portvalueListenongivenportfortheDNSoverHTTPSproxyserver. (default: 53) [$TUNNEL_DNS_PORT]
--proxy-dns-addressvalueListenaddressfortheDNSoverHTTPSproxyserver. (default: "localhost") [$TUNNEL_DNS_ADDRESS]
--proxy-dns-upstreamvalueUpstreamendpointURL, youcanspecifymultipleendpointsforredundancy. (default: "https://1.1.1.1/dns-query", "https://1.0.0.1/dns-query") (accepts multiple inputs) [$TUNNEL_DNS_UPSTREAM]
--proxy-dns-max-upstream-connsvalueMaximumconcurrentconnectionstoupstream. Settingto0meansunlimited. (default: 5) [$TUNNEL_DNS_MAX_UPSTREAM_CONNS]
--proxy-dns-bootstrapvaluebootstrapendpointURL, youcanspecifymultipleendpointsforredundancy. (default: "https://162.159.36.1/dns-query", "https://162.159.46.1/dns-query", "https://[2606:4700:4700::1111]/dns-query", "https://[2606:4700:4700::1001]/dns-query") (accepts multiple inputs) [$TUNNEL_DNS_BOOTSTRAP]
--credentials-filevalue, --cred-filevalueFilepathatwhichtoread/writethetunnelcredentials [$TUNNEL_CRED_FILE]
--regionvalueCloudflareEdgeregiontoconnectto. Omitorsettoemptytoconnecttotheglobalregion. [$TUNNEL_REGION]
--hostnamevalueSetahostnameonaCloudflarezonetoroutetrafficthroughthistunnel. [$TUNNEL_HOSTNAME]
--lb-poolvalueThenameofa (new/existing) loadbalancingpooltoaddthisoriginto. [$TUNNEL_LB_POOL]
--metrics-update-freqvalueFrequencytoupdatetunnelmetrics (default: 5s) [$TUNNEL_METRICS_UPDATE_FREQ]
--tagKEY=VALUECustomtagsusedtoidentifythistunnel, informatKEY=VALUE. Multipletagsmaybespecified (acceptsmultipleinputs) [$TUNNEL_TAG]
--retriesvalueMaximumnumberofretriesforconnection/protocolerrors. (default: 5) [$TUNNEL_RETRIES]
--grace-periodvalueWhencloudflaredreceivesSIGINT/SIGTERMitwillstopacceptingnewrequests, waitforin-progressrequeststoterminate, thenshutdown. Waitingforin-progressrequestswilltimeoutafterthisgraceperiod, or when asecondSIGTERM/SIGINTisreceived. (default: 30s) [$TUNNEL_GRACE_PERIOD]
--compression-qualityvalue (beta) Usecross-streamcompressioninsteadHTTPcompression. 0-off, 1-low, 2-medium, >=3-high. (default: 0) [$TUNNEL_COMPRESSION_LEVEL]
--namevalue, -nvalueStablenametoidentifythetunnel. Usingthisflagwillcreate, routeandrunatunnel. Forproductionusage, executeeachcommandseparately [$TUNNEL_NAME]
--uiLaunchtunnelUI. Tunnellogsarescrollablevia'j', 'k', orarrowkeys. (default: false)
--overwrite-dns, -fOverwritesexistingDNSrecordswiththishostname (default: false) [$TUNNEL_FORCE_PROVISIONING_DNS]
--help, -hshowhelp (default: false)title: Set up your first tunnel
When setting up your first Cloudflare Tunnel, you have the option to create it:
Before you start, make sure you:
First, download cloudflared on your machine. Visit the downloads page to find the right package for your OS.
Next, install cloudflared.
Use the deb package manager to install cloudflared on compatible machines. amd64 / x86-64 is used in this example.
wget -q https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64.deb && dpkg -i cloudflared-linux-amd64.debUse the rpm package manager to install cloudflared on compatible machines. amd64 / x86-64 is used in this example.
wget -q https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-x86_64.rpmBuild from source
You can also build the latest version of cloudflared from source with the following steps.
git clone https://github.com/cloudflare/cloudflared.git
cd cloudflared
make cloudflared
go install github.com/cloudflare/cloudflared/cmd/cloudflaredDepending on where you installed cloudflared, you can move it to a known path as well.
mv /root/cloudflared/cloudflared /usr/bin/cloudflared{{}}
Review terminology for tunnels setup locally through the CLI.
A tunnel is a secure, outbound-only pathway you can establish between your origin and the Cloudflare edge. Each tunnel you create will be assigned a name and a UUID.
A tunnel UUID is an alphanumeric, unique ID assigned to a tunnel. The tunnel UUID can be used in configuration files, and in general, whenever you need to reference a specific tunnel.
The cloudflared tunnel create <NAME> command creates a tunnel and assigns it a name. Once named, a tunnel is a persistent pathway within which you can stop and start as many connectors as needed, adding stability and ease of use to your tunnel experience. Tunnel names do not need to be hostnames; for example, you can assign your tunnel a name that represents your application/network, a particular server, or the cloud environment where it runs. Just choose any identifier that lets you easily reference a tunnel whenever you need.
You can create and configure a tunnel once and run it as multiple different cloudflared processes. These processes are known as connectors, or replicas. DNS records and Cloudflare Load Balancers can still point to the tunnel and its UUID, while that tunnel sends traffic to the multiple instances of cloudflared that run through it. Using multiple connectors provides tunnels with high availability, scalability, and elasticity.
cloudflared uses a default directory when storing credentials files for your tunnels, as well as the cert.pem file it generates when you run cloudflared login. The default directory is also where cloudflared will look for a configuration file if no other file path is specified when running a tunnel.
| OS | Path to default directory |
|---|---|
| Windows | %USERPROFILE%\.cloudflared |
| MacOS and Unix-like systems | ~/.cloudflared, /etc/cloudflared, and /usr/local/etc/cloudflared, in this order. |
This is a .yaml file that functions as the operating manual for cloudflared. cloudflared will automatically look for the configuration file in the default cloudflared directory, but you can store your configuration file in any directory. It is recommended to always specify the file path for your configuration file whenever you reference it. By creating a configuration file, you can have fine-grained control over how their instance of cloudflared will operate. This includes operations like what you want cloudflared to do with traffic (for example, proxy websockets to port xxxx, or ssh to port yyyy), where cloudflared should search for authorization (credentials file, tunnel token), and what mode it should run in (for example, warp-routing). In the absence of a configuration file, cloudflared will proxy outbound traffic through port 8080. For more information on how to create, store, and structure a configuration file, refer to the dedicated instructions.
Ingress rules let you specify which local services traffic should be proxied to. If a rule does not specify a path, all paths will be matched. Ingress rules can be listed in your configuration file or when running cloudflared tunnel ingress.
This is the certificate file issued by Cloudflare when you run cloudflared tunnel login. This file uses a certificate to authenticate your instance of cloudflared and it is required when you create new tunnels, delete existing tunnels, change DNS records, or configure tunnel routing from cloudflared. This file is not required to perform actions such as running an existing tunnel or managing tunnel routing from the Cloudflare dashboard. Refer to the Tunnel permissions page for more details on when this file is needed.
The cert.pem origin certificate is valid for at least 10 years, and the service token it contains is valid until revoked.
This file is created when you run cloudflared tunnel create <NAME>. It stores your tunnel’s credentials in JSON format, and is unique to each tunnel. This file functions as a token authenticating the tunnel it is associated with. Refer to the Tunnel permissions page for more details on when this file is needed.
Quick tunnels, when run, will generate a URL that consists of a random subdomain of the website trycloudflare.com, and point traffic to localhost on port 8080. If you have a web service running at that address, users who visit the generated subdomain will be able to visit your web service through Cloudflare’s network. Refer to TryCloudflare for more information on how to run quick tunnels.
A software abstraction that allows you to logically segregate resources on your private network. Tunnel Virtual Networks are especially useful for exposing resources which have overlapping IP routes. To connect to a resource, end users would select a virtual network in their WARP client settings before entering the destination IP.
cloudflared tunnel loginRunning this command will:
- Open a browser window and prompt you to log in to your Cloudflare account. After logging in to your account, select your hostname.
- Generate an account certificate, the cert.pem file, in the default
cloudflareddirectory.
cloudflared tunnel create <NAME>Running this command will:
- Create a tunnel by establishing a persistent relationship between the name you provide and a UUID for your tunnel. At this point, no connection is active within the tunnel yet.
- Generate a tunnel credentials file in the default
cloudflareddirectory. - Create a subdomain of
.cfargotunnel.com.
From the output of the command, take note of the tunnel’s UUID and the path to your tunnel’s credentials file.
Confirm that the tunnel has been successfully created by running:
cloudflared tunnel listCreate a configuration file in your .cloudflared directory using any text editor. This file will configure the tunnel to route traffic from a given origin to the hostname of your choice.
Add the following fields to the file:
If you are connecting an application
url: http://localhost:8000
tunnel: <Tunnel-UUID>
credentials-file: /root/.cloudflared/<Tunnel-UUID>.jsonIf you are connecting a network
tunnel: <Tunnel-UUID>
credentials-file: /root/.cloudflared/<Tunnel-UUID>.json
warp-routing:
enabled: trueConfirm that the configuration file has been successfully created by running:
cat config.ymlNow assign a CNAME record that points traffic to your tunnel subdomain.
If you are connecting an application
cloudflared tunnel route dns <UUID or NAME><hostname>If you are connecting a network
Add the IP/CIDR you would like to be routed through the tunnel.
cloudflared tunnel route ip add <IP/CIDR><UUID or NAME>You can confirm that the route has been successfully established by running:
cloudflared tunnel route ip showRun the tunnel to proxy incoming traffic from the tunnel to any number of services running locally on your origin.
cloudflared tunnel run <UUID or NAME>If your configuration file has a custom name or is not in the .cloudflared directory, add the --config flag and specify the path.
cloudflared tunnel --config /path/your-config-file.yaml run{{
}}Cloudflare Tunnel can install itself as a system service on Linux and Windows and as a launch agent on macOS. For more information, refer to Run as a service.
{{
}}Your tunnel configuration is complete! If you want to get information on the tunnel you just created, you can run:
cloudflared tunnel infopcx-content-type: how-to
title: Create a Tunnel
| Before you start |
|---|
| 1. Add a website to Cloudflare |
| 2. Change your domain nameservers to Cloudflare |
3. Install and authenticate cloudflared |
To create a Tunnel, run the following command:
cloudflared tunnel create <NAME>Replace <NAME> with the name you want to give to the Tunnel. The name assigned can be any string and does not need to relate to the hostname where traffic will be served.
This command will create a Tunnel with the name provided and associate it with a UUID. The relationship between the UUID and the name is persistent. The command will not create a connection at this point.
The created Tunnel can serve traffic for multiple hostnames in your Cloudflare account and send traffic to multiple services available to cloudflared, including SSH, RDP, and most arbitrary TCP connections.
Creating a Tunnel generates a credentials file for that specific Tunnel. This file is distinct from the cert.pem file. To run the Tunnel without managing DNS from cloudflared, you only need the credentials file.
{{}}
| Action | cert.pem | Credentials file |
|---|---|---|
| Create a new Tunnel | Required | - |
| Delete a Tunnel | Required | - |
| Run a Tunnel | Available | Required |
| Create DNS records from cloudflared | Required | - |
| Connect to load balancer pools from cloudflared | Required | - |
| Route traffic to a running Tunnel from the Cloudflare dashboard | Available | Available |
{{}}
cloudflared can list all created Tunnels in your account, as well as those actively connected to Cloudflare, by running the following command:
cloudflared tunnel listNote: the command requires the cert.pem file.
You can delete an existing Tunnel with cloudflared. To delete a Tunnel, run the following command:
cloudflared tunnel delete <NAME>{{
}}The command requires the cert.pem file.
{{
}}If there are still active connections on that Tunnel, then you will have to force the deletion with:
cloudflared tunnel delete -f <NAME>This will cause those connections to be dropped.
Deleting the Tunnel also invalidates the credentials file associated with that Tunnel, meaning those connections can not be re-established.
{{
}}Tunnels created in this method do not currently display in the Traffic tab of the Cloudflare dashboard. These connections will be added to the dashboard in a future release.
{{
}}Cloudflare Tunnel deletes DNS records after 24-48 hours of a Tunnel being unregistered. Cloudflare Tunnel does not delete TLS certificates on your behalf once the Tunnel is shut down. If you want to clean up a Tunnel you’ve shut down, you can delete DNS records in the DNS editor and revoke TLS certificates in the Origin Certificates section of the SSL/TLS tab of the Cloudflare dashboard.
In this tutorial, you will learn how to retrieve data in your Cloudflare Workers applications from a PostgreSQL database using Postgres database connector.
{{
}}If you are using a MySQL database, refer to the MySQL database connector template.
{{
}}For a quick start, you will use Docker to run a local instance of Postgres and PgBouncer, and to securely expose the stack to the Internet using Cloudflare Tunnel.
To get started:
- Run the following
gitcommand to clone a basic Postgres database connector project. - After running the
git clonecommand,cdinto the new project.
git clone https://github.com/cloudflare/worker-template-postgres/
cd worker-template-postgresTo create and manage secure Cloudflare Tunnels, you first need to authenticate cloudflared CLI.
Skip this step if you already have authenticated cloudflared locally.
docker run -v ~/.cloudflared:/etc/cloudflared cloudflare/cloudflared:2021.11.0 login
# should be without a specific old tag, use latest
docker run -v ~/.cloudflared:/etc/cloudflared cloudflare/cloudflared loginRunning this command will:
- Prompt you to select your Cloudflare account and hostname.
- Download credentials and allow
cloudflaredto create Tunnels and DNS records.
{{
}}Cloudflare Tunnel will be accessible from the Internet once you run the following docker compose command. Cloudflare recommends that you secure your TUNNEL_HOSTNAME behind Cloudflare Access before you continue.
{{
}}You can find a prepared docker-compose file that does not require any changes in scripts/postgres with the following services:
- postgres
- pgbouncer - Placed in front of Postgres to provide connection pooling.
- cloudflared - Allows your applications to connect securely, through a encrypted tunnel, without opening any local ports.
Run the following commands to start all services. Replace postgres-tunnel.example.com with a hostname on your Cloudflare zone to route traffic through this tunnel.
cd scripts/postgres
export TUNNEL_HOSTNAME=postgres-tunnel.example.com
export TUNNEL_HOSTNAME=blog
docker-compose up
# Alternative: Run `docker-compose up -D` to start docker-compose detacheddocker-compose will spin up and configure all the services for you, including the creation of the Tunnel's DNS record.
The DNS record will point to the Cloudflare Tunnel, which keeps a secure connection between a local instance of cloudflared and the Cloudflare network.
Once Postgres is up and running, seed the database with a schema and a dataset. For this tutorial, you will use the Pagila schema and dataset. Use docker exec to execute a command inside the running Postgres container and import Pagila schema and dataset.
curl https://raw.githubusercontent.com/devrimgunduz/pagila/master/pagila-schema.sql | docker exec -i postgres_postgresql_1 psql -U postgres -d postgres
curl https://raw.githubusercontent.com/devrimgunduz/pagila/master/pagila-data.sql | docker exec -i postgres_postgresql_1 psql -U postgres -d postgresThe above commands will download the SQL schema and dataset files from Pagila's GitHub repository and execute them in your local Postgres database instance.
In src/index.ts, replace https://dev.example.com with your Cloudflare Tunnel hostname, ensuring that it is prefixed with the https:// protocol:
// src/index.tsconstclient=newClient({user: 'postgres',database: 'postgres',hostname: 'https://REPLACE_WITH_TUNNEL_HOSTNAME',password: '',port: 5432,});At this point, you can deploy your Worker and make a request to it to verify that your database connection is working.
The template script includes a simple query to select a number (SELECT 42;) that is executed in the database. Edit the script to query the imported Pagila dataset if the pagila-table query parameter is present.
// Query the database.// Parse the URL, and get the 'pagila-table' query parameter (which may not exist)consturl=newURL(request.url);constpagilaTable=url.searchParams.get("pagila-table");letresult;// if pagilaTable is defined, run a query on the Pagila datasetif(["actor","address","category","city","country","customer","film","film_actor","film_category","inventory","language","payment","payment_p2020_01","payment_p2020_02","payment_p2020_03","payment_p2020_04","payment_p2020_05","payment_p2020_06","rental","staff","store",].includes(pagilaTable)){result=awaitclient.queryObject(`SELECT * FROM ${pagilaTable};`);}else{constparam=42;result=awaitclient.queryObject(`SELECT ${param} as answer;`);}// Return result from database.returnnewResponse(JSON.stringify(result));In wrangler.toml, enter your Cloudflare account ID in the line containing account_id:
{{
}}Refer to Get started if you need help finding your Cloudflare account ID.
{{
}}---filename: wrangler.tomlhighlight: [3]---name = "worker-postgres-template"type = "javascript"account_id = ""Publish your function:
wrangler publish
✨ Built successfully, built project size is 10 KiB.
✨ Successfully published your script to
https://workers-postgres-template.example.workers.devhttps://developers.cloudflare.com/cloudflare-one/identity/service-auth/service-tokens
Create and save a Client ID and a Client Secret to Worker secrets in case your Tunnel is protected by Cloudflare Access.
wrangler secret put CF_CLIENT_ID
wrangler secret put CF_CLIENT_SECRETRequest some of the Pagila tables by adding the ?pagila-table query parameter with a table name to the URL of the Worker.
curl https://example.workers.dev/?pagila-table=actor
curl https://example.workers.dev/?pagila-table=address
curl https://example.workers.dev/?pagila-table=country
curl https://example.workers.dev/?pagila-table=languageRun the following command to stop and remove the Docker containers and networks:
docker compose down
# Stop and remove containers, networksIf you found this tutorial useful, continue building with other Cloudflare Workers tutorials below.
This repo contains example code and a PostgreSQL driver that can be used in any Workers project. If
you are interested in using the driver outside of this template, copy the driver/postgres module
into your project's node_modules or directly alongside your source.
Before you start, please refer to the official tutorial.
constclient=newClient({user: '<DATABASE_USER>',database: '<DATABASE_NAME>',// hostname is the full URL to your pre-created Cloudflare Tunnel, see documentation here:// https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/create-tunnelhostname: env.TUNNEL_HOST||'https://dev.example.com',password: env.DATABASE_PASSWORD,// use a secret to store passwordsport: '<DATABASE_PORT>',})awaitclient.connect()Please Note:
- you must use this config object format vs. a database connection string
- the
hostnameproperty must be the URL to your Cloudflare Tunnel, NOT your database host- your Tunnel will be configured to connect to your database host
postgres/docker-compose.yml
This docker-compose composition will get you up and running with a local instance of postgresql,
pgbouncer in front to provide connection pooling, and a copy of cloudflared to enable your
applications to securely connect, through a encrypted tunnel, without opening any ports up locally.
from within
scripts/postgres, run:
- Create credentials file (first time only)
docker run -v ~/.cloudflared:/etc/cloudflared cloudflare/cloudflared:2021.10.5 login- Start a local dev stack (cloudflared/pgbouncer/postgres)
TUNNEL_HOSTNAME=dev.example.com docker-compose up
