Skip to content

Repository files navigation

postgres-cloudflare-docker

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.Cleanup

🚀 Javascript full-stack 🚀

https://github.com/coding-to-music/postgres-cloudflare-docker

By Cloudflare Documentation

https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/tunnel-useful-terms/#default-cloudflared-directory

https://developers.cloudflare.comhttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/tunnel-guide/#set-up-a-tunnel-locally-cli-setup

https://developers.cloudflare.comhttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/create-tunnel/

https://github.com/cloudflare/cloudflare-docs/blob/production/contenthttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/tunnel-guide.md

https://github.com/cloudflare/cloudflare-docs/blob/production/contenthttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/create-tunnel/index.md

https://developers.cloudflare.com/workers/tutorials/query-postgres-from-workers-using-database-connectors/

Environment Values

GitHub

gitinitgitadd .
gitremoteremoveorigingitcommit -m"first commit"gitbranch -Mmaingitremoteaddorigingit@github.com:coding-to-music/postgres-cloudflare-docker.gitgitpush -uoriginmain

Naming and storing a configuration file

cloudflared 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-name

How to setup a Cloudflare Tunnel

https://dev.to/realchaika/how-to-setup-a-cloudflare-tunnel-on-linux-40d9

Installing Cloudflared

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.

.deb install (Ubuntu, Linux Mint, Debian, etc)

wget -qhttps://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64.deb && sudo dpkg -i cloudflared-linux-amd64.deb

​ .rpm install (Centos, Fedora, Rhel, OpenSusu, etc)

wget -qhttps://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-x86_64.rpm && sudo rpm -i cloudflared-linux-x86_64.rpm 

Login to Cloudflared

cloudflaredtunnellogin

This 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.

Create a tunnel

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".

Create your tunnel configuration file

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>.json

The 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.

Route traffic to your tunnel

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.dev

Run your tunnel

Finally, you can test out your tunnel.

cloudflaredtunnelrun <UUIDorName>

You can also specify a specific configuration file to run

cloudflaredtunnel --configpath/config.yamlrun

Once 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.

Run your tunnel as a service

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.

sudocloudflaredserviceinstall

You may need to manually specify config location. In my case, I did have to specify it.

For example,

sudocloudflared --config /home/{username}/.cloudflared/config.ymlserviceinstall

Note 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

sudosystemctlenablecloudflaredsudosystemctlstartcloudflared

Ensure your tunnel started/is running fine:

sudosystemctlstatuscloudflared

Test out your tunnel by visting the hostname you routed it to.

Example: cloudflared run in docker

https://gist.github.com/joejordanbrown/b63f82a298da208a5e4780c2200af8fb

Example: cloudflared run in docker


  1. 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
  1. 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
  1. 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
  1. 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
  1. 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:404

Possible helpful GitHub issue

cloudflare/cloudflared#504

References 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 Cloudflare

Another 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:404

Cloudflared documentation

NAME:
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)

Set up your first tunnel

https://github.com/cloudflare/cloudflare-docs/blob/production/contenthttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/tunnel-guide.md

title: Set up your first tunnel

When setting up your first Cloudflare Tunnel, you have the option to create it:

Prerequisites

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.

.deb install

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.deb

​.rpm install

Use 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.rpm
Build 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/cloudflared

Depending on where you installed cloudflared, you can move it to a known path as well.

mv /root/cloudflared/cloudflared /usr/bin/cloudflared

Useful terms

{{}}

Review terminology for tunnels setup locally through the CLI.

Tunnel

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.

Tunnel 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.

Tunnel name

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.

Connector

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.

Default cloudflared directory

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.

OSPath to default directory
Windows%USERPROFILE%\.cloudflared
MacOS and Unix-like systems~/.cloudflared, /etc/cloudflared, and /usr/local/etc/cloudflared, in this order.

Configuration file

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 rule

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.

Cert.pem

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.

Credentials file

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

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.

Virtual Networks

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.

2. Authenticate cloudflared

cloudflared tunnel login

Running 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 cloudflared directory.

3. Create a tunnel and give it a name

cloudflared tunnel create <NAME>

Running this command will:

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 list

4. Create a configuration file

Create 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>.json

If you are connecting a network

tunnel: <Tunnel-UUID>
credentials-file: /root/.cloudflared/<Tunnel-UUID>.json
warp-routing:
enabled: true

Confirm that the configuration file has been successfully created by running:

cat config.yml

5. Start routing traffic

Now 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 show

6. Run the tunnel

Run 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.

{{

}}

7. Check the tunnel

Your tunnel configuration is complete! If you want to get information on the tunnel you just created, you can run:

cloudflared tunnel info

pcx-content-type: how-to

title: Create a Tunnel

Create a Tunnel

Before you start
1. Add a website to Cloudflare
2. Change your domain nameservers to Cloudflare
3. Install and authenticate cloudflared

Create a Tunnel

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.

Create a tunnel

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.

{{}}

Actioncert.pemCredentials file
Create a new TunnelRequired-
Delete a TunnelRequired-
Run a TunnelAvailableRequired
Create DNS records
from cloudflared
Required-
Connect to load balancer
pools from cloudflared
Required-
Route traffic to a running Tunnel
from the Cloudflare dashboard
AvailableAvailable

{{}}

List available Tunnels

cloudflared can list all created Tunnels in your account, as well as those actively connected to Cloudflare, by running the following command:

cloudflared tunnel list

Note: the command requires the cert.pem file.

List tunnels

Revoke and delete a Tunnel

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.

Query Postgres from Workers using a database connector

Overview

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.

Basic project scaffolding

To get started:

  1. Run the following git command to clone a basic Postgres database connector project.
  2. After running the git clone command, cd into the new project.
git clone https://github.com/cloudflare/worker-template-postgres/
cd worker-template-postgres

Cloudflare Tunnel authentication

To 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 login

Running this command will:

  • Prompt you to select your Cloudflare account and hostname.
  • Download credentials and allow cloudflared to create Tunnels and DNS records.

Start and prepare Postgres database

Start the Postgres server

{{

}}

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:

  1. postgres
  2. pgbouncer - Placed in front of Postgres to provide connection pooling.
  3. 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 detached

docker-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.

Import example dataset

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 postgres

The above commands will download the SQL schema and dataset files from Pagila's GitHub repository and execute them in your local Postgres database instance.

Edit Worker and query Pagila dataset

Database connection settings

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.

Query Pagila dataset

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));

Worker deployment

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.dev

Set secrets

https://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_SECRET

Test the Worker

Request 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=language

Cleanup

Run the following command to stop and remove the Docker containers and networks:

docker compose down
# Stop and remove containers, networks

Related resources

If you found this tutorial useful, continue building with other Cloudflare Workers tutorials below.

Cloudflare Workers + PostgreSQL

https://developers.cloudflare.com/workers/tutorials/query-postgres-from-workers-using-database-connectors/

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.

Usage

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 hostname property must be the URL to your Cloudflare Tunnel, NOT your database host
    • your Tunnel will be configured to connect to your database host

Running the Postgres Demo

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.

Usage

from within scripts/postgres, run:

  1. Create credentials file (first time only)
docker run -v ~/.cloudflared:/etc/cloudflared cloudflare/cloudflared:2021.10.5 login
  1. Start a local dev stack (cloudflared/pgbouncer/postgres)
TUNNEL_HOSTNAME=dev.example.com docker-compose up

About

Query Postgres from Workers using a database connector. Retrieve data in your Cloudflare Workers applications from a PostgreSQL database using Postgres database connector

Resources

Code of conduct

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
GitHub - coding-to-music/postgres-cloudflare-docker: Query Postgres from Workers using a database connector. Retrieve data in your Cloudflare Workers applications from a PostgreSQL database using Postgres database connector · GitHub
Skip to content

