Introduction

In my pursuit to learn Swift, I’ve decided to branch out into the backend development. That might sound an odd statement to some, as Swift is usually associated only with Apple platforms, but Swift is a cross-platform language!

Apple released Swift to the OSS community with version 2.2, which started a flurry of activity on work to bring Swift support to Linux. Right now, you can run Swift on both macOS and Ubuntu. Most developers will find themselves developing on macOS but packaging for Ubuntu for deployment. It’s typical to containerise the app which offers numerous benefits.

You may be asking, why run Swift for backend workloads at all? The simple answer is familiarity. I come from the world of Xamarin, which is a .NET based mobile development framework. It’s most significant selling point has always been the concept of reusing pre-existing knowledge. In the context of Xamarin, developers could reuse C# experience from web and desktop development, to build native iOS, macOS and Android apps.

It’s not just about reusing code snippets. It’s about reusing existing skills like knowledge of design patterns and best practises, for example. As you learn a language, you learn much more than just syntax It’s this reason that I’ve decided to use Vapor. To help solidify my understanding of Swift and become a better developer.

 

 

 

What is Vapor?

Vapor is an open source web framework written in Swift. It can be used to create RESTful APIs, web apps, and real-time applications using WebSockets. In addition to the core framework, Vapor provides an ORM, a templating language, and packages to facilitate user authentication and authorisation.

WikipediaOct 2019

 

It has a long feature list with a buzzing community who are continually adding new extensions. By default, it contains everything you’d need to get started with developing a backend with Swift. These include features like:

 

  • Authentication
  • REST APIs
  • Caching
  • Crypto
  • URL Routing
  • Validation
  • Websocketss

 

Supported Platforms

Vapor aims to go where Swift goes in terms of OS support, so right now, the only practical production deployment option is Ubuntu. Fortunately, once you’ve containerised the app, it doesn’t matter what the underlying OS is.

Containerising the app means that it’s possible to deploy it almost anywhere. In my case, I deploy locally for testing, before then pushing to Azure Container Registry (ACR) for use in deployment. From ACR, I can then quickly deploy to any number of Azure compute services. Azure Container Registry is a private docker registry for you to store and manage all of your containers in one place. It integrates deeply with other Azure Services, making it straightforward to use containers throughout Azure.

 

Run in Azure

Deciding how and where to host your backend server can be a difficult decision to make. It’s best to choose a compute service tailored to the type of workload your deploying. Below I’ve outlined a few of the offerings available in Azure and the typical workloads that you might deploy to them. The advice below is in the context of a Vapor website or REST API service.

 

Development & Testing

While developing and testing your backend server written in Vapor, you may want to deploy to Azure Container Instances, the fastest way to deploy a container in Azure! While it’s undoubtedly the fastest and easiest way to deploy a container, it isn’t a good idea to rely on Container Instances for production workloads that’ll stick around for a while. Instead, you should use Container Instances for testing in the cloud.

 

Small > Medium Backend

Once the server app has been tested and is confirmed to work, it’s time to deploy to production! There are so many options that it can have a paralysing effect. My advice is to keep it simple to start with and use as many managed services as possible.

If you’re looking for the most straightforward solution, then look no further than Azure App Services. App Services provides the ability to deploy your container to a managed web server quickly. It provides automatic high availability, auto-scaling, deployment slots, VNET integration, and custom domains to name but a few of its features. All you need to worry about is picking a location from our 54 available regions and then deciding how powerful the underlying infrastructure should be.

You’ve plenty of options for picking the spec of your App Services. By default you will be shown Production specs but it’s possible to select a free tier specification within the Dev / Test tab.

 

App Services Spec Selector

 

Massive Scale

If you need a significant amount of compute, you’ll likely want some form of container orchestration service — the most popular of these at the moment is Kubernetes. It gets its name from the Greek word, κυβερνήτης, meaning ‘helmsman’ or ‘pilot’.

