IBM Cloud Code Engine is a fully managed, serverless platform that runs your containerized workloads, including web apps, microservices, event-driven functions or batch jobs. In this article, we’re focusing on Code Engine applications that are designed to serve HTTP requests. We will demonstrate how to use the web UI and the CLI to deploy our code. By the end of this post, you will have a clear understanding of how to deploy your own code to Code Engine using your preferred programming language.
Before we can deploy our simple HTTP server, we need to set up Code Engine. If you don’t have an IBM Cloud account yet, you can create one for free here. Be aware that Code Engine requires an account with a valid credit card on file. However, Code Engine provides a generous free tier with ample resources to kickstart your project.
After logging into IBM Cloud, you have two options to interact with IBM Cloud and Code Engine—using the command line interface (CLI) or the web UI.
Here are the steps:
curl -fsSL https://clis.cloud.ibm.com/install/linux | sh
curl -fsSL https://clis.cloud.ibm.com/install/osx | sh
iex (New-Object Net.WebClient).DownloadString('https://clis.cloud.ibm.com/ins tall/powershell')
ibmcloud login
ibmcloud plugin install code-engine
To use the web UI, follow these steps:
You can now proceed to deploy your simple HTTP server. In the next section, we’ll look at the sample code for your HTTP server in Python, Node.js and Go.
The following sample code will start a server on port 8080 and set up a simple GET route that serves a “Hello World” message. The beauty of using Code Engine is that you don’t need any specific modules or configurations. If the code runs successfully on your localhost at port 8080, it will run on Code Engine without any modifications.
// require expressjs const express = require("express") const app = express() // define port 8080 PORT = 8080 app.use(express.json()) // use router to bundle all routes to / const router = express.Router() app.use("/", router) // get on root route router.get("/", (req,res) => { res.send("hello world!!!") }) // start server app.listen(PORT, () => { console.log("Server is up and running!!") })
Find the Github repository here.
package main import ( "fmt" "log" "net/http" ) // create function for route func helloworld(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello, World!") } func main() // use helloworld on root route http.HandleFunc("/", helloworld) // use port 8080 log.Fatal(http.ListenAndServe(":8080", nil)) }
Find the Github repository here.
from flask import Flask import os app = Flask(__name__) # set up root route @app.route("/") def hello_world(): return "Hello World" # Get the PORT from environment port = os.getenv('PORT', '8080') if __name__ == "__main__": app.run(host='0.0.0.0',port=int(port))
It is important to note that Python will require a Procfile:
web: python main.py
Find the Github repository here.
Now that we’ve looked at the sample code, let’s move on to deploying it. The first step is to create a new project. Your application will be contained within this project.
Note that the group Default and region us-east are the default. If you want to target a specific region use the following:
If you want to target a specific group, use the following:
Now that we’ve created a project, let’s move on to deploying our code. We’ll be deploying our Node.js code from a source that’s hosted in a GitHub repository along with the package.json and package-lock.json files. In this repository, you’ll find a sample server written in Node.js (see the sample code above).
Code Engine will now do its job and build and deploy the source code for you. You can click on Test application to obtain the application URL to see your application live.
Define the name of your app:
Define the source of the code:
Note that the source can be a local file on your computer, as well.
When your code is not located in the root directory of your repo or directory, it is important to specify the exact location of your code by using the option --build-context-dir path/to/folder
. To run the example code in the CodeEngine repository (as I am doing), execute the following command:
Let’s briefly discuss how to update your application. For instance, you might want to add a new POST route to your Node.js code that returns data sent to the server:
router.post("/echo", (req, res) => { // echo the message back to the user res.json({ message: req && req.body && req.body.message || "nothing to echo back" }); res.end(); });
ibmcloud ce app update --name appname --src repolink-here --str buildpacks
That’s all you need to do to deploy your app from source. Let’s talk about the magic that happens after you hit Create.
First, Code Engine loads your source code from a repository or from your computer locally. It then builds a container image and runs it on IBM Cloud. Specifically, your container is managed by two open-source technologies—Kubernetes and Knative— that automatically scale your application up and down based on the traffic it receives. This ensures that your application always has enough resources to handle incoming requests, while saving money during low-traffic periods when your application is scaled down again. If it receives no traffic, it will even scale to 0 and stops incurring charges. Once your application receives traffic, it will automatically “wake up” and scale back up to one instance.
Congratulations, you now know how to deploy a simple web app quickly and easily. But what if I told you there’s a way to make your application more efficient? Enter containers.
When you deploy your app from source, Code Engine creates a container image for you. The platform detects the language you’re using and selects a general purpose pre-built image for it. But, of course, it doesn’t know exactly what your app needs or doesn’t need. As a result, the image may be larger than necessary, leading to slower deployment performance and longer start-up times. By defining your own container image, you can optimize your app by ensuring that only the necessary components are included.
Since Code Engine will build the container image for you, you don’t need to worry about installing Docker or getting its daemon to run properly.
To build your own custom image, you’ll need to create a Dockerfile. In this example, we’ll be creating one for the Node.js application. To get started, create a new file called “Dockerfile” without any file extension:
FROM node:alpine WORKDIR /usr/src/app COPY package*.json index.js ./ RUN npm install EXPOSE 8080 CMD ["node", "index.js"]
Use a pre-built image (alpine is extremely lightweight):
FROM node:alpine
Specify a working directory:
WORKDIR /usr/src/app
Copy package.json and package-lock.json:
COPY package*.json index.js ./
Install the required packages:
RUN npm install
Expose the port 8080 to the outside:
Expose 8080
Finally, run the server:
CMD ["node", "index.js"]
Once you have configured your Dockerfile (and added it to your repo or folder) you can easily deploy the image.
Deploying your code with a Dockerfile in the web UI works the same as deploying your code without one. However, in step 8, you will need to select Dockerfile so that Code Engine uses the instructions in your Dockerfile to build the image.
ibmcloud ce app update --name appname --src repolink-here --str dockerfile
Note that it’s important that your Dockerfile is located in the root directory of your project.
By specifying how to build the image, the resulting image size can be dramatically reduced. In my case, I was able to reduce the image size by about 90%. This means that everything will run much faster. If you are interested in learning more about build optimizations, you’ll find useful information in the following article: “Writing a Dockerfile for Code Engine”
Deploying a simple HTTP server to Code Engine is a straightforward process that can be done using different programming languages, including Python, Node.js, Go and more. With Code Engine, you can deploy your code without worrying about the underlying infrastructure, making it easy to focus on writing your code.
In this blog post, we explored how to set up Code Engine using the web UI and the CLI and then provided sample code for the three programming languages. We also demonstrated how to create a new project and deploy your code. With the steps outlined in this post, you should have a clear understanding of how to deploy your own code to Code Engine using your preferred programming language and method.
Try it out for yourself and see how easy it is to deploy your code to IBM Cloud Code Engine.