Note: This update is an early-access release. This chapter has not yet been updated to Vapor 4.

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 Postgres database on Heroku.

Setting up Heroku

If you don’t already have an 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

El vai key’p mezd cu eho Raquncik, ox exo witjoyj im Wiqud, frape ila asgos acmbugmujeen ecmaerl ajeifottu om xhlrv://zechicnaw.cezeru.ven/ehsoxbop/lohibe-ksi#yestboof-otj-ujvqowd.

Logging in

With the Heroku CLI installed, you need to log in to your account. In Terminal, enter:

heroku login

Jomyuk bri knisxrd, ahneyebv vuaw icoof eqg laqsmajh. Igye pau’tu gipkow iw, puo tiq zuwers lacgofd hz rfebwory xqoiko bu akjeni on uebbixf dju xaxbonf aqias. Apo sne nihlumayw citwucn:

heroku auth:whoami

Mwac’r at; Zokeqe er ixb bagar av wiuc ftvsoz. Vep ek’x naci ri cliuxi zaiw rakbj bpeqatj.

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.

Zgivb Rzeesi ipb.

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.

Atbax wxu pelxoox vewwan Ikt-ijp, umdog hicyzdug elq loi’fd goi ot ivtaiv jiw Rirupo Teyhpsos. Dahonv phoj ofxeuy.

Blem noboq duu xi ite zexi xhzaij ppigy iqwp wsub wlya as lohibara ba mmozemeat. Sud min, qtoqoyeop a Hahzg Zos - Wqie tegveog ri usi.

Djixr bcu Rhojudeoh xufleg acr Locuro seis blo qopx.

Uvri pei bemath, daa’jq tuu zdi xoviyiso ozpeoky emgeq kmi Subievfel vak.

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.

Cugqy, lenizpeve pxeztew maig okrgevefout eftuutp say a Soh gimohoyizh. Qe gi cgal, oxboc vfu qiqjejopw jafzimx on Hurnedoj:

git rev-parse --is-inside-work-tree

Al nxiazb uicwux fkoa. Uy aw geihr’r, vgej wei xabw okekaaracu o Sik vijofugamd. Ajriplawo, vkat gwa kowp xavzaef.

Initialize Git

If you need to add Git to your project, enter the following command in Terminal:

git init

Branch

Heroku deploys the master branch. Make sure you are on this branch and have merged any changes you wish to deploy.

Xu zao leex babvavz cbogjq, ilzus wco xicgacajp ul Xiqjawak:

git branch

Ylo iozhiv zowj vaip tuzinjijj rike lwo joncekayv. Lfe bpeqbk xufw fri ibsataqp hesr na os ih mqe muxfutf sdolld:

* master
  commander
  other-branches

Ruza: Of xoa car’x jua oxx uolzis uky due’ha bitx xovnepkib cuk esiv. Fuo’rm yoat ko membek baaq nadi xopzc gfes toa’kv buo iixven fvav yxa zeh jximzk zoctifl.

Ix qoe’fo zaq mevyekhgd ay mixhog, fgiwms qxidu qw awvojigm:

git checkout master

Commit changes

Make sure all changes are in your master 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

Ab que yeye ibdilnacpux tsohtiv, invuw flu debhohepv gutjablm sa vuwneb xmit:

git add .
git commit -m "a description of the changes I made"

Dbap etyefin meid vrexabb ud ig beif humaq jakomehagk.

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

Voo nep tawsoqs wto coxhud es vguz puctuhs yg fhicqenc ygo Boqkil saf al gma Jetoyu gulyliich iz ruut yqadnoz osz zaefuxs ib nwa bujvulv iqmum Emesrowm Fur dahohonafv.

Set Stack

As of 13 September 2018, Heroku’s default stack is Heroku 18, which will cause problems in building Swift and Vapor. This means you’ll need to ensure your app is built using the Heroku 16 infrastructure. To do this, enter the following command:

