May 4, 2022 By Enrico Regge 5 min read

How to configure a custom domain to point to an application running on IBM Cloud Code Engine by proxying traffic through Cloudflare and intercepting requests with an Edge Function.

IBM Cloud Code Engine is the easiest way to deploy your source code or container to the IBM Cloud. Our goal always has been to allow you to focus on the development of the application code itself, while Code Engine manages the underlying infrastructure. Part of that infrastructure is automatically providing a secure and reliable HTTP endpoint for your applications, which includes DNS routing and TLS certificates. Once your application is deployed, it will be accessible via a generic URL like this: https://<myprefix>.<randomcharacters>.<region-name>.codeengine.appdomain.cloud

That is fine for testing, but for end-user facing content, you will likely want to use your own custom domain for your application. Something like https://example.com.

In this blog post, I will walk you through the various steps needed to configure a custom domain and then point it to your application running on Code Engine. The goal of this blog post is to create a setup designed to serve personal and small business use cases, without adding any additional costs beyond obtaining the domain name. This will be achieved by completing the following three setup steps:

  • Step 1: Allow Cloudflare to handle your domain
  • Step 2: Create an Edge Function that resolves to your Code Engine application
  • Step 3: Configure the Edge Function to intercept each call to your domain

In a later blog post, I will explain how this configuration can be extended to also serve business-critical workloads of enterprise customers.

How to configure your custom domain for an IBM Cloud Code Engine app 

Prerequisite steps 

Yes — you’ll need a domain. If you haven’t already, purchase the domain of your choice at the registrar of your choice. You don’t need additional SSL or other hosting capabilities; the plain domain is good enough. If you already have a domain, it is noteworthy that you’ll need to have full control over it, which includes its DNS routing configuration.

The solution described in this post requires you to move the routing controls of your domain to Cloudflare. In case this requirement is not applicable to you, please don’t hesitate to reach out by contacting IBM support and creating a support case to discuss your concrete use case and viable alternative options.

If you don’t have an IBM Cloud Code Engine application running yet, go to “Getting Started with Code Engine” in the documentation and deploy your first container or simply deploy your source code directly as an application:

Step 1: Allow Cloudflare to handle your domain 

  • Open the Cloudflare website and create an account using the free plan.
  • Once your account has been verified, you can go ahead and add a site. After entering your domain, choose the free plan and continue the onboarding dialogue. Learn more about these onboarding steps by reading the following Cloudflare article — “Add site to Cloudflare“:
  • On the next page, you are asked to review your DNS records. Make sure that all subdomains and the root domain to be handled by applications running on Code Engine have an A or CNAME record. At this point, it does not matter to which target IP or domain the record points to. If there is no record for the root domain, you can go ahead and create an A record for the name “@” that points to the IPv4 address 9.9.9.9.
  • In order to complete the site onboarding, you’ll need to configure a custom DNS within the configuration of your registrar by entering the nameservers that are listed by Cloudflare. By entering the nameservers, you basically transferring the name resolution of the domain to Cloudflare. Please note that this step can take up to 24 hours until the configuration has been populated in the Internet. Once it has been completed, you’ll receive an email from Cloudflare:
  • To complete this step, navigate to the SSL/TLS > Overview page and set the encryption mode to Full. Furthermore, I recommend that you enable always use HTTPS on the SSL/TLS > Edge Certificates page to activate the redirect of incoming http:// requests to https://.

