Deploying Kitura with Docker & Kubernetes: Getting Started

Kitura servers built in Swift are pretty cool, but it’s even cooler to deploy them in the cloud! See how to build a Docker image, then deploy to Kubernetes.

Version

  • Swift 4.2, macOS 10.14, Xcode 10

Creating a Kitura server in Swift is pretty cool, but it’s even cooler to deploy it live, in the cloud! You want it scalable and load-balanced, so it’s always available. And you want to be able to monitor it.

Kubernetes is a popular platform for deploying and managing any application composed from Docker images. And Kitura apps come with everything you need to build a Docker image, then deploy to Kubernetes.

Note: The word kubernetes is ancient Greek for helmsman, so think of it as a system that steers the container ship that is your app. You deploy apps with the Helm package manager: the local Helm client interacts with a Tiller server, which interacts with Kubernetes. Tiller installs, upgrades and uninstalls Helm charts — application definitions that specify how to deploy your app in Kubernetes.

All the main players have a Kubernetes cloud service where you can deploy and manage your apps:

In this tutorial, you’ll build and push a Docker image for an app named EmojiJournal to Docker Hub, then deploy it to IBM Cloud Kubernetes Service. EmojiJournal is a pre-built Kitura app that allows you to save all your favorite emoji.

Note: This tutorial assumes you know how to create a Kitura app (as in Kitura Tutorial: Getting Started) and you’re comfortable using Docker’s command line interface (as in Docker on macOS: Getting Started).

Getting Started

Click the Download Materials button at the top or bottom of this tutorial to get the project files you’ll use to build the sample Kitura app.

Running Docker

If you don’t have a Docker account, go to Docker’s web page, click the Please Login to Download button, create an account, then respond to the activation email when it arrives.

If you don’t have the Docker Desktop app, download Docker Desktop for Mac, then install and run the app. Moby the whale should appear in your Mac’s status bar:

Docker Desktop in menu bar

Note: If the direct download link above doesn’t work, download from the Docker download page after you activate and sign in with your Docker account.

Setting up Kubernetes on IBM Cloud

Sign up for an IBM Cloud account, or click the Log in button if you already have one.

Note: This is a two-step process. First you sign up for an IBMid and then for an IBM Cloud account. If your IBM Cloud account is not confirmed within a few minutes, switch to using Chrome to trigger the confirmation email. It looks like the IBM site might not be fully-compatible with Safari.

IBM Cloud Signup

Click Catalog:

IBM Cloud Catalog

Next select Kubernetes Service (clear the filter field and click Filter if you are not seeing the Featured Offerings or Kubernetes Service):

Featured Offerings

At this point you will have to use the Upgrade button to upgrade from the free account by providing credit card details, but once you have done that, there is a Lite plan which provides one cluster for free.

When you are back on the Kubernetes page, click Create (you may end up on the Create a new cluster page automatically after entering your credit card details):

Create new cluster

In the cluster configuration page, select Free, choose a location near you, give it the cluster name emojijournalcluster, finally click Create Cluster:

Creating a free cluster

You won’t see any feedback — just wait a short time and you will be directed to the page shown below. You’re limited to one free cluster, and it expires in one month.

In Terminal, run all the commands listed in the Access tab of your new cluster:

Cluster access commands

Note: Use the handy “copy” button.

The Prerequisites command installs helm, kubectl and ibmcloud CLIs.

Commands 1 and 2 are customized with the IBM Cloud and Kubernetes regions that match your location. I’m in Melbourne, Australia so my commands specify au-syd and ap-south. Scroll down if you need to see commands 3, 4 and 5.

Building & Pushing a Docker Image

In this section, you’ll build a Docker image for the sample app, then push it to your Docker account.

You should have already started Docker Desktop, back in the Running Docker section — click on Moby the whale, and sign in to your Docker account (if you’re not already signed in):

Sign in to Docker

Building

In Finder, locate the starter folder EmojiJournalServer, then open Terminal, and cd to this directory:

cd <drag the EmojiJournalServer folder from Finder to the terminal window> 
Note: Check that your full path doesn’t contain any spaces, like Tutorial Projects/Deploy Kitura/starter/EmojiJournalServer — some deeply-buried commands don’t like odd characters in path names. To play it safe, stick to CamelCase for all enclosing folders.