Repository files navigation

postgres-cloudflare-docker

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.Cleanup

🚀 Javascript full-stack 🚀

https://github.com/coding-to-music/postgres-cloudflare-docker

By Cloudflare Documentation

https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/tunnel-useful-terms/#default-cloudflared-directory

https://developers.cloudflare.comhttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/tunnel-guide/#set-up-a-tunnel-locally-cli-setup

https://developers.cloudflare.comhttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/create-tunnel/

https://github.com/cloudflare/cloudflare-docs/blob/production/contenthttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/tunnel-guide.md

https://github.com/cloudflare/cloudflare-docs/blob/production/contenthttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/create-tunnel/index.md

https://developers.cloudflare.com/workers/tutorials/query-postgres-from-workers-using-database-connectors/

Environment Values

GitHub

gitinitgitadd .
gitremoteremoveorigingitcommit -m"first commit"gitbranch -Mmaingitremoteaddorigingit@github.com:coding-to-music/postgres-cloudflare-docker.gitgitpush -uoriginmain

Naming and storing a configuration file

cloudflared 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-name

How to setup a Cloudflare Tunnel

https://dev.to/realchaika/how-to-setup-a-cloudflare-tunnel-on-linux-40d9

Installing Cloudflared

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.

.deb install (Ubuntu, Linux Mint, Debian, etc)

wget -qhttps://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64.deb && sudo dpkg -i cloudflared-linux-amd64.deb

​ .rpm install (Centos, Fedora, Rhel, OpenSusu, etc)

wget -qhttps://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-x86_64.rpm && sudo rpm -i cloudflared-linux-x86_64.rpm 

Login to Cloudflared

cloudflaredtunnellogin

This 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.

Create a tunnel

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".

Create your tunnel configuration file

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>.json

The 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.

Route traffic to your tunnel

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.dev

Run your tunnel

Finally, you can test out your tunnel.

cloudflaredtunnelrun <UUIDorName>

You can also specify a specific configuration file to run

cloudflaredtunnel --configpath/config.yamlrun

Once 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.

Run your tunnel as a service

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.

sudocloudflaredserviceinstall

You may need to manually specify config location. In my case, I did have to specify it.

For example,

sudocloudflared --config /home/{username}/.cloudflared/config.ymlserviceinstall

Note 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

sudosystemctlenablecloudflaredsudosystemctlstartcloudflared

Ensure your tunnel started/is running fine:

sudosystemctlstatuscloudflared

Test out your tunnel by visting the hostname you routed it to.

Example: cloudflared run in docker

https://gist.github.com/joejordanbrown/b63f82a298da208a5e4780c2200af8fb

Example: cloudflared run in docker


  1. 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
  1. 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
  1. 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
  1. 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
  1. 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:404

Possible helpful GitHub issue

cloudflare/cloudflared#504

References 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 Cloudflare

Another 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:404

Cloudflared documentation

NAME:
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)

Set up your first tunnel

https://github.com/cloudflare/cloudflare-docs/blob/production/contenthttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/tunnel-guide.md

title: Set up your first tunnel

When setting up your first Cloudflare Tunnel, you have the option to create it:

Prerequisites

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.

.deb install

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.deb

​.rpm install

Use 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.rpm
Build 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/cloudflared

Depending on where you installed cloudflared, you can move it to a known path as well.

mv /root/cloudflared/cloudflared /usr/bin/cloudflared

Useful terms

{{}}

Review terminology for tunnels setup locally through the CLI.

Tunnel

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.

Tunnel 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.

Tunnel name

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.

Connector

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.

Default cloudflared directory

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.

OSPath to default directory
Windows%USERPROFILE%\.cloudflared
MacOS and Unix-like systems~/.cloudflared, /etc/cloudflared, and /usr/local/etc/cloudflared, in this order.

Configuration file

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 rule

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.

Cert.pem

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.

Credentials file

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

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.

Virtual Networks

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.

2. Authenticate cloudflared

cloudflared tunnel login

Running 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 cloudflared directory.

3. Create a tunnel and give it a name

cloudflared tunnel create <NAME>

Running this command will:

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 list

4. Create a configuration file

Create 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>.json

If you are connecting a network

tunnel: <Tunnel-UUID>
credentials-file: /root/.cloudflared/<Tunnel-UUID>.json
warp-routing:
enabled: true

Confirm that the configuration file has been successfully created by running:

cat config.yml

5. Start routing traffic

Now 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 show

6. Run the tunnel

Run 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.

{{

}}

7. Check the tunnel

Your tunnel configuration is complete! If you want to get information on the tunnel you just created, you can run:

cloudflared tunnel info

pcx-content-type: how-to

title: Create a Tunnel

Create a Tunnel

Before you start
1. Add a website to Cloudflare
2. Change your domain nameservers to Cloudflare
3. Install and authenticate cloudflared

Create a Tunnel

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.

Create a tunnel

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.

{{}}

Actioncert.pemCredentials file
Create a new TunnelRequired-
Delete a TunnelRequired-
Run a TunnelAvailableRequired
Create DNS records
from cloudflared
Required-
Connect to load balancer
pools from cloudflared
Required-
Route traffic to a running Tunnel
from the Cloudflare dashboard
AvailableAvailable

{{}}

List available Tunnels

cloudflared can list all created Tunnels in your account, as well as those actively connected to Cloudflare, by running the following command:

cloudflared tunnel list

Note: the command requires the cert.pem file.

List tunnels

Revoke and delete a Tunnel

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.

Query Postgres from Workers using a database connector

Overview

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.

Basic project scaffolding

To get started:

  1. Run the following git command to clone a basic Postgres database connector project.
  2. After running the git clone command, cd into the new project.
git clone https://github.com/cloudflare/worker-template-postgres/
cd worker-template-postgres

Cloudflare Tunnel authentication

To 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 login

Running this command will:

  • Prompt you to select your Cloudflare account and hostname.
  • Download credentials and allow cloudflared to create Tunnels and DNS records.

Start and prepare Postgres database

Start the Postgres server

{{

}}

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:

  1. postgres
  2. pgbouncer - Placed in front of Postgres to provide connection pooling.
  3. 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 detached

docker-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.

Import example dataset

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 postgres

The above commands will download the SQL schema and dataset files from Pagila's GitHub repository and execute them in your local Postgres database instance.

Edit Worker and query Pagila dataset

Database connection settings

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.

Query Pagila dataset

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));

Worker deployment

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.dev

Set secrets

https://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_SECRET

Test the Worker

Request 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=language

Cleanup

Run the following command to stop and remove the Docker containers and networks:

docker compose down
# Stop and remove containers, networks

Related resources

If you found this tutorial useful, continue building with other Cloudflare Workers tutorials below.

Cloudflare Workers + PostgreSQL

https://developers.cloudflare.com/workers/tutorials/query-postgres-from-workers-using-database-connectors/

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.

Usage

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 hostname property must be the URL to your Cloudflare Tunnel, NOT your database host
    • your Tunnel will be configured to connect to your database host

Running the Postgres Demo

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.

Usage

from within scripts/postgres, run:

  1. Create credentials file (first time only)
docker run -v ~/.cloudflared:/etc/cloudflared cloudflare/cloudflared:2021.10.5 login
  1. Start a local dev stack (cloudflared/pgbouncer/postgres)
TUNNEL_HOSTNAME=dev.example.com docker-compose up

About

Query Postgres from Workers using a database connector. Retrieve data in your Cloudflare Workers applications from a PostgreSQL database using Postgres database connector

Resources

Code of conduct

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - coding-to-music/postgres-cloudflare-docker: Query Postgres from Workers using a database connector. Retrieve data in your Cloudflare Workers applications from a PostgreSQL database using Postgres database connector · GitHub
Skip to content