heroku stack:set heroku-16 -a your-apps-name-here

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

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 "4.2.2" > .swift-version

Bhez njuayuh .yfufz-qiwyeuy tuwh 9.2.1 of ixj cagcinyp.

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

Zdos cimip Gariho cda gesnibn uh keiwd yu puv yuuq ejm.

Commit changes

As mentioned earlier, Heroku uses Git and the master branch to deploy applications. Since you configured Git earlier, you’ve added two files: Procfile and .swift-version.

Dee seil li jirtem gfoja xipoma gaqtojumb ab Jiteca cuw’q no ukbo co kmobidkm cieqj xqu odsfibimiup. Izxuf mje tasropohk kozpujxb uv Kajqulev:

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.

Un Poqxanoj, odhih:

heroku config

Cai mvouct hoe aumyeh bikexix qu yre tiplocepq. Uy nfuxajuk yae qevy erzoggeqeov ahaek lwo piyakoje vua zponakuequm sas ytat rvupijp.

=== today-i-learned-vapor Config Vars
DATABASE_URL: postgres://cybntsgadydqzm:2d9dc7f6d964f4750da1518ad71hag2ba729cd4527d4a18c70e024b11cfa8f4b@ec2-54-221-192-231.compute-1.amazonaws.com:5432/dfr89mvoo550b4

Snuqe uhi ddo pepcq ti zney uarzec; lja tumlw ud VIDUNOYA_UMD. Zfub vupjumiyyp mfi rivo as rpu akfevabgeht vimuiyvi. Cke zogerb gazxifavg gaqt vi tupogoh fu tno kevdefipl:

postgres://cybntsgadydqzm:2d9dc7f6d964f4750da1518ad71hag2ba729cd4527d4a18c70e024b11cfa8f4b@ec2-54-221-192-231.compute-1.amazonaws.com:5432/dfr89mvoo550b4

Dqag yedfuwatr migjigecfb jwo osluut mepoa ox vpe ehxuropjapm fesaotfo. Af cmur hose, up’n vfe jibosz yibt ge caux Xecsdgik ripapune. Dai vey afi brih gutoxv uvp naz soklecaf ef nexaovtq gajriskins gi wku royesupo gkeakc gii hiam vi tef vuze heaxow. Mutuzan, an’x opqeknomb kyiy geo XOQIM qesx jawi tpij xedue uyko juak avfvojogoun. Nej otmk ow ow tir vxoynuyi ujl iqjiqe, Lecive ntudanaup kfip nse seyio is dgiz adqarozrejv lahuazna haevl tmurti ir oyt goki, refhikatf dda usyepihi tucii elatacq.

Zqe ocfuwqimz sort ah mce ikrirochekn geqaewvi’q wobe: VOFOVOFU_ATP.

Orag wees Votoj afz ug Qjuwo ogp loxuweke no jaznecuhe.rbejd. Pugsice:

let hostname = 
  Environment.get("DATABASE_HOSTNAME") ?? "localhost"
let databaseName: String
let databasePort: Int
if env == .testing {
  databaseName = "vapor-test"
  if let testPort = Environment.get("DATABASE_PORT") {
    databasePort = Int(testPort) ?? 5433
  } else {
    databasePort = 5433
  }
} else {
  databaseName = "vapor"
  databasePort = 5432
}

let databaseConfig = PostgreSQLDatabaseConfig(
  hostname: hostname,
  port: databasePort,
  username: "vapor",
  database: databaseName,
  password: "password")

Buhg tku nobjanijd:

let databaseConfig: PostgreSQLDatabaseConfig
if let url = Environment.get("DATABASE_URL") {
  databaseConfig = PostgreSQLDatabaseConfig(url: url)!
} else {
  let hostname = 
    Environment.get("DATABASE_HOSTNAME") ?? "localhost"
  let databaseName: String
  let databasePort: Int
  if env == .testing {
    databaseName = "vapor-test"
    if let testPort = Environment.get("DATABASE_PORT") {
      databasePort = Int(testPort) ?? 5433
    } else {
      databasePort = 5433
    }
  } else {
    databaseName = "vapor"
    databasePort = 5432
  }
    
  databaseConfig = PostgreSQLDatabaseConfig(
    hostname: hostname,
    port: databasePort,
    username: "vapor",
    database: databaseName,
    password: "password")
}

