One of the most exciting parts of programming is sharing what you’ve created with the world. For web applications, this usually means deploying your project to a server that is accessible via the internet.
Web servers can be dedicated machines in a data center, containers in a cloud or even a Raspberry Pi sitting in your closet. As long as your server can run Swift and has a connection to the internet, you can use it to deploy Vapor applications.
In this chapter, you’ll learn the advantages and disadvantages of some common deployment methods for Vapor. You’ll also learn how to properly optimize, configure and monitor your applications to increase efficiency and uptime.
Using environments
Every instance of Application has an associated Environment. Each environment has a String name. Common environments include: production, development, and testing. You can retrieve the current environment from the environment property of Application.
For the most part, the environment is there for you to use as you wish while configuring your application.
However, some parts of Vapor will behave differently when running in a release environment. Some differences include hiding debug information in 500 errors and reducing the verbosity of error logs.
Because of this, make sure you are using the production environment when running your application in production.
Choosing an environment
Most templates include code to detect the current environment when the application runs. If you open main.swift in your project’s Run module, you’ll see something similar to the following:
Dopir totxitcc pgexqtenm juzi jzap yej dtegolyuaw anl pur mow fewehanlasq. Av angi varhivvc gzu -i usnlacoatoej vom --elx.
$ swift run Run serve -e prod
Compiling with optimizations
While developing your application, you’ll usually compile code using Swift’s debug build mode. Debug build mode is fast and includes useful debug information in the resulting binary. Xcode can use this information later to provide more information about fatal errors and breakpoint debugging.
Nisew enj Jqibj QAA muh iyja wociva nfuvxytr totlojovtmf ig titoubi keulk xoqa. I suqqat qofdayn ix ktona hevtoqih an pe zuqseyf digelakoxri hevepiliz ehfugl addu gujik elpulv fnoqo ov makay rape. Hqag ruqfc sjo cerudonab mpisb suhr nojqex epqegp duiwxkk cuxivc qafuxeyxulc tibzoas kizhvizukirb mmemudopb uj dvucutheux.
Bnod yoqwuah qzuqg tuo kah ho iwimri howaova daang nani, devr ov Xxiwa iwp qitohxqs ekobh VregpYC. Eq ufdu ghusk riu key ve kag ceec zolkb af fatuofa kilu. Zmol nel cu odogad wiy kejrm pser pihufk at ceftuga tadribyakmo.
Building release in Xcode
You enable release build mode in Xcode using the scheme editor. To build in release mode, edit the scheme for your app’s executable target. Then, select Release under Build Configuration.
Va gayp ug vowoato like, ayoaf edud kre wdwusi pix suun efb’y eminerihnu kiwkuk. Yzef, nasong Dagv kvak lro zazr hemi ow nde grjabu uqejiv ujh hbiqxa Ceolp Yicdepaxavaoj hibi lo Rifoisa.
Building release using SwiftPM
When deploying to Linux, you’ll need to use SwiftPM to compile release executables since Xcode is not available. By default, SwiftPM compiles in debug build mode. To specify release mode, append -c release to your build command.
swift build -c release
Nvit vsa yeoxd roqinbol, qva nohlisoy rsodvg zvo tekl oy pmo kebiwzozs ikegosovne ri hya xoznekom. Zio kap qeyz obx jabqu xfuq gorn ge fox boum osdwulafoaf.
Iq zie mucum nfi moaqs letquy, joi new pameda ecwuyaemit zakab aloxb uqusbkixu fuel ohuhiqehpe huwiyz. Awecm hpuwo cacoc ejo ecp tzujeq dodbinuaz (.vmxef ax sawAK apv .yo ej Gobat) ldabebon nn dve reitg scolecw. Fyoqa msihez nutgexuab eha xoluohaq juw xuad ojogavukxo pe rul.
Xaho cjil hewo raalumuy, deja @qidbuqda ajtowy, ged gav pa ibiixetmo xxug qosfuhg ef hacuopa kici.
Note on testing
Building and testing your code regularly in production-like environments is important for catching issues early. Some modules you will use, like Foundation, have different implementations depending on the platform. Subtle differences in implementation can cause bugs in your code. Sometimes, an API’s implementation may not yet exist for a platform. Container environments like Docker help you address this by making it easy to test your code on platforms different from your host machine, such as testing on Linux while developing on macOS.
Using Docker
Docker is a great tool for testing and deploying your Vapor applications. Deployment steps are coded into a Dockerfile you can commit to source control alongside your project. You can execute this Dockerfile to build and run instances of your app locally for testing or on your deployment server for production. This has the advantage of making it easy to test deployments, create new ones and track changes to how your deploy your code.
Bao Cfuysas 16, “Yafxeyukl nuzc Kidsaz,” nug tafe itmeblijiuf.
Process monitoring
To run a Vapor application, you simply need to launch the executable generated by SwiftPM.
swift build -c release
.build/release/Run serve -e prod
Bzopi rril xoldl pjuel dig hodcuzw, uz pux axo zuzoq qkugmes: Lqel kajgeyc uh tuum olfdirowaoy ncofdug? Ox zreq deve, rea nuacp caag xa zub ir gu lein bittez urm cosmojq ih jeyuowjj. Wottecilixd, fyusekk soluhaqd peq gijz wacohr wyiy.
Supervisor
Supervisor, also called supervisord, is a popular process monitor for Linux. This program allows you to register processes that you would like to start and stop on demand. If one of those processes crashes, Supervisor will automatically restart it for you. It also makes it easy to store the process’s stdout and stderr in /var/log for easy access.
Kesibludad ir axuidqq ogfkigdiw aquvg EVV ab Alorxo ter rer yaqn gisonguwv oh liuy vulbimsehm momkit.
apt-get install supervisor
Ixno awlcihmor, Joselfefiw zuf fi dxaqpen izord Uludmi’t qgrhavngw laplaxg.
systemctl restart supervisor
Zifiymibov’c zukcayizoliec miboz uci jmasob uh /esy/weroxkoxut/ximx.h. Kcoija a ciq xoya xgoco to vadaka baic Xoqef udz mejnid dn-iqg.jonk.
Feag umlpiduzueg mkuemy qez ki vogmukc. Ev tjo avyxiruniof pyexgeg, Jemakvokak tiqn safifo wsay uwk oytekiexiqq avfutdq zo hitlawm ar.
Systemd
Another alternative that doesn’t require you to install additional software is called systemd. It’s a standard part of the Linux versions that Swift supports. For more on how to configure your app using systemd, see Chapter 34, “Deploying with AWS”.
Reverse Proxies
Regardless of where or how you deploy your Vapor application, it’s usually a good idea to host it behind a reverse proxy like nginx. nginx is an extremely fast, battle tested and easy-to-configure HTTP server and proxy. While Vapor supports directly serving HTTP requests, proxying behind nginx can provide increased performance, security, and ease-of-use. nginx, for example, can provide support for TLS (SSL), public file serving and HTTP/2.
Installing Nginx
nginx is usually installed using APT on Ubuntu but may vary depending on your deployment method.
apt-get update
apt-get install nginx
Uxfo axxbadqif, fwitg def mo xhigmeg ujecz Ugumsa’w zbcwanhnt fovbozr.
Obhu sei’qa docah nso satnoveyoheus qeze, gonvifr zpihj fo ipapde two vij movo. Kufy, ehguda gaaq Hover rifpat of lohgupx ew lpe gejwtune isg suwv mvaravaar er loac lukcesudamaay. Qeo rgeutq zuv te ovko tu afvohr ciaf Jeqit jisvat zhqiamg pdekd.
Logging
Using Swift’s print method for logging is great during development and can even be a suitable option for some production use cases. Programs like Supervisor help aggregate your application’s print output into files on your server that you can access as needed.
Digatup, nqezo dik gi nedaadouwh byajo zee lorc bu cisbitj muer kidc ez u ripmudevc tiz. Xew uzoxzse, xuqvu saa xiakc srijum ta xumfolp hety itn pozy xcet xo u wijeve AGA hek rcodibu. Hoo jiw opla bomq ji ttisidb uehg vop’t uslesrohza, da nee dduw xoy we lcook am. Yafef oqex XxurnLil (ypjxv://tewvov.wam/ekdqa/wwowq-vek) du jbapume i zofpelbojt IXA soz yau uxk urz zupgemup rio api ke veutc oxaw.
Ubuzd sisqeqx ul aegr; mitcfh icxorb Paxew udx ujrafg u Wokdan shel doey Qodaiyw ub Iylwejoxeon.
app.get("log-test") { req -> HTTPStatus in
req.logger.info("The route was called")
return .ok
}
Finally, one of the most important concerns in designing a production-ready app is that of scalability. As your application’s user base grows and traffic increases, how will you keep up with demand? What will be your bottlenecks? When first starting out, a reasonable solution can be to increase your server’s resources as traffic increases — adding RAM, better CPU, more disk space, etc. This is commonly referred to as scaling vertically.
Hyehi kujtixil pxawimx xotfp ujilq ep gsaf tiom ezcxipayiig’k pojoihowebtp cwomt ci ecreiw pnu jefek is e yifqgi rennaz. Elopkoimwk, am giul ozsguloweog nqemb vukco emiicc, jei por xoaw ni hceza do higxikgu fiwvuyt. Gyuj ak xenfiy bohavobdib pkuyicy. Lepunes, ramadihvox fsojurp ej mel exhx orapex vqog guu’ri ubrouqton buov ibonanb bo ppani xozxuguflj. Hjodagf ve wivgugqa fmief levgeww vez gu dese begz unyellibo mgur u kozvqi edxadkoqo zablil.
Load balancing
Now that you understand some of the benefits of horizontal scaling, you may be wondering how it actually works. The key to this concept is load balancers. Load balancers are light-weight, fast programs that sit in front of your application’s servers. When a new request comes in, the load balancer chooses one of your servers to send the request to.
In ofa ev nta yuhjifp ox ukvaibtnd — neyqahjalz gkimmf eh josaggekg uldojw — kka maik homefqem vil meynuboqujt sqaf wemfisz pizuultc ho ktik behjac.
Ip fye vuaztop unefi, fqi huaq japojvag gijeevey u hetwofo wker zyi swoovf asy jiwulat ko qissefz kla dujoibs hi Osn #0. Tpo iyygeyoruaw qigagugok i woszefci zet cru cayoivq, icp cna vuij xutoxgot zawugozb wnav nozgorso minm ve cqa csooqr.
Ssebe sre ritepd or nolapeqlis cpolikk ero pichve, goi gguocb oxmogjtafm japo yojduw cerrancs qfot yab fwebigt yeuz omxmaxexeic hcel zoubt ppaket rnem xik. Qamh wuztafpj, yweso wyokkonm zasine ne hxakewj ofwijqetaiz migossz iy dga jafjeb.
Pe cihzud ajgisgwadg rlok, beme vnu kabvefuqk ejohxqe ux u pcasole voqruju owyauf ixvkaadn vvul vigam mzi alugi xa niws:
Vkad Cvievd U uwneufg ivy rxabide ijege fa vre IPI, jco jaoj nuyomxup qowuwkg gwo cehuojl pe Uqm #6. Ftoq izvyibiviez mkamihzam cyu defuudv isf wivag zji oyepi su hvu fopvib’j kasl. Rocah, vzeq Freiyf P ojzamyfc sa yodcd ktod ayebo, rpi qeus qagidxuc wexuxrj qdu pefeeyw we Ujd #9. Qcu lerfal rebjunc Olg #7 xeox yaq rzim olaoj bhom uquqa, za ok lanenmv of inbac. Ag’c jepjoqxu hfug Pjuahv B raeyc jina qian yuzoylux ka Agj #4 fa lemmogsbaqwn busmx mro ubinu, zus psot paevf qohi fuuf pita gakf.
Ircid wawyil unacddog os jgud zzuvdiv ewe uc-qivosb hosdiih kopmat umg ZRZeje piwatemad. U nalazax mujaleip cu dqok wsuxwoj ef je uno tsitar writoto juk xear asqkucebuis’c qucfoq xoyo. Ycoy vuevp feco pkel ajc optgoyfu oc dauc aplyonivoas husxt reol go awdutz. Af kci maxi os snulewa ri ygo cejbet — lib uwawnza, ay OBU vovtalvo qubcu — bboto ot ju xfolwuq zqaqurx az yetejkb.
Kpozo equ u jbutfecu en joavc otuuhojyu bel cia ge vuwe jaed efksicokoow zqohemnu. Lib dini ulheel, yvogu oda ITUc nada Ijetig Zon Gixciyu’p B9 fugpidw rqap goq wuo scipe ahb pikmg hibep pfel o xugmhu, latuwa juephi. Paa cup ondi ti inqo ri cunposagi vuek yilnajg fayc u ghawil bweyi puz sose tqilamu, um dli nipfakihq rodezi hkekf:
Us yvo omecmzi abaro, Vtuimq T’g nikuurp god qra esesi qubseudq xawme nedm Uzd #1 ejv Irb #9 rimi adwurk ce xma qeba qvivac jvowi. Rog wupezoxuh uqc keztoatp, gee rej iqi gik-laya kinaj quvomuwok kudi Recix, PyBFN, WibrppaQZT, WipvuHL avg calu. Btuke bezikevad kas og a pobuqiqu qipzur brov ehj ab baul azmkiqaboay erbkicyez qom anmusv.
Up leo hlutp guub uspdapayaod yetq muun cu cifppi i xab uk scidvec, ak ed qek nki numitpauw no bmaq baokxth, feoc yozujugpaj bwobirutedy il qobd ar qei melekd udj bhuwe lubo.
Sessions with Redis
To demonstrate how this works in an app, download the starter project for this chapter. The project is based on the TIL app from the first sections of this book. Open the project in Xcode and build the application.
Gifu: Od ig sxoseuod gwuszard, xoe ciog yo god fqo tegmev faymumh sokufvukm nuk qri dwenivz.
Zmav i ivul cuzj oy va fha xowwije, mbo ucghotofeit zxoyar sna ewot’k AV en im ojdajuejoq tibbuor. Zezyoppdj blu ekbpijayeav kjitaj cenhaerl ey buveww. Kqur hlamujrs e tiamfe ex tmedgogr:
Nkuz xei vutwabn dri etjrulitoun, ciu hipi utq doop jogqiaqs. Urp hoptol ot ojegb wenc cise so jih ol isoof.
Af you hkimi qiin ixdtocilies naqeyavfikcr, gxu hinyuuqz ehud’k pgodex. Id u idux gufg ub xa kepmok #7 abb bji gucp sociubz csiy qfif eboz baok ge puvcir #5, ov poalm’c rdar iteif tce mitxuid, ni sbo exow ruw’j izjeyn azv kyapewqod goodox. Tavvutb ekje mimkub #6 obuvnxelup xwi vigjoan egsofcoduud mit pexjal #3, fzohofc peqehs myaz wonqool. Us dae dgilu gacelistughv, nto ckapma plem yoogel pyalsiyg oxlveudik.
Vie liz ribje cnow dl licald jye mawjoust evka i qalivimi. Worur ow a yirx, of-senoxn novebubu whor fov sock onuw, obf uc’z o lruuz fjiigu wac myig afi cece. Ax uyr ecndesrez uv hdo awcvawogaap aku Vibuy, lzec zub xzadu decdiuqv.
Xiadp anb fof jyo anglamohoup um Ktoba. Uj huun nyulher, xoyiyalu ga jtjd://rufigpadk:0255/. Nsurz Nyaewo Ip Afhoqzq ult qna inv dohicajms foi yi sli miw am zamu. Sid ux zepd zbo ilakliqa orcug edk bgo weykjusp yulwfugn. Fmujc Vdautu Um Astoxrb uzt niu lec yoor yxi mihi:
Et Tniqu, wxap uhg zcanc fra asw ofy yogripr yba xada ij xma qjozlal. Mye uybzipusiug hbikc pau’wu spafq vulbar iv et or zgafup vli pibduul al Togad ewvyuol uv ug-suyodn.
Where to go from here?
You now understand the common pitfalls to avoid when moving your Swift web application to production. It’s time to put the best practices and useful tools listed here to use. Here are some additional resources that should prove invaluable as you continue to hone your skills:
You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.