This directory contains the Dockerfile and Dockerfile-tools files you’ll use to build your Docker image.

Next, enter this command:

docker build -t emojijournal-build -f Dockerfile-tools .

You first build the emojijournal-build image that you’ll use to compile your app.

Then, enter this command:

docker run -v $PWD:/swift-project -w /swift-project emojijournal-build /swift-utils/tools-utils.sh build release

You use emojijournal-build to compile your application code into an executable file. This may take a while…

And then, enter this command:

docker build -t emojijournal-run .

You’re finally building the image that you’ll push to Docker Hub, using the default Dockerfile.

Now check your image by running it in a container:

docker run --rm -it -p 8080:8080 emojijournal-run

In your browser, open http://localhost:8080/client:

EmojiJournal on localhost

The app is already hooked up to a CouchDB (IBM-alias Cloudant) database, with entries added by David Okun, when he recorded his Kitura video course. Go ahead and add your own emoji: click the smiley button to open the character menu, select an emoji, then click the big plus sign. It takes a few seconds to update the database and reload the page to show your new emoji.

Note: To stop the server, press Control-C in the terminal window where the container is running. The --rm option in the docker run command removes the container from your system.

Optional: Viewing in Xcode

If you feel more comfortable when you can view the files in Xcode, enter this command:

swift package generate-xcodeproj

This creates an xcodeproj file in the project folder. Open the project in Xcode by double-clicking this file in Finder, or enter this command in Terminal:

open EmojiJournalServer.xcodeproj

You can also use this command to open the project in Xcode:

xed .

Pushing

In a browser, login to Docker Hub and create a new repository named emojijournal.

Create DockerHub repository

Back in Terminal, still in the EmojiJournalServer directory, run this command:

docker tag emojijournal-run:latest <your Docker username>/emojijournal:v1.0.0

You’re creating a tag that refers to your local Docker image — the tag matches your new repository name, and adds a version number.

Note: Kubernetes best practice is to create Docker tags from version numbers or source control commit hash values, not latest. This ensures that Kubernetes pulls and deploys any new images you push to Docker Hub, because the new image has a different tag.

Now push your tagged image to your Docker repository:

docker push <your Docker username>/emojijournal:v1.0.0

Once that has completed, go back to your browser and reload your Docker Hub repo page to confirm it’s there:

Confirm Docker push

Deploying from Docker to Kubernetes

OK, you’re all set to deploy your app to your IBM Cloud Kubernetes cluster! All you need is a Helm chart … what? how? No worries, it’s already in your Kitura app! You just have to customize it with the name of your Docker image.

In the terminal window with working directory EmojiJournalServer, cd to the directory containing the chart files:

cd chart/emojijournalserver/

Next, open EmojiJournalServer/chart/emojijournalserver/values.yaml in your favorite text editor, and edit the image:repository value:

repository: <your Docker username>/emojijournal

Kubernetes looks in Docker Hub by default, so you don’t need to specify the URL — just write the image name as you would in a docker pull command.

And you don’t have to change the tag value, because that’s the tag I told you to use! ;]

Save values.yaml, then initialize Helm:

helm init

This command configures the local Helm client and installs the Tiller server into your Kubernetes cluster. Tiller interacts with Kubernetes to install, upgrade, rollback, query and remove Kubernetes resources based on your Helm chart.

And — finally! — install the chart into your Kubernetes cluster:

helm install --name emojijournal .
Note: If this fails with Error: could not find a ready tiller pod, run tiller in your terminal, Control-C to stop it, and then try again.

Here’s the output of this command, for my deployment:

NAME:   emojijournalserver
LAST DEPLOYED: Sat Feb  9 16:19:28 2019
NAMESPACE: default
STATUS: DEPLOYED

RESOURCES:
==> v1/Service
NAME                TYPE      CLUSTER-IP      EXTERNAL-IP  PORT(S)         AGE
emojijournalserver  NodePort  172.21.136.154  <none>       8080:32078/TCP  0s

==> v1beta1/Deployment
NAME                           DESIRED  CURRENT  UP-TO-DATE  AVAILABLE  AGE
emojijournalserver-deployment  1        0        0           0          0s