Repository files navigation

postgres-cloudflare-docker

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.Cleanup

🚀 Javascript full-stack 🚀

https://github.com/coding-to-music/postgres-cloudflare-docker

By Cloudflare Documentation

https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/tunnel-useful-terms/#default-cloudflared-directory

https://developers.cloudflare.comhttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/tunnel-guide/#set-up-a-tunnel-locally-cli-setup

https://developers.cloudflare.comhttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/create-tunnel/

https://github.com/cloudflare/cloudflare-docs/blob/production/contenthttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/tunnel-guide.md

https://github.com/cloudflare/cloudflare-docs/blob/production/contenthttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/create-tunnel/index.md

https://developers.cloudflare.com/workers/tutorials/query-postgres-from-workers-using-database-connectors/

Environment Values

GitHub

gitinitgitadd .
gitremoteremoveorigingitcommit -m"first commit"gitbranch -Mmaingitremoteaddorigingit@github.com:coding-to-music/postgres-cloudflare-docker.gitgitpush -uoriginmain

Naming and storing a configuration file

cloudflared 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-name

How to setup a Cloudflare Tunnel

https://dev.to/realchaika/how-to-setup-a-cloudflare-tunnel-on-linux-40d9

Installing Cloudflared

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.

.deb install (Ubuntu, Linux Mint, Debian, etc)

wget -qhttps://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64.deb && sudo dpkg -i cloudflared-linux-amd64.deb

​ .rpm install (Centos, Fedora, Rhel, OpenSusu, etc)

wget -qhttps://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-x86_64.rpm && sudo rpm -i cloudflared-linux-x86_64.rpm 

Login to Cloudflared

cloudflaredtunnellogin

This 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.

Create a tunnel

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".

Create your tunnel configuration file

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>.json

The 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.

Route traffic to your tunnel

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.dev

Run your tunnel

Finally, you can test out your tunnel.

cloudflaredtunnelrun <UUIDorName>

You can also specify a specific configuration file to run

cloudflaredtunnel --configpath/config.yamlrun

Once 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.

Run your tunnel as a service

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.

sudocloudflaredserviceinstall

You may need to manually specify config location. In my case, I did have to specify it.

For example,

sudocloudflared --config /home/{username}/.cloudflared/config.ymlserviceinstall

Note 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

sudosystemctlenablecloudflaredsudosystemctlstartcloudflared

Ensure your tunnel started/is running fine:

sudosystemctlstatuscloudflared

Test out your tunnel by visting the hostname you routed it to.

Example: cloudflared run in docker

https://gist.github.com/joejordanbrown/b63f82a298da208a5e4780c2200af8fb

Example: cloudflared run in docker


  1. 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
  1. 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
  1. 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
  1. 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
  1. 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:404

Possible helpful GitHub issue

cloudflare/cloudflared#504

References 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 Cloudflare

Another 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:404

Cloudflared documentation

NAME:
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)

Set up your first tunnel

https://github.com/cloudflare/cloudflare-docs/blob/production/contenthttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/tunnel-guide.md

title: Set up your first tunnel

When setting up your first Cloudflare Tunnel, you have the option to create it:

Prerequisites

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.

.deb install

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.deb

​.rpm install

Use 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.rpm
Build 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/cloudflared

Depending on where you installed cloudflared, you can move it to a known path as well.

mv /root/cloudflared/cloudflared /usr/bin/cloudflared

Useful terms

{{}}

Review terminology for tunnels setup locally through the CLI.

Tunnel

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.

Tunnel 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.

Tunnel name

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.

Connector

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.

Default cloudflared directory

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.

OSPath to default directory
Windows%USERPROFILE%\.cloudflared
MacOS and Unix-like systems~/.cloudflared, /etc/cloudflared, and /usr/local/etc/cloudflared, in this order.

Configuration file

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 rule

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.

Cert.pem

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.

Credentials file

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

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.

Virtual Networks

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.

2. Authenticate cloudflared

cloudflared tunnel login

Running 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 cloudflared directory.

3. Create a tunnel and give it a name

cloudflared tunnel create <NAME>

Running this command will:

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 list

4. Create a configuration file

Create 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>.json

If you are connecting a network

tunnel: <Tunnel-UUID>
credentials-file: /root/.cloudflared/<Tunnel-UUID>.json
warp-routing:
enabled: true

Confirm that the configuration file has been successfully created by running:

cat config.yml

5. Start routing traffic

Now 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 show

6. Run the tunnel

Run 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.

{{

}}

7. Check the tunnel

Your tunnel configuration is complete! If you want to get information on the tunnel you just created, you can run:

cloudflared tunnel info

pcx-content-type: how-to

title: Create a Tunnel

Create a Tunnel

Before you start
1. Add a website to Cloudflare
2. Change your domain nameservers to Cloudflare
3. Install and authenticate cloudflared

Create a Tunnel

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.

Create a tunnel

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.

{{}}

Actioncert.pemCredentials file
Create a new TunnelRequired-
Delete a TunnelRequired-
Run a TunnelAvailableRequired
Create DNS records
from cloudflared
Required-
Connect to load balancer
pools from cloudflared
Required-
Route traffic to a running Tunnel
from the Cloudflare dashboard
AvailableAvailable

{{}}

List available Tunnels

cloudflared can list all created Tunnels in your account, as well as those actively connected to Cloudflare, by running the following command:

cloudflared tunnel list

Note: the command requires the cert.pem file.

List tunnels

Revoke and delete a Tunnel

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.

Query Postgres from Workers using a database connector

Overview

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.

Basic project scaffolding

To get started:

  1. Run the following git command to clone a basic Postgres database connector project.
  2. After running the git clone command, cd into the new project.
git clone https://github.com/cloudflare/worker-template-postgres/
cd worker-template-postgres

Cloudflare Tunnel authentication

To 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 login

Running this command will:

  • Prompt you to select your Cloudflare account and hostname.
  • Download credentials and allow cloudflared to create Tunnels and DNS records.

Start and prepare Postgres database

Start the Postgres server

{{

}}

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:

  1. postgres
  2. pgbouncer - Placed in front of Postgres to provide connection pooling.
  3. 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 detached

docker-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.

Import example dataset

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 postgres

The above commands will download the SQL schema and dataset files from Pagila's GitHub repository and execute them in your local Postgres database instance.

Edit Worker and query Pagila dataset

Database connection settings

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.

Query Pagila dataset

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));

Worker deployment

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.dev

Set secrets

https://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_SECRET

Test the Worker

Request 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=language

Cleanup

Run the following command to stop and remove the Docker containers and networks:

docker compose down
# Stop and remove containers, networks

Related resources

If you found this tutorial useful, continue building with other Cloudflare Workers tutorials below.

Cloudflare Workers + PostgreSQL

https://developers.cloudflare.com/workers/tutorials/query-postgres-from-workers-using-database-connectors/

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.

Usage

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 hostname property must be the URL to your Cloudflare Tunnel, NOT your database host
    • your Tunnel will be configured to connect to your database host

Running the Postgres Demo

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.

Usage

from within scripts/postgres, run:

  1. Create credentials file (first time only)
docker run -v ~/.cloudflared:/etc/cloudflared cloudflare/cloudflared:2021.10.5 login
  1. Start a local dev stack (cloudflared/pgbouncer/postgres)
TUNNEL_HOSTNAME=dev.example.com docker-compose up

About

Query Postgres from Workers using a database connector. Retrieve data in your Cloudflare Workers applications from a PostgreSQL database using Postgres database connector

Resources

Code of conduct

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - coding-to-music/postgres-cloudflare-docker: Query Postgres from Workers using a database connector. Retrieve data in your Cloudflare Workers applications from a PostgreSQL database using Postgres database connector · GitHub
Skip to content

