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

IBM Tech Now: April 8, 2024

< 1 min read - ​Welcome IBM Tech Now, our video web series featuring the latest and greatest news and announcements in the world of technology. Make sure you subscribe to our YouTube channel to be notified every time a new IBM Tech Now video is published. IBM Tech Now: Episode 96 On this episode, we're covering the following topics: IBM Cloud Logs A collaboration with IBM watsonx.ai and Anaconda IBM offerings in the G2 Spring Reports Stay plugged in You can check out the…

The advantages and disadvantages of private cloud 

6 min read - The popularity of private cloud is growing, primarily driven by the need for greater data security. Across industries like education, retail and government, organizations are choosing private cloud settings to conduct business use cases involving workloads with sensitive information and to comply with data privacy and compliance needs. In a report from Technavio (link resides outside ibm.com), the private cloud services market size is estimated to grow at a CAGR of 26.71% between 2023 and 2028, and it is forecast to increase by…

Optimize observability with IBM Cloud Logs to help improve infrastructure and app performance

5 min read - There is a dilemma facing infrastructure and app performance—as workloads generate an expanding amount of observability data, it puts increased pressure on collection tool abilities to process it all. The resulting data stress becomes expensive to manage and makes it harder to obtain actionable insights from the data itself, making it harder to have fast, effective, and cost-efficient performance management. A recent IDC study found that 57% of large enterprises are either collecting too much or too little observability data.…

IBM Newsletters

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