While an incredibly popular service for container enthusiasts, it’s not a service that should be deployed on a whim. It’s a hugely complex piece of software, which for smaller teams can be a burden to maintain.

Thankfully, Microsoft provides a free managed instances of Kubernetes with its Azure Kubernetes Service (AKS), designed to help you manage complex micro-service systems.

 

Demo Time

 

Let’s jump into creating a simple Vapor App and learn how to deploy it to Azure!

 

Installing Vapor

Installing Vapor is super easy as it’s available via HomeBrew. This will install everything you need to get started with Vapor!

 

brew tap vapor/tap
brew install vapor/tap/vapor

//verify after install
vapor --help

 

Sample Project

We’re going to keep things pretty simple on the Vapor side of things, instead opting to focus on the Azure piece of the puzzle.

To achieve this, we’ll use the default template provided by Vapor Toolbox and only make minor modifications.

 

New Project

Open terminal and use the following commands:

 

//Creates a new project named AzureSampleAPI
vapor new AzureSampleAPI

//Change directory 
cd AzureSampleAPI 

 

Vapor Toolbox successfully created new project

 

//create Xcode project
vapor xcode

When it’s finished creating an Xcode project for you, you’ll be prompted to open it.

 

Open in Xcode?

Opening the project in Xcode will kick off the Indexing process, which can take a little while depending on your system. Once everything is indexed, you’re ready to build and test locally. You’ll need to change the current scheme from AzureSampleAPI to Run. You can then click Play or Cmd + R to run your backend API.

 

Swift backend API running locally

 

Containerising for Deployment

Now we know that the server app runs locally on macOS, we want to test if it’ll run in a container running Ubuntu.
Thankfully the team at Vapor have made this simple through providing a pre-built Dockerfile to kickstart the process.
You can find the Dockerfile named web.dockerfile in the root directory of AzureSampleAPI directory created earlier. We will need to edit a few values before we can use it though! You’ll want to change line 30s environment to ‘development’.

 

//Old 
ENV ENVIRONMENT=$env

//New 
ENV ENVIRONMENT=development

 

Docker Build

Next up is to use the dockerfile which is responsible for defining the build process that builds our container. To do this, we can call the Docker Build command.

 

docker build -t azuresampleapi -f web.dockerfile  .

This starts the build process, which can be a time-consuming process as Docker needs to download all the dependencies required for the build.

While I’m building locally at the moment, it’s worth noting that the Azure Container Registry provides the functionality to execute remote Docker builds. This is a handy feature for those who might have limited bandwidth and connectivity as you can avoid needing to download all the dependencies locally. This is great for those times when you’re working in a cafe and don’t have hours to kill waiting for downloads.

 

Creating Docker Image

 

 

Running Locally

To run our newly created Docker container locally, we can execute the following command in Terminal:

 

docker run -it -p 80:80 azuresampleapi

You can then navigate to 127.0.0.1, and you’ll see that Vapor is successfully able to fulfil the request.

 

Running Vapor API in Docker Container Locally

 

Deploying to Azure

In order to continue, you’ll need to have an Azure account. You can sign up to Azure for free and the first 12 months includes lots of premium services for free!

Once you’ve signed up, head over to the portal at portal.azure.com, the Azure portal provides an easy way to get started with Azure deployments. It allows you to browse, configure and maintain services across the globe. It also provides the ability to create dashboards of important metrics for your apps. Below is an example dashboard I’ve made for one of my iOS apps. 

 

Azure portal dashboard

 

Azure CLI

If you’re going to get the most out of using Azure, then I highly recommend downloading and installing the Azure CLI. It’s our open-source command-line tool for interacting with Azure Resources. It can be installed using HomeBrew with the following command:

 

brew update && brew install azure-cli

 

Azure Container Registry

To create an Azure Container Registry, you’ll want to click the hamburger menu in the top left corner of the screen. You’ll then be able to select “Create new Resource”. You can then search for Container Registry or any other Azure Service you’d like to deploy.

 