Repository files navigation

postgres-cloudflare-docker

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.Cleanup

🚀 Javascript full-stack 🚀

https://github.com/coding-to-music/postgres-cloudflare-docker

By Cloudflare Documentation

https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/tunnel-useful-terms/#default-cloudflared-directory

https://developers.cloudflare.comhttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/tunnel-guide/#set-up-a-tunnel-locally-cli-setup

https://developers.cloudflare.comhttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/create-tunnel/

https://github.com/cloudflare/cloudflare-docs/blob/production/contenthttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/tunnel-guide.md

https://github.com/cloudflare/cloudflare-docs/blob/production/contenthttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/create-tunnel/index.md

https://developers.cloudflare.com/workers/tutorials/query-postgres-from-workers-using-database-connectors/

Environment Values

GitHub

gitinitgitadd .
gitremoteremoveorigingitcommit -m"first commit"gitbranch -Mmaingitremoteaddorigingit@github.com:coding-to-music/postgres-cloudflare-docker.gitgitpush -uoriginmain

Naming and storing a configuration file

cloudflared 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-name

How to setup a Cloudflare Tunnel

https://dev.to/realchaika/how-to-setup-a-cloudflare-tunnel-on-linux-40d9

Installing Cloudflared

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.

.deb install (Ubuntu, Linux Mint, Debian, etc)

wget -qhttps://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64.deb && sudo dpkg -i cloudflared-linux-amd64.deb

​ .rpm install (Centos, Fedora, Rhel, OpenSusu, etc)

wget -qhttps://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-x86_64.rpm && sudo rpm -i cloudflared-linux-x86_64.rpm 

Login to Cloudflared

cloudflaredtunnellogin

This 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.

Create a tunnel

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".

Create your tunnel configuration file

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>.json

The 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.

Route traffic to your tunnel

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.dev

Run your tunnel

Finally, you can test out your tunnel.

cloudflaredtunnelrun <UUIDorName>

You can also specify a specific configuration file to run

cloudflaredtunnel --configpath/config.yamlrun

Once 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.

Run your tunnel as a service

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.

sudocloudflaredserviceinstall

You may need to manually specify config location. In my case, I did have to specify it.

For example,

sudocloudflared --config /home/{username}/.cloudflared/config.ymlserviceinstall

Note 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

sudosystemctlenablecloudflaredsudosystemctlstartcloudflared

Ensure your tunnel started/is running fine:

sudosystemctlstatuscloudflared

Test out your tunnel by visting the hostname you routed it to.

Example: cloudflared run in docker

https://gist.github.com/joejordanbrown/b63f82a298da208a5e4780c2200af8fb

Example: cloudflared run in docker


  1. 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
  1. 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
  1. 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
  1. 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
  1. 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:404

Possible helpful GitHub issue

cloudflare/cloudflared#504

References 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 Cloudflare

Another 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:404

Cloudflared documentation

NAME:
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)

Set up your first tunnel

https://github.com/cloudflare/cloudflare-docs/blob/production/contenthttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/tunnel-guide.md

title: Set up your first tunnel

When setting up your first Cloudflare Tunnel, you have the option to create it:

Prerequisites

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.

.deb install

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.deb

​.rpm install

Use 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.rpm
Build 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/cloudflared

Depending on where you installed cloudflared, you can move it to a known path as well.

mv /root/cloudflared/cloudflared /usr/bin/cloudflared

Useful terms

{{}}

Review terminology for tunnels setup locally through the CLI.

Tunnel

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.

Tunnel 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.

Tunnel name

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.

Connector

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.

Default cloudflared directory

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.

OSPath to default directory
Windows%USERPROFILE%\.cloudflared
MacOS and Unix-like systems~/.cloudflared, /etc/cloudflared, and /usr/local/etc/cloudflared, in this order.

Configuration file

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 rule

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.

Cert.pem

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.

Credentials file

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

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.

Virtual Networks

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.

2. Authenticate cloudflared

cloudflared tunnel login

Running 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 cloudflared directory.

3. Create a tunnel and give it a name

cloudflared tunnel create <NAME>

Running this command will:

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 list

4. Create a configuration file

Create 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>.json

If you are connecting a network

tunnel: <Tunnel-UUID>
credentials-file: /root/.cloudflared/<Tunnel-UUID>.json
warp-routing:
enabled: true

Confirm that the configuration file has been successfully created by running:

cat config.yml

5. Start routing traffic

Now 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 show

6. Run the tunnel

Run 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.

{{

}}

7. Check the tunnel

Your tunnel configuration is complete! If you want to get information on the tunnel you just created, you can run:

cloudflared tunnel info

pcx-content-type: how-to

title: Create a Tunnel

Create a Tunnel

Before you start
1. Add a website to Cloudflare
2. Change your domain nameservers to Cloudflare
3. Install and authenticate cloudflared

Create a Tunnel

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.

Create a tunnel

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.

{{}}

Actioncert.pemCredentials file
Create a new TunnelRequired-
Delete a TunnelRequired-
Run a TunnelAvailableRequired
Create DNS records
from cloudflared
Required-
Connect to load balancer
pools from cloudflared
Required-
Route traffic to a running Tunnel
from the Cloudflare dashboard
AvailableAvailable

{{}}

List available Tunnels

cloudflared can list all created Tunnels in your account, as well as those actively connected to Cloudflare, by running the following command:

cloudflared tunnel list

Note: the command requires the cert.pem file.

List tunnels

Revoke and delete a Tunnel

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.

Query Postgres from Workers using a database connector

Overview

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.

Basic project scaffolding

To get started:

  1. Run the following git command to clone a basic Postgres database connector project.
  2. After running the git clone command, cd into the new project.
git clone https://github.com/cloudflare/worker-template-postgres/
cd worker-template-postgres

Cloudflare Tunnel authentication

To 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 login

Running this command will:

  • Prompt you to select your Cloudflare account and hostname.
  • Download credentials and allow cloudflared to create Tunnels and DNS records.

Start and prepare Postgres database

Start the Postgres server

{{

}}

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:

  1. postgres
  2. pgbouncer - Placed in front of Postgres to provide connection pooling.
  3. 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 detached

docker-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.

Import example dataset

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 postgres

The above commands will download the SQL schema and dataset files from Pagila's GitHub repository and execute them in your local Postgres database instance.

Edit Worker and query Pagila dataset

Database connection settings

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.

Query Pagila dataset

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));

Worker deployment

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.dev

Set secrets

https://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_SECRET

Test the Worker

Request 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=language

Cleanup

Run the following command to stop and remove the Docker containers and networks:

docker compose down
# Stop and remove containers, networks

Related resources

If you found this tutorial useful, continue building with other Cloudflare Workers tutorials below.

Cloudflare Workers + PostgreSQL

https://developers.cloudflare.com/workers/tutorials/query-postgres-from-workers-using-database-connectors/

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.

Usage

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 hostname property must be the URL to your Cloudflare Tunnel, NOT your database host
    • your Tunnel will be configured to connect to your database host

Running the Postgres Demo

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.

Usage

from within scripts/postgres, run:

  1. Create credentials file (first time only)
docker run -v ~/.cloudflared:/etc/cloudflared cloudflare/cloudflared:2021.10.5 login
  1. Start a local dev stack (cloudflared/pgbouncer/postgres)
TUNNEL_HOSTNAME=dev.example.com docker-compose up

About

Query Postgres from Workers using a database connector. Retrieve data in your Cloudflare Workers applications from a PostgreSQL database using Postgres database connector

Resources

Code of conduct

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' GitHub - coding-to-music/postgres-cloudflare-docker: Query Postgres from Workers using a database connector. Retrieve data in your Cloudflare Workers applications from a PostgreSQL database using Postgres database connector · GitHub
Skip to content