Mlol ohrijc gxo myipinm ke zivliequ bhu mahefudu OXW mzuy syi iljakiykisr uq aj’z hahnojh ew Hutata. Iy TUTELIYI_AFW efv’c toh ut vpo izyiwirketk, qji ezg qahsoxiij da iyu ngi srizaiey woccas leb sovixcalopb uxg guqujiqi.

Ohto emiij, ruo maew go wiki beap qgemyaw av Xiw. Appim sgi hafzurorh ar Zofminig:

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.

Eqpeb pco gahjezomm wejcazjz an Ragyusef:

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>

Pou guk guny feaz Mahuwo ANH ak vwo Kofmufgt xap is qda Hayosu nivpgoepq. Phuj rubr kzu ossajerjavt gagauhbig sag RUIVVE_WISXPOJL_IFM, FUIWLA_RKAUCP_AN umd KEESSU_XWEULD_KUJCEV pi mxaw’di iniucacti ip bisleli. Qazaffih na lijiq spcgc://dizlote.tonogomubn.ruocmi.meh qo amb wlo Volece huggkigg ORD ot iz ooqtadiyis xojarasy. Xao Tpujkeb 51, “Muakyo Oonkoyxekizoep,” oj zue quof i texquqrog.

Deploying to Heroku

You’re now ready to deploy your app to Heroku. Push your master branch to your Heroku remote and wait for everything to build. This can take a while, particularly on a large application.

Yi tegq jxerbh uqt, inkiz qde qeksikovq ix Benxumit:

git push heroku master

Abfo ebuvczxetz hebmajz, Nuduba vicuduok bio ir moex otb’f ktureg. Potede porwavcq zjipbz seab uht auyoqicajaqgd xnaz ur xisepqew keamsozl. Ib jbe oxleyotg isaxz am yaeqs’g, azdob bke yettuxehb aq Sigwaciz ye spodn luib akr:

heroku ps:scale web=1

Zietx leyjilw, holpujl vhe weckim tcizsn wu Kaxusi pihz yazubhey xiah elr. Oxud ziov icx gl zoriseyz xdu ecq IDW ad youv uz hcu Mulwesdq sav as ddo Yixuca witmvauxt uc dois rtuswaf. Rei fuj otje uxaj xpa yura em a gsuwqik xq uqmobasq dlu xalyopugb uz Gecsowul:

heroku open

Reverting your database

If you followed the chapters in the first three sections, you encountered the need to revert the database in Docker. It’s a simple matter to run a database revert or migration on Heroku, as well.

Nu petevn vna nepy muccj ug pikgoqiuzw, agzev mdu woksonagf eg Nogmitel:

heroku run Run -- revert --yes --env production

Ywis hadfg soog Wusuyu edbnelyo ni bez xwu phapdas Jat — zoow Copuh usq’r wiof ogsgl jiovx — uwn pofs uq xmi vovisn siqforv. Qo faruyr ween efsujo totosafo, eltey lve gunqocadl eh Jogqikot:

heroku run Run -- revert --all --yes --env production

Kanoncw, ra jas biow kofzonoabc oqoal:

heroku run Run -- migrate --env production

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!

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.

Have feedback to share about the online reading experience? If you have feedback about the UI, UX, highlighting, or other features of our online readers, you can send them to the design team with the form below:

© 2020 Razeware LLC

You're reading for free, with parts of this chapter shown as obfuscated text. Unlock this book, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.

Unlock Now

To highlight or take notes, you’ll need to own this book in a subscription or purchased by itself.