When creating any new Azure resources, you’ll need to provide some configuration data. As a general rule, you’ll need to provide at least a name and a resource group.

 

Registry Name: The name of your container registry need to be unique. The portal will show you a tick if the name you’ve provided is available.

Subscription: Pick the Azure subscription you want to associate with this service.

Resource Group: Consider this a logical container for all the services related to a particular task. In this example, let imagine we’ve a payroll service. It’ll likely have at least an API, a database and some authentication. These three separate services are all required for the a functioning system, thus get grouped together.

Location: Pick from our 54 regions. It’s a good idea to place the service as close to your users as possible.

Admin User: When enabled, you get a single user, username/password combination you can immediately use to interact with the registry.

SKU: Pick the right service tier for you. Defaults to Standard, which  includes increased storage and image throughput.

 

 

 

Log into Azure Container Registry with the CLI

We’re going to be pushing our containers from our macs up to Azure Container Registry. For this to happen, we must first authenticate the CLI ACR.

Firstly, we’ll want to ensure that we’ve enabled the Admin User. To do this, select the ‘Access Keys’ in the side menu within the Azure Portal. You should then be able to toggle on the “Admin user” feature.

 

Azure Container Registry – Access Control

In my case, the above credentials get mapped to the following command:

 

az acr login --username vaporapisample --password SfIErFrzU8Ek0P4h+0ZFvfMA94YOXU06 --name vaporapisample

You should then receive a “Login Successful” response. You’re now ready to tag and push the previously locally built container.

 

Finding the container

To start let’s list out all our currently installed containers.

 

 docker container ls -a          

 

Docker Containers listed in terminal

In my case, it’s obvious which container image I wish to use as I only have the one. For you, it’ll be important to ensure you’ve tagging the correct container.

 

//Tag Container Image
docker tag azuresampleapi vaporapisample.azurecr.io/learning/vapor

//Push to Azure Container Registry 
docker push vaporapisample.azurecr.io/learning/vapor

 

Pushing local container to Azure

Once the push has completed, you should head back over to the Azure portal. In the repositories tab of the slide bar, you should now see your newly pushed containers.

 

Container Registry – Post Push

 

Running the container!

Now that we’ve deployed the container to the container registry, let’s take a look at how we can spin up an instance and make it available to all.

 

Container Instances

As mentioned previously, Azure Container Instances offers the easiest path for getting started. Still, it is not wise to leave a Container Instance running forever as there are more cost-effective ways of running your contained workloads in Azure. With that said, let’s go ahead and deploy with ACI!

 

Create a new resource

As before, we’re going to deploy a new Azure resource, in this case, a Container Instance. To do this, click the hamburger menu in the top left of the screen and select “Create a resource”.

Next up is to search to “Container Instances” and then click “Create” on the results.

 

Create an Azure Container Instance

Just as before, we’ll need to provide a variety of parameters as part of the initial configuration.

 

Many options for configuring the container instance

You’ll want to select “private” for the Image Type property as we’re going to provide the container image from Azure Container Registry. You should use the same credentials you used earlier in the CLI.

Once you’ve filled in all the options, you can skip to “Review + create” to start the deployment process.

 

Deploying Azure Container Instance

Once the deployment has completed, you should navigate to the new resource. You’ll see a dashboard like the following:

 

Successfully deploy container

Within the overview for the Container Instance, you should see the IP Address property. Copying and pasting this into your browser should result in seeing “It works!” being printed.

 

Vapor app running in Azure!

 

Conclusion

Wrapping up this post, I can see massive potential in using Vapor in my projects. There is an untold benefit when a team to standardise on technology or language, and Vapor allows me to do just that!

While the Vapor Toolbox provides an idiot-proof way to deploy your server apps to Vapor Cloud and Heroku, I hope the above shows just how simple it can be to take your Vapor server app and run it in Azure.

 

Azure Learning

If you’re interested in learning more about containers with Azure, then I can highly recommend our Microsoft Learn portal for free, interactive learning.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.