==> v1/Pod(related)
NAME                                            READY  STATUS   RESTARTS  AGE
emojijournalserver-deployment-85f48f796c-zc8sl  0/1    Pending  0         0s
Note: Your cluster IP and port values will be different.

The app is starting up, so the values of CURRENT, AVAILABLE, READY, etc. are all 0.

Enter this helm command to see these values updated to 1, once your app is running:

helm status emojijournal

Kubernetes Terminology

So many moving parts! Time for some definitions:

  • Service: An API object that describes how to access applications, such as a set of Pods, and can describe ports and load-balancers.
  • Deployment: An API object that manages a replicated application.
  • Cluster: A set of machines, called nodes, that run containerized applications managed by Kubernetes. A cluster has several worker nodes and at least one master node.
  • Pod: The smallest and simplest Kubernetes object. A Pod represents a set of running containers on your cluster. A Pod is typically set up to run a single primary container.
  • Node: A node is a worker machine, which may be a VM or a physical machine. It has an External IP address — available from outside the cluster — and an Internal IP address, routable only within the cluster. IBM Cloud’s names for these are Public IP and Private IP.

To access your application, you have to find the external IP address of the worker node it has been deployed to. Where is it? Time to go exploring!

Enter this kubectl command for another view of your deployed service:

kubectl describe service emojijournalserver

The output lists the same cluster IP address as the helm status command, and also an Endpoint, a Port (8080) and a NodePort (32078, for me):

Name:                     emojijournalserver
Namespace:                default
Labels:                   chart=emojijournalserver-1.0.0
Annotations:              prometheus.io/scrape=true
Selector:                 app=emojijournalserver-selector
Type:                     NodePort
IP:                       172.21.136.154
Port:                     <unset>  8080/TCP
TargetPort:               8080/TCP
NodePort:                 <unset>  32078/TCP
Endpoints:                172.30.172.155:8080
Session Affinity:         None
External Traffic Policy:  Cluster
Events:                   <none>
Spoiler: Grab your NodePort value — you’ll need it soon!

Accessing your Deployed App

Because you deployed your app to IBM Cloud, you can also view information about it there. On the IBM Cloud Kubernetes Clusters page, select your emojijournalcluster. Then, on the emojijournalcluster page, click the Kubernetes Dashboard button:

Kubernetes dashboard

Scroll down to see your app in the Deployments section, with one Pod running:

Kubernetes deployments

The information in the Kubernetes Dashboard matches the output of the helm and kubectl commands above. But your app is in IBM Cloud, which adds another set of information. Back in the IBM Cloud emojijournalcluster page, select the Worker Nodes tab to see — aha! —Private and Public IP addresses:

Cluster IP addresses

Alternatively, enter this ibmcloud command in Terminal, to get the Public IP address:

ibmcloud cs workers emojijournalcluster

Now you’ve got the numbers you need! In a browser, open {Public IP}:{NodePort}. You should see the Kitura welcome page:

Kitura welcome page

Add /client to the browser location to see the EmojiJournal entries:

Your app in the cloud!

Success!

Connecting to a Database in Kubernetes

Our Server Side Swift with Kitura book uses a PostgreSQL database for EmojiJournalServer, and shows you how to deploy PostgreSQL and EmojiJournalServer to Kubernetes. This is more straightforward than deploying Cloudant/CouchDB because there’s a Helm chart for PostgreSQL in the stable Helm repository. The CouchDB Helm chart is in the incubator.

A similar, but shorter route is IBM’s ToDoBackend tutorial, which shows you how to:

Both of these tutorials run Kubernetes in Docker, completely on your Mac.

Where to Go From Here?

In this tutorial, you built and pushed a Docker image for your app, then deployed it to IBM Cloud Kubernetes Cloud Service, and accessed it in your browser. You used Kubernetes, Helm and IBM Cloud CLI commands, and the IBM Cloud dashboards. That’s just the start! When you deploy your own apps, you can add redundancy, load balancing, and monitoring with custom charts and graphs.

Here are some resources to keep you going:

Also, check out more server-side Swift tutorials!

We hope you enjoyed this tutorial on deploying Kitura with Docker and Kubernetes. If you have any questions or comments, please join the forum discussion below!

Contributors

Comments