Repository files navigation

postgres-cloudflare-docker

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.Cleanup

🚀 Javascript full-stack 🚀

https://github.com/coding-to-music/postgres-cloudflare-docker

By Cloudflare Documentation

https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/tunnel-useful-terms/#default-cloudflared-directory

https://developers.cloudflare.comhttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/tunnel-guide/#set-up-a-tunnel-locally-cli-setup

https://developers.cloudflare.comhttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/create-tunnel/

https://github.com/cloudflare/cloudflare-docs/blob/production/contenthttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/tunnel-guide.md

https://github.com/cloudflare/cloudflare-docs/blob/production/contenthttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/create-tunnel/index.md

https://developers.cloudflare.com/workers/tutorials/query-postgres-from-workers-using-database-connectors/

Environment Values

GitHub

gitinitgitadd .
gitremoteremoveorigingitcommit -m"first commit"gitbranch -Mmaingitremoteaddorigingit@github.com:coding-to-music/postgres-cloudflare-docker.gitgitpush -uoriginmain

Naming and storing a configuration file

cloudflared 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-name

How to setup a Cloudflare Tunnel

https://dev.to/realchaika/how-to-setup-a-cloudflare-tunnel-on-linux-40d9

Installing Cloudflared

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.

.deb install (Ubuntu, Linux Mint, Debian, etc)

wget -qhttps://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64.deb && sudo dpkg -i cloudflared-linux-amd64.deb

​ .rpm install (Centos, Fedora, Rhel, OpenSusu, etc)

wget -qhttps://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-x86_64.rpm && sudo rpm -i cloudflared-linux-x86_64.rpm 

Login to Cloudflared

cloudflaredtunnellogin

This 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.

Create a tunnel

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".

Create your tunnel configuration file

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>.json

The 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.

Route traffic to your tunnel

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.dev

Run your tunnel

Finally, you can test out your tunnel.

cloudflaredtunnelrun <UUIDorName>

You can also specify a specific configuration file to run

cloudflaredtunnel --configpath/config.yamlrun

Once 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.

Run your tunnel as a service

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.

sudocloudflaredserviceinstall

You may need to manually specify config location. In my case, I did have to specify it.

For example,

sudocloudflared --config /home/{username}/.cloudflared/config.ymlserviceinstall

Note 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

sudosystemctlenablecloudflaredsudosystemctlstartcloudflared

Ensure your tunnel started/is running fine:

sudosystemctlstatuscloudflared

Test out your tunnel by visting the hostname you routed it to.

Example: cloudflared run in docker

https://gist.github.com/joejordanbrown/b63f82a298da208a5e4780c2200af8fb

Example: cloudflared run in docker


  1. 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
  1. 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
  1. 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
  1. 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
  1. 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:404

Possible helpful GitHub issue

cloudflare/cloudflared#504

References 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 Cloudflare

Another 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:404

Cloudflared documentation

NAME:
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)

Set up your first tunnel

https://github.com/cloudflare/cloudflare-docs/blob/production/contenthttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/tunnel-guide.md

title: Set up your first tunnel

When setting up your first Cloudflare Tunnel, you have the option to create it:

Prerequisites

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.

.deb install

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.deb

​.rpm install

Use 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.rpm
Build 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/cloudflared

Depending on where you installed cloudflared, you can move it to a known path as well.

mv /root/cloudflared/cloudflared /usr/bin/cloudflared

Useful terms

{{}}

Review terminology for tunnels setup locally through the CLI.

Tunnel

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.

Tunnel 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.

Tunnel name

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.

Connector

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.

Default cloudflared directory

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.

OSPath to default directory
Windows%USERPROFILE%\.cloudflared
MacOS and Unix-like systems~/.cloudflared, /etc/cloudflared, and /usr/local/etc/cloudflared, in this order.

Configuration file

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 rule

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.

Cert.pem

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.

Credentials file

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

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.

Virtual Networks

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.

2. Authenticate cloudflared

cloudflared tunnel login

Running 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 cloudflared directory.

3. Create a tunnel and give it a name

cloudflared tunnel create <NAME>

Running this command will:

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 list

4. Create a configuration file

Create 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>.json

If you are connecting a network

tunnel: <Tunnel-UUID>
credentials-file: /root/.cloudflared/<Tunnel-UUID>.json
warp-routing:
enabled: true

Confirm that the configuration file has been successfully created by running:

cat config.yml

5. Start routing traffic

Now 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 show

6. Run the tunnel

Run 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.

{{

}}

7. Check the tunnel

Your tunnel configuration is complete! If you want to get information on the tunnel you just created, you can run:

cloudflared tunnel info

pcx-content-type: how-to

title: Create a Tunnel

Create a Tunnel

Before you start
1. Add a website to Cloudflare
2. Change your domain nameservers to Cloudflare
3. Install and authenticate cloudflared

Create a Tunnel

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.

Create a tunnel

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.

{{}}

Actioncert.pemCredentials file
Create a new TunnelRequired-
Delete a TunnelRequired-
Run a TunnelAvailableRequired
Create DNS records
from cloudflared
Required-
Connect to load balancer
pools from cloudflared
Required-
Route traffic to a running Tunnel
from the Cloudflare dashboard
AvailableAvailable

{{}}

List available Tunnels

cloudflared can list all created Tunnels in your account, as well as those actively connected to Cloudflare, by running the following command:

cloudflared tunnel list

Note: the command requires the cert.pem file.

List tunnels

Revoke and delete a Tunnel

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.

Query Postgres from Workers using a database connector

Overview

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.

Basic project scaffolding

To get started:

  1. Run the following git command to clone a basic Postgres database connector project.
  2. After running the git clone command, cd into the new project.
git clone https://github.com/cloudflare/worker-template-postgres/
cd worker-template-postgres

Cloudflare Tunnel authentication

To 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 login

Running this command will:

  • Prompt you to select your Cloudflare account and hostname.
  • Download credentials and allow cloudflared to create Tunnels and DNS records.

Start and prepare Postgres database

Start the Postgres server

{{

}}

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:

  1. postgres
  2. pgbouncer - Placed in front of Postgres to provide connection pooling.
  3. 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 detached

docker-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.

Import example dataset

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 postgres

The above commands will download the SQL schema and dataset files from Pagila's GitHub repository and execute them in your local Postgres database instance.

Edit Worker and query Pagila dataset

Database connection settings

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.

Query Pagila dataset

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));

Worker deployment

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.dev

Set secrets

https://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_SECRET

Test the Worker

Request 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=language

Cleanup

Run the following command to stop and remove the Docker containers and networks:

docker compose down
# Stop and remove containers, networks

Related resources

If you found this tutorial useful, continue building with other Cloudflare Workers tutorials below.

Cloudflare Workers + PostgreSQL

https://developers.cloudflare.com/workers/tutorials/query-postgres-from-workers-using-database-connectors/

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.

Usage

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 hostname property must be the URL to your Cloudflare Tunnel, NOT your database host
    • your Tunnel will be configured to connect to your database host

Running the Postgres Demo

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.

Usage

from within scripts/postgres, run:

  1. Create credentials file (first time only)
docker run -v ~/.cloudflared:/etc/cloudflared cloudflare/cloudflared:2021.10.5 login
  1. Start a local dev stack (cloudflared/pgbouncer/postgres)
TUNNEL_HOSTNAME=dev.example.com docker-compose up

About

Query Postgres from Workers using a database connector. Retrieve data in your Cloudflare Workers applications from a PostgreSQL database using Postgres database connector

Resources

