32.
Deploying with Heroku
Written by Logan Wright
Heroku is a popular hosting solution that simplifies deployment of web and cloud applications. It supports a number of popular languages and database options. In this chapter, you’ll learn how to deploy a Vapor web app with a PostgreSQL database on Heroku.
Setting up Heroku
If you don’t already have a Heroku account, sign up for one now. Heroku offers free options and setting up an account is painless. Simply visit https://signup.heroku.com/ and follow the instructions to create an account.
Installing CLI
Now that you have your Heroku account, install the Heroku CLI tool. The easiest way to install on macOS is through Homebrew. In Terminal, enter:
brew install heroku/brew/heroku
If you don’t wish to use Homebrew, or are running on Linux, there are other installation options available at https://devcenter.heroku.com/articles/heroku-cli#download-and-install.
Logging in
With the Heroku CLI installed, you need to log in to your account. In Terminal, enter:
heroku login
Follow the prompts, entering your email and password. Once you’ve logged in, you can verify success by checking whoami to ensure it outputs the correct email. Use the following command:
heroku auth:whoami
That’s it; Heroku is all set up on your system. Now it’s time to create your first project.
Create an application
Visit heroku.com in your browser to create a new application. Heroku.com should redirect you to dashboard.heroku.com. If it doesn’t, make sure you’re logged in and try again. Once at the dashboard, in the upper right hand corner, there’s a button that says New. Click it and select Create new app.
Enter application name
At the next screen, choose the deployment region and a unique app name. If you don’t want to choose your app’s name, leave the field blank and Heroku automatically generates a unique slug to identify the application for you. Whether you create a name, or Heroku assigns you one, make note of it; you’ll use it later when configuring your app.
Click Create app.
Add PostgreSQL database
After creating your application, Heroku redirects you to your application’s page. Near the top, under your application’s name, there is a row of tabs. Select Resources.
Under the section titled Add-ons, enter postgres and you’ll see an option for Heroku Postgres. Select this option.
This takes you to one more screen which asks what type of database to provision. For now, provision a Hobby Dev - Free version to use.
Click Submit Order Form and Heroku does the rest.
Once you finish, you’ll see the database appears under the Resources tab.
Setting up your Vapor app locally
Your application is now setup with Heroku; the next step is to configure the Vapor app locally. Download and open the project associated with this chapter. If you’ve been following along with the book, it should look like the TIL project you’ve been working on. You’re free to use your own project instead.
Git
Heroku uses Git to deploy your app, so you’ll need to put your project into a Git repository, if it isn’t already.
First, determine whether your application already has a Git repository. To do this, enter the following command in Terminal:
git rev-parse --is-inside-work-tree
It should output true. If it doesn’t, then you must initialize a Git repository. Otherwise, skip the next section.
Initialize Git
If you need to add Git to your project, enter the following command in Terminal:
git init
git add .
git commit -m "Initial commit"
These commands create a local Git repository within your project and create an initial commit of your project in that repository.
Branch
Heroku deploys the main branch. Make sure you are on this branch and have merged any changes you wish to deploy.
To see your current branch, enter the following in Terminal:
git branch
The output will look similar to the following. The branch with the asterisk next to it is the current branch:
* main
commander
other-branches
If you’re not currently on main, navigate there by entering:
git checkout main
Git may have automatically created a master branch for you instead of main. If this is the case, navigate to master by entering the following:
git checkout master
Subsequently, you can rename this branch by using the following command:
git branch -m main
The rest of this chapter assumes you have a main branch as your default branch. If you create a branch named main in addition to a master branch, it may cause issues.
Commit changes
Make sure all changes are in your main branch and committed. You can verify by entering the following command. If you see any output, it means you have uncommitted changes.
git status --porcelain
If you have uncommitted changes, enter the following commands to commit them:
git add .
git commit -m "a description of the changes I made"
This ensures your project is committed to your local repository.
Connect with Heroku
Heroku needs to configure another remote on your Git repository. Enter the following command in Terminal, substituting your app’s Heroku name:
heroku git:remote -a your-apps-name-here
You can confirm the format of this command by clicking the Deploy tab on the Heroku dashboard in your browser and looking at the command under Existing Git repository.
Set Buildpack
Heroku uses something called a Buildpack to provide the recipe for building your app when you deploy it. The Vapor Community currently provides a Buildpack designed for Vapor apps. To set the Buildpack for your application, enter the following in Terminal:
heroku buildpacks:set \
https://github.com/vapor-community/heroku-buildpack
Enable Test Discovery
There are some remaining artifacts from the build system on Linux that will search for test files. You want to omit those in preference for automatic discovery, so enter the following command:
heroku config:set SWIFT_BUILD_FLAGS="--enable-test-discovery"
Swift version file
Now that your Buildpack is set, Heroku needs a couple of configuration files. The first of these is .swift-version. This is used by the Buildpack to determine which version of Swift to install for the project. Enter the following command in Terminal:
echo "5.3" > .swift-version
This creates .swift-version with 5.3 as its contents. It’s important to note that files with a leading . are hidden by default on macOS, so you may not see this file in finder.
Procfile
Once the app is built on Heroku, Heroku needs to know what type of process to run and how to run it. To determine this, it utilizes a special file named Procfile. Enter the following command to create your Procfile:
echo "web: Run serve --env production" \
"--hostname 0.0.0.0 --port \$PORT" > Procfile
This gives Heroku the needed command to run your app. If you don’t include the \ before $PORT, then it will interpret this entry as a bash command and will not run properly. Your completed Procfile should match these contents exactly:
web: Run serve --env production --hostname 0.0.0.0 --port $PORT
Commit changes
As mentioned earlier, Heroku uses Git and the main branch to deploy applications. Since you configured Git earlier, you’ve added two files: Procfile and .swift-version. These need to be committed before deploying or Heroku won’t be able to properly build the application. Enter the following commands in Terminal:
git add .
git commit -m "adding heroku build files"
Configure the database
There’s one more thing to do before you deploy your app: You must configure the database within your app. Start by listing the configuration variables for your app.
In Terminal, enter:
heroku config
You should see output similar to the following. It provides you with information about the database you provisioned for this project.
=== today-i-learned-vapor Config Vars
DATABASE_URL: postgres://cybntsgadydqzm:2d9dc7f6d964f4750da1518ad71hag2ba729cd4527d4a18c70e024b11cfa8f4b@ec2-54-221-192-231.compute-1.amazonaws.com:5432/dfr89mvoo550b4
There are two parts to this output; the first is DATABASE_URL. This represents the name of the environment variable. The second component will be similar to the following:
postgres://cybntsgadydqzm:2d9dc7f6d964f4750da1518ad71hag2ba729cd4527d4a18c70e024b11cfa8f4b@ec2-54-221-192-231.compute-1.amazonaws.com:5432/dfr89mvoo550b4
This component represents the actual value of the environment variable. In this case, it’s the direct link to your PostgreSQL database. You can use this direct url for purposes of manually connecting to the database should you need to for some reason. However, it’s important that you NEVER hard code this value into your application. Not only is it bad practice and unsafe, Heroku specifies that the value of this environment variable could change at any time, rendering the absolute value useless.
The important part is the environment variable’s name: DATABASE_URL.
Open your Vapor app in Xcode and navigate to configure.swift. Find the section that sets up the database configuration. Look for this line:
app.databases.use(.postgres(
hostname: Environment.get("DATABASE_HOST") ?? "localhost",
port: databasePort,
username: Environment.get("DATABASE_USERNAME") ??
"vapor_username",
password: Environment.get("DATABASE_PASSWORD") ??
"vapor_password",
database: Environment.get("DATABASE_NAME") ?? databaseName
), as: .psql)
This code works great for the database configurations you’ve used so far, but Heroku passes the entire URL, so you’ll have to make use of that. Replace the line of code above with the following:
if var config = Environment.get("DATABASE_URL")
.flatMap(URL.init)
.flatMap(PostgresConfiguration.init) {
config.tlsConfiguration = .forClient(
certificateVerification: .none)
app.databases.use(.postgres(
configuration: config
), as: .psql)
} else {
app.databases.use(
.postgres(
hostname: Environment.get("DATABASE_HOST") ??
"localhost",
port: databasePort,
username: Environment.get("DATABASE_USERNAME") ??
"vapor_username",
password: Environment.get("DATABASE_PASSWORD") ??
"vapor_password",
database: Environment.get("DATABASE_NAME") ??
databaseName),
as: .psql)
}
This allows the project to retrieve the database URL from the environment if it’s running on Heroku. If DATABASE_URL is not set in the environment, the app continues to use the previous method for determining its database.
Once again, you need to save your changes in Git. Enter the following in Terminal:
git add .
git commit -m "configured heroku database"
Configure Google environment variables
If you completed Chapter 22, “Google Authentication” and are using that as your project here, you must configure the same Google environment variables you used there.
Enter the following commands in Terminal:
heroku config:set \
GOOGLE_CALLBACK_URL=https://<YOUR_HEROKU_URL>/oauth/google
heroku config:set GOOGLE_CLIENT_ID=<YOUR_CLIENT_ID>
heroku config:set GOOGLE_CLIENT_SECRET=<YOUR_CLIENT_SECRET>
You can find your Heroku URL on the Settings tab of the Heroku dashboard. This sets the environment variables for GOOGLE_CALLBACK_URL, GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET so they’re available at runtime. Remember to visit https://console.developers.google.com to add the Heroku callback URL as an authorized redirect. See Chapter 22, “Google Authentication,” if you need a refresher.
Configure GitHub environment variables
If you completed Chapter 23, “GitHub Authentication” and are using that as your project here, you must configure the same GitHub environment variables you used there.
Enter the following commands in Terminal:
heroku config:set \
GITHUB_CALLBACK_URL=https://<YOUR_HEROKU_URL>/oauth/github
heroku config:set GITHUB_CLIENT_ID=<YOUR_CLIENT_ID>
heroku config:set GITHUB_CLIENT_SECRET=<YOUR_CLIENT_SECRET>
You can find your Heroku URL on the Settings tab of the Heroku dashboard. This sets the environment variables for GITHUB_CALLBACK_URL, GITHUB_CLIENT_ID and GITHUB_CLIENT_SECRET so they’re available at runtime. Remember to visit https://github.com/settings/developers to add the Heroku callback URL as an authorized redirect. See Chapter 23, “GitHub Authentication,” if you need a refresher.
Deploy to Heroku
You’re now ready to deploy your app to Heroku. Push your main branch to your Heroku remote and wait for everything to build. This can take a while, particularly on a large application.
To kick things off, enter the following in Terminal:
git push heroku main
Once everything deploys, Heroku notifies you of your app’s status. Heroku normally starts your app automatically when it finishes building. In the unlikely event it doesn’t, enter the following in Terminal to start your app:
heroku ps:scale web=1
Going forward, pushing the main branch to Heroku will redeploy your app. Open your app by visiting the app URL as seen in the Settings tab of the Heroku dashboard in your browser. You can also open the site in a browser by entering the following in Terminal:
heroku open
Where to go from here?
In this chapter, you learned how to set up the app in the Heroku dashboard, configure your Git repository, add the necessary configuration files to your project, and deploy your app. Explore your dashboard and the Heroku Help to learn even more options!