Step 2: Create an Edge Function that resolves to your Code Engine application

  • On the Cloudflare dashboard of your domain, navigate to the Workers page and click Manage workers
  • Create a new Worker Service and select HTTP handler as starter. If you are interested in learning more about the concept of Workers, you’ll find useful information in the Cloudflare article “Workers Services.”
  • On the Worker Service configuration page click the Quick edit  button to enter the JavaScript editor.
  • Copy the following code snippet and replace the Code Engine application domain placeholder:
    addEventListener('fetch', (event) => {
        const mutable_request = new Request(event.request);
        event.respondWith(directRequestToCodeEngineApp(mutable_request));
    });
    
    async function directRequestToCodeEngineApp(request) {
        // FQDN of the Code Engine application that should receive the traffic
        const targetHost = '<app-name>.<randomcharacters>.<region-name>.codeengine.appdomain.cloud';
        
        try {
          const url = new URL(request.url);
    
          // let the code engine know what origin the request came from
          request.headers.set('X-Forwarded-Host', url.hostname);
          request.headers.set('host', targetHost);
    
          // override the hostname
          url.hostname = targetHost;
    
          // enforce HTTPS towards Code Engine
          url.protocol = "https:";
        
          // pass the request to the application running on Code Engine
          return await fetch(url.toString(), request);
        } catch (error) {
          // in case of an error, play the regular request
          console.log(`Failed to pass reqzest to '${targetHost}'`, error);
          return await fetch(request);
        }
    }
  • Click Save and Deploy followed by Send to verify whether the edge function works as expected and can route traffic to the Code Engine application:

Step 3: Configure the Edge Function to intercept each call to your domain

  • On the detail page of your newly created Cloudflare Worker Service, navigate to the Trigger tab and add two Routes as zone:
    • *example.com/*
    • *.example.com/*
  • For Zone, select your domain.
  • As a failure-mode option, I recommend choosing the Fail closed (block) option:
  • And that is it! Open the browser, enter your domain and see your Code Engine application serving content:

Summary

In this blog post, I described how to configure a custom domain to point to an application running on IBM Cloud Code Engine by proxying traffic through Cloudflare and intercepting requests with an Edge Function running on Cloudflare Workers. Setting up the different components is straight-forward and adds analytics traffic insights and basic security measures like DDoS protection (even on a free plan). Furthermore, it allows operators to further enhance (e.g., custom certificates, WAF firewall rules, rate limiting) and grow (e.g., increase the request limit of Edge Function executions) by upgrading the respective plans.

In my next blog post, I will demonstrate how Cloudflare on IBM Cloud — a fully integrated IBM Cloud service — can help to protect and optimize the serving aspects of your business-critical workloads running on IBM Cloud Code Engine.

If you have feedback, suggestions, or questions about this post, please reach out to me on Twitter (@ReggeEnrico) or LinkedIn or on StackOverflow by using one of the following tags “ibm-cloud” or “ibm-cloud-code-engine“.

Was this article helpful?
YesNo

More from Cloud

Enhance your data security posture with a no-code approach to application-level encryption

4 min read - Data is the lifeblood of every organization. As your organization’s data footprint expands across the clouds and between your own business lines to drive value, it is essential to secure data at all stages of the cloud adoption and throughout the data lifecycle. While there are different mechanisms available to encrypt data throughout its lifecycle (in transit, at rest and in use), application-level encryption (ALE) provides an additional layer of protection by encrypting data at its source. ALE can enhance…

Attention new clients: exciting financial incentives for VMware Cloud Foundation on IBM Cloud

4 min read - New client specials: Get up to 50% off when you commit to a 1- or 3-year term contract on new VCF-as-a-Service offerings, plus an additional value of up to USD 200K in credits through 30 June 2025 when you migrate your VMware workloads to IBM Cloud®.1 Low starting prices: On-demand VCF-as-a-Service deployments begin under USD 200 per month.2 The IBM Cloud benefit: See the potential for a 201%3 return on investment (ROI) over 3 years with reduced downtime, cost and…

The history of the central processing unit (CPU)

10 min read - The central processing unit (CPU) is the computer’s brain. It handles the assignment and processing of tasks, in addition to functions that make a computer run. There’s no way to overstate the importance of the CPU to computing. Virtually all computer systems contain, at the least, some type of basic CPU. Regardless of whether they’re used in personal computers (PCs), laptops, tablets, smartphones or even in supercomputers whose output is so strong it must be measured in floating-point operations per…

IBM Newsletters

Get our newsletters and topic updates that deliver the latest thought leadership and insights on emerging trends.
Subscribe now More newsletters