Code of conduct

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - coding-to-music/postgres-cloudflare-docker: Query Postgres from Workers using a database connector. Retrieve data in your Cloudflare Workers applications from a PostgreSQL database using Postgres database connector · GitHub
Skip to content

Repository files navigation

postgres-cloudflare-docker

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.Cleanup

🚀 Javascript full-stack 🚀

https://github.com/coding-to-music/postgres-cloudflare-docker

By Cloudflare Documentation

https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/tunnel-useful-terms/#default-cloudflared-directory

https://developers.cloudflare.comhttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/tunnel-guide/#set-up-a-tunnel-locally-cli-setup

https://developers.cloudflare.comhttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/create-tunnel/

https://github.com/cloudflare/cloudflare-docs/blob/production/contenthttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/tunnel-guide.md

https://github.com/cloudflare/cloudflare-docs/blob/production/contenthttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/create-tunnel/index.md

https://developers.cloudflare.com/workers/tutorials/query-postgres-from-workers-using-database-connectors/

Environment Values

GitHub

gitinitgitadd .
gitremoteremoveorigingitcommit -m"first commit"gitbranch -Mmaingitremoteaddorigingit@github.com:coding-to-music/postgres-cloudflare-docker.gitgitpush -uoriginmain

Naming and storing a configuration file

cloudflared 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-name

How to setup a Cloudflare Tunnel

https://dev.to/realchaika/how-to-setup-a-cloudflare-tunnel-on-linux-40d9

Installing Cloudflared

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.

.deb install (Ubuntu, Linux Mint, Debian, etc)

wget -qhttps://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64.deb && sudo dpkg -i cloudflared-linux-amd64.deb

​ .rpm install (Centos, Fedora, Rhel, OpenSusu, etc)

wget -qhttps://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-x86_64.rpm && sudo rpm -i cloudflared-linux-x86_64.rpm 

Login to Cloudflared

cloudflaredtunnellogin

This 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.

Create a tunnel

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".

Create your tunnel configuration file

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>.json

The 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.

Route traffic to your tunnel

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.dev

Run your tunnel

Finally, you can test out your tunnel.

cloudflaredtunnelrun <UUIDorName>

You can also specify a specific configuration file to run

cloudflaredtunnel --configpath/config.yamlrun

Once 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.

Run your tunnel as a service

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.

sudocloudflaredserviceinstall

You may need to manually specify config location. In my case, I did have to specify it.

For example,

sudocloudflared --config /home/{username}/.cloudflared/config.ymlserviceinstall

Note 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

sudosystemctlenablecloudflaredsudosystemctlstartcloudflared

Ensure your tunnel started/is running fine:

sudosystemctlstatuscloudflared

Test out your tunnel by visting the hostname you routed it to.

Example: cloudflared run in docker

https://gist.github.com/joejordanbrown/b63f82a298da208a5e4780c2200af8fb

Example: cloudflared run in docker


  1. 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
  1. 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
  1. 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
  1. 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
  1. 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:404

Possible helpful GitHub issue

cloudflare/cloudflared#504

References 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 Cloudflare

Another 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:404

Cloudflared documentation

NAME:
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)

Set up your first tunnel

https://github.com/cloudflare/cloudflare-docs/blob/production/contenthttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/tunnel-guide.md

title: Set up your first tunnel

When setting up your first Cloudflare Tunnel, you have the option to create it:

Prerequisites

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.

.deb install

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.deb

​.rpm install

Use 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.rpm
Build 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/cloudflared

Depending on where you installed cloudflared, you can move it to a known path as well.

mv /root/cloudflared/cloudflared /usr/bin/cloudflared

Useful terms

{{}}

Review terminology for tunnels setup locally through the CLI.

Tunnel

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.

Tunnel 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.

Tunnel name

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.

Connector

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.

Default cloudflared directory

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.

OSPath to default directory
Windows%USERPROFILE%\.cloudflared
MacOS and Unix-like systems~/.cloudflared, /etc/cloudflared, and /usr/local/etc/cloudflared, in this order.

Configuration file

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 rule

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.

Cert.pem

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.

Credentials file

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

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.

Virtual Networks

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.

2. Authenticate cloudflared

cloudflared tunnel login

Running 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 cloudflared directory.

3. Create a tunnel and give it a name

cloudflared tunnel create <NAME>

Running this command will:

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 list

4. Create a configuration file

Create 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>.json

If you are connecting a network

tunnel: <Tunnel-UUID>
credentials-file: /root/.cloudflared/<Tunnel-UUID>.json
warp-routing:
enabled: true

Confirm that the configuration file has been successfully created by running:

cat config.yml

5. Start routing traffic

Now 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 show

6. Run the tunnel

Run 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.

{{

}}

7. Check the tunnel

Your tunnel configuration is complete! If you want to get information on the tunnel you just created, you can run:

cloudflared tunnel info

pcx-content-type: how-to

title: Create a Tunnel

Create a Tunnel

Before you start
1. Add a website to Cloudflare
2. Change your domain nameservers to Cloudflare
3. Install and authenticate cloudflared

Create a Tunnel

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.

Create a tunnel

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.

{{}}

Actioncert.pemCredentials file
Create a new TunnelRequired-
Delete a TunnelRequired-
Run a TunnelAvailableRequired
Create DNS records
from cloudflared
Required-
Connect to load balancer
pools from cloudflared
Required-
Route traffic to a running Tunnel
from the Cloudflare dashboard
AvailableAvailable

{{}}

List available Tunnels

cloudflared can list all created Tunnels in your account, as well as those actively connected to Cloudflare, by running the following command:

cloudflared tunnel list

Note: the command requires the cert.pem file.

List tunnels

Revoke and delete a Tunnel

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.

Query Postgres from Workers using a database connector

Overview

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.

Basic project scaffolding

To get started:

  1. Run the following git command to clone a basic Postgres database connector project.
  2. After running the git clone command, cd into the new project.
git clone https://github.com/cloudflare/worker-template-postgres/
cd worker-template-postgres

Cloudflare Tunnel authentication

To 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 login

Running this command will:

  • Prompt you to select your Cloudflare account and hostname.
  • Download credentials and allow cloudflared to create Tunnels and DNS records.

Start and prepare Postgres database

Start the Postgres server

{{

}}

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:

  1. postgres
  2. pgbouncer - Placed in front of Postgres to provide connection pooling.
  3. 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 detached

docker-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.

Import example dataset

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 postgres

The above commands will download the SQL schema and dataset files from Pagila's GitHub repository and execute them in your local Postgres database instance.

Edit Worker and query Pagila dataset

Database connection settings

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.

Query Pagila dataset

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));

Worker deployment

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.dev

Set secrets

https://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_SECRET

Test the Worker

Request 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=language

Cleanup

Run the following command to stop and remove the Docker containers and networks:

docker compose down
# Stop and remove containers, networks

Related resources

If you found this tutorial useful, continue building with other Cloudflare Workers tutorials below.

Cloudflare Workers + PostgreSQL

https://developers.cloudflare.com/workers/tutorials/query-postgres-from-workers-using-database-connectors/

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.

Usage

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 hostname property must be the URL to your Cloudflare Tunnel, NOT your database host
    • your Tunnel will be configured to connect to your database host

Running the Postgres Demo

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.

Usage

from within scripts/postgres, run:

  1. Create credentials file (first time only)
docker run -v ~/.cloudflared:/etc/cloudflared cloudflare/cloudflared:2021.10.5 login
  1. Start a local dev stack (cloudflared/pgbouncer/postgres)
TUNNEL_HOSTNAME=dev.example.com docker-compose up

About

Query Postgres from Workers using a database connector. Retrieve data in your Cloudflare Workers applications from a PostgreSQL database using Postgres database connector

Resources

