Integration Architecture

Articles by Mike Gough.

Published on 27 Jan 2020.🕑 3 minutes read.

Containerising a Vapor application

Learn how to generate and containerise a server-side API using Swift and Vapor inside of a Docker container.

Prerequisites

To keep things simple, we will assume you have already installed the following: Docker Swift * Brew

My setup instructions are based macOS, but you can follow along on Linux as well.

What is Vapor?

Vapor logo

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. It is particularly geared towards projects that utilise the Model View Controller (MVC) style design pattern.

To learn more about Vapor, visit vapor.codes

Installing Vapor

Installing Vapor is a relativly straightforward, it can be done by running the following commands in your preferred Command Line Interface (CLI):

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

Once complete, you can verify that Vapor was installed correctly by running:

vapor --help

This should print a list of command options to the screen.

Creating a Vapor project

Vapor is easy to get started with, for this post we will make use of the built in code generator to create a simple Hello World application. Use the vapor executable we installed to create a new project by running the following command:

vapor new hello-world

Once the project files have been generated, navigate into the directory by running:

cd hello-world

Creating a Docker Image

To create a Docker image containing the Vapor project, we can use the web.Dockerfile file that was generated by running the following command:

docker build --build-arg env=docker -t vapor-image -f web.Dockerfile

This command may take some time to finish, but when complete we will have made a Docker image containing our compiled Vapor project. To run the Docker container and our project we can use the following command:

docker run --name vapor-server -p 8080:80 vapor-image

Docker will run the container and bind port 80 inside of the container to port 8080 on your local machine. If you go to your browser and enter http://localhost:8080/hello, you'll see that Vapor is running inside your container... Hello, World!

Summary

Thats It! In this post we have demonstrated how easy it is to get started with Vapor by generating a server-side Swift project. When then illustrated how that project can be compiled and hosted inside of a Docker container. In future posts we will look at how we can expand on this example to develop Swift mircroservices.

References