Code of conduct

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - coding-to-music/postgres-cloudflare-docker: Query Postgres from Workers using a database connector. Retrieve data in your Cloudflare Workers applications from a PostgreSQL database using Postgres database connector · GitHub
Skip to content

Repository files navigation

postgres-cloudflare-docker

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.Cleanup

🚀 Javascript full-stack 🚀

https://github.com/coding-to-music/postgres-cloudflare-docker

By Cloudflare Documentation

https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/tunnel-useful-terms/#default-cloudflared-directory

https://developers.cloudflare.comhttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/tunnel-guide/#set-up-a-tunnel-locally-cli-setup

https://developers.cloudflare.comhttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/create-tunnel/

https://github.com/cloudflare/cloudflare-docs/blob/production/contenthttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/tunnel-guide.md

https://github.com/cloudflare/cloudflare-docs/blob/production/contenthttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/create-tunnel/index.md

https://developers.cloudflare.com/workers/tutorials/query-postgres-from-workers-using-database-connectors/

Environment Values

GitHub

gitinitgitadd .
gitremoteremoveorigingitcommit -m"first commit"gitbranch -Mmaingitremoteaddorigingit@github.com:coding-to-music/postgres-cloudflare-docker.gitgitpush -uoriginmain

Naming and storing a configuration file

cloudflared 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-name

How to setup a Cloudflare Tunnel

https://dev.to/realchaika/how-to-setup-a-cloudflare-tunnel-on-linux-40d9

Installing Cloudflared

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.

.deb install (Ubuntu, Linux Mint, Debian, etc)

wget -qhttps://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64.deb && sudo dpkg -i cloudflared-linux-amd64.deb

​ .rpm install (Centos, Fedora, Rhel, OpenSusu, etc)

wget -qhttps://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-x86_64.rpm && sudo rpm -i cloudflared-linux-x86_64.rpm 

Login to Cloudflared

cloudflaredtunnellogin

This 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.

Create a tunnel

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".

Create your tunnel configuration file

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>.json

The 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.

Route traffic to your tunnel

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.dev

Run your tunnel

Finally, you can test out your tunnel.

cloudflaredtunnelrun <UUIDorName>

You can also specify a specific configuration file to run

cloudflaredtunnel --configpath/config.yamlrun

Once 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.

Run your tunnel as a service

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.

sudocloudflaredserviceinstall

You may need to manually specify config location. In my case, I did have to specify it.

For example,

sudocloudflared --config /home/{username}/.cloudflared/config.ymlserviceinstall

Note 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

sudosystemctlenablecloudflaredsudosystemctlstartcloudflared

Ensure your tunnel started/is running fine:

sudosystemctlstatuscloudflared

Test out your tunnel by visting the hostname you routed it to.

Example: cloudflared run in docker

https://gist.github.com/joejordanbrown/b63f82a298da208a5e4780c2200af8fb

Example: cloudflared run in docker


  1. 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
  1. 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
  1. 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
  1. 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
  1. 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:404

Possible helpful GitHub issue

cloudflare/cloudflared#504

References 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 Cloudflare

Another 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:404

Cloudflared documentation

NAME:
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)

Set up your first tunnel

https://github.com/cloudflare/cloudflare-docs/blob/production/contenthttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/tunnel-guide.md

title: Set up your first tunnel

When setting up your first Cloudflare Tunnel, you have the option to create it:

Prerequisites

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.

.deb install

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.deb

​.rpm install

Use 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.rpm
Build 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/cloudflared

Depending on where you installed cloudflared, you can move it to a known path as well.

mv /root/cloudflared/cloudflared /usr/bin/cloudflared

Useful terms

{{}}

Review terminology for tunnels setup locally through the CLI.

Tunnel

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.

Tunnel 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.

Tunnel name

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.

Connector

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.

Default cloudflared directory

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.

OSPath to default directory
Windows%USERPROFILE%\.cloudflared
MacOS and Unix-like systems~/.cloudflared, /etc/cloudflared, and /usr/local/etc/cloudflared, in this order.

Configuration file

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 rule

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.

Cert.pem

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.

Credentials file

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

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.

Virtual Networks

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.

2. Authenticate cloudflared

cloudflared tunnel login

Running 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 cloudflared directory.

3. Create a tunnel and give it a name

cloudflared tunnel create <NAME>

Running this command will:

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 list

4. Create a configuration file

Create 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>.json

If you are connecting a network

tunnel: <Tunnel-UUID>
credentials-file: /root/.cloudflared/<Tunnel-UUID>.json
warp-routing:
enabled: true

Confirm that the configuration file has been successfully created by running:

cat config.yml

5. Start routing traffic

Now 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 show

6. Run the tunnel

Run 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.

{{

}}

7. Check the tunnel

Your tunnel configuration is complete! If you want to get information on the tunnel you just created, you can run:

cloudflared tunnel info

pcx-content-type: how-to

title: Create a Tunnel

Create a Tunnel

Before you start
1. Add a website to Cloudflare
2. Change your domain nameservers to Cloudflare
3. Install and authenticate cloudflared

Create a Tunnel

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.

Create a tunnel

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.

{{}}

Actioncert.pemCredentials file
Create a new TunnelRequired-
Delete a TunnelRequired-
Run a TunnelAvailableRequired
Create DNS records
from cloudflared
Required-
Connect to load balancer
pools from cloudflared
Required-
Route traffic to a running Tunnel
from the Cloudflare dashboard
AvailableAvailable

{{}}

List available Tunnels

cloudflared can list all created Tunnels in your account, as well as those actively connected to Cloudflare, by running the following command:

cloudflared tunnel list

Note: the command requires the cert.pem file.

List tunnels

Revoke and delete a Tunnel

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.

Query Postgres from Workers using a database connector

Overview

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.

Basic project scaffolding

To get started:

  1. Run the following git command to clone a basic Postgres database connector project.
  2. After running the git clone command, cd into the new project.
git clone https://github.com/cloudflare/worker-template-postgres/
cd worker-template-postgres

Cloudflare Tunnel authentication

To 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 login

Running this command will:

  • Prompt you to select your Cloudflare account and hostname.
  • Download credentials and allow cloudflared to create Tunnels and DNS records.

Start and prepare Postgres database

Start the Postgres server

{{

}}

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:

  1. postgres
  2. pgbouncer - Placed in front of Postgres to provide connection pooling.
  3. 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 detached

docker-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.

Import example dataset

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 postgres

The above commands will download the SQL schema and dataset files from Pagila's GitHub repository and execute them in your local Postgres database instance.

Edit Worker and query Pagila dataset

Database connection settings

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.

Query Pagila dataset

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));

Worker deployment

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.dev

Set secrets

https://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_SECRET

Test the Worker

Request 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=language

Cleanup

Run the following command to stop and remove the Docker containers and networks:

docker compose down
# Stop and remove containers, networks

Related resources

If you found this tutorial useful, continue building with other Cloudflare Workers tutorials below.

Cloudflare Workers + PostgreSQL

https://developers.cloudflare.com/workers/tutorials/query-postgres-from-workers-using-database-connectors/

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.

Usage

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 hostname property must be the URL to your Cloudflare Tunnel, NOT your database host
    • your Tunnel will be configured to connect to your database host

Running the Postgres Demo

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.

Usage

from within scripts/postgres, run:

  1. Create credentials file (first time only)
docker run -v ~/.cloudflared:/etc/cloudflared cloudflare/cloudflared:2021.10.5 login
  1. Start a local dev stack (cloudflared/pgbouncer/postgres)
TUNNEL_HOSTNAME=dev.example.com docker-compose up

About

Query Postgres from Workers using a database connector. Retrieve data in your Cloudflare Workers applications from a PostgreSQL database using Postgres database connector

Resources

Code of conduct

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); GitHub - coding-to-music/postgres-cloudflare-docker: Query Postgres from Workers using a database connector. Retrieve data in your Cloudflare Workers applications from a PostgreSQL database using Postgres database connector · GitHub
Skip to content

Repository files navigation

postgres-cloudflare-docker

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.Cleanup

🚀 Javascript full-stack 🚀

https://github.com/coding-to-music/postgres-cloudflare-docker

By Cloudflare Documentation

https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/tunnel-useful-terms/#default-cloudflared-directory

https://developers.cloudflare.comhttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/tunnel-guide/#set-up-a-tunnel-locally-cli-setup

https://developers.cloudflare.comhttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/create-tunnel/

https://github.com/cloudflare/cloudflare-docs/blob/production/contenthttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/tunnel-guide.md

https://github.com/cloudflare/cloudflare-docs/blob/production/contenthttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/create-tunnel/index.md

https://developers.cloudflare.com/workers/tutorials/query-postgres-from-workers-using-database-connectors/

Environment Values

GitHub

gitinitgitadd .
gitremoteremoveorigingitcommit -m"first commit"gitbranch -Mmaingitremoteaddorigingit@github.com:coding-to-music/postgres-cloudflare-docker.gitgitpush -uoriginmain

Naming and storing a configuration file

cloudflared 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-name

How to setup a Cloudflare Tunnel

https://dev.to/realchaika/how-to-setup-a-cloudflare-tunnel-on-linux-40d9

Installing Cloudflared

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.

.deb install (Ubuntu, Linux Mint, Debian, etc)

wget -qhttps://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64.deb && sudo dpkg -i cloudflared-linux-amd64.deb

​ .rpm install (Centos, Fedora, Rhel, OpenSusu, etc)

wget -qhttps://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-x86_64.rpm && sudo rpm -i cloudflared-linux-x86_64.rpm 

Login to Cloudflared

cloudflaredtunnellogin

This 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.

Create a tunnel

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".

Create your tunnel configuration file

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>.json

The 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.

Route traffic to your tunnel

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.dev

Run your tunnel

Finally, you can test out your tunnel.

cloudflaredtunnelrun <UUIDorName>

You can also specify a specific configuration file to run

cloudflaredtunnel --configpath/config.yamlrun

Once 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.

Run your tunnel as a service

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.

sudocloudflaredserviceinstall

You may need to manually specify config location. In my case, I did have to specify it.

For example,

sudocloudflared --config /home/{username}/.cloudflared/config.ymlserviceinstall

Note 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

sudosystemctlenablecloudflaredsudosystemctlstartcloudflared

Ensure your tunnel started/is running fine:

sudosystemctlstatuscloudflared

Test out your tunnel by visting the hostname you routed it to.

Example: cloudflared run in docker

https://gist.github.com/joejordanbrown/b63f82a298da208a5e4780c2200af8fb

Example: cloudflared run in docker


  1. 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
  1. 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
  1. 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
  1. 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
  1. 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:404

Possible helpful GitHub issue

cloudflare/cloudflared#504

References 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 Cloudflare

Another 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:404

Cloudflared documentation

NAME:
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)

Set up your first tunnel

https://github.com/cloudflare/cloudflare-docs/blob/production/contenthttps://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/tunnel-guide.md

title: Set up your first tunnel

When setting up your first Cloudflare Tunnel, you have the option to create it:

Prerequisites

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.

.deb install

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.deb

​.rpm install

Use 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.rpm
Build 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/cloudflared

Depending on where you installed cloudflared, you can move it to a known path as well.

mv /root/cloudflared/cloudflared /usr/bin/cloudflared

Useful terms

{{}}

Review terminology for tunnels setup locally through the CLI.

Tunnel

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.

Tunnel 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.

Tunnel name

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.

Connector

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.

Default cloudflared directory

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.

OSPath to default directory
Windows%USERPROFILE%\.cloudflared
MacOS and Unix-like systems~/.cloudflared, /etc/cloudflared, and /usr/local/etc/cloudflared, in this order.

Configuration file

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 rule

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.

Cert.pem

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.

Credentials file

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

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.

Virtual Networks

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.

2. Authenticate cloudflared

cloudflared tunnel login

Running 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 cloudflared directory.

3. Create a tunnel and give it a name

cloudflared tunnel create <NAME>

Running this command will:

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 list

4. Create a configuration file

Create 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>.json

If you are connecting a network

tunnel: <Tunnel-UUID>
credentials-file: /root/.cloudflared/<Tunnel-UUID>.json
warp-routing:
enabled: true

Confirm that the configuration file has been successfully created by running:

cat config.yml

5. Start routing traffic

Now 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 show

6. Run the tunnel

Run 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.

{{

}}

7. Check the tunnel

Your tunnel configuration is complete! If you want to get information on the tunnel you just created, you can run:

cloudflared tunnel info

pcx-content-type: how-to

title: Create a Tunnel

Create a Tunnel

Before you start
1. Add a website to Cloudflare
2. Change your domain nameservers to Cloudflare
3. Install and authenticate cloudflared

Create a Tunnel

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.

Create a tunnel

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.

{{}}

Actioncert.pemCredentials file
Create a new TunnelRequired-
Delete a TunnelRequired-
Run a TunnelAvailableRequired
Create DNS records
from cloudflared
Required-
Connect to load balancer
pools from cloudflared
Required-
Route traffic to a running Tunnel
from the Cloudflare dashboard
AvailableAvailable

{{}}

List available Tunnels

cloudflared can list all created Tunnels in your account, as well as those actively connected to Cloudflare, by running the following command:

cloudflared tunnel list

Note: the command requires the cert.pem file.

List tunnels

Revoke and delete a Tunnel

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.

Query Postgres from Workers using a database connector

Overview

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.

Basic project scaffolding

To get started:

  1. Run the following git command to clone a basic Postgres database connector project.
  2. After running the git clone command, cd into the new project.
git clone https://github.com/cloudflare/worker-template-postgres/
cd worker-template-postgres

Cloudflare Tunnel authentication

To 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 login

Running this command will:

  • Prompt you to select your Cloudflare account and hostname.
  • Download credentials and allow cloudflared to create Tunnels and DNS records.

Start and prepare Postgres database

Start the Postgres server

{{

}}

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:

  1. postgres
  2. pgbouncer - Placed in front of Postgres to provide connection pooling.
  3. 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 detached

docker-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.

Import example dataset

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 postgres

The above commands will download the SQL schema and dataset files from Pagila's GitHub repository and execute them in your local Postgres database instance.

Edit Worker and query Pagila dataset

Database connection settings

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.

Query Pagila dataset

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));

Worker deployment

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.dev

Set secrets

https://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_SECRET

Test the Worker

Request 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=language

Cleanup

Run the following command to stop and remove the Docker containers and networks:

docker compose down
# Stop and remove containers, networks

Related resources

If you found this tutorial useful, continue building with other Cloudflare Workers tutorials below.

Cloudflare Workers + PostgreSQL

https://developers.cloudflare.com/workers/tutorials/query-postgres-from-workers-using-database-connectors/

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.

Usage

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 hostname property must be the URL to your Cloudflare Tunnel, NOT your database host
    • your Tunnel will be configured to connect to your database host

Running the Postgres Demo

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.

Usage

from within scripts/postgres, run:

  1. Create credentials file (first time only)
docker run -v ~/.cloudflared:/etc/cloudflared cloudflare/cloudflared:2021.10.5 login
  1. Start a local dev stack (cloudflared/pgbouncer/postgres)
TUNNEL_HOSTNAME=dev.example.com docker-compose up

About

Query Postgres from Workers using a database connector. Retrieve data in your Cloudflare Workers applications from a PostgreSQL database using Postgres database connector

Resources

Code of conduct

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages