Note: This update is an early-access release. This chapter has not yet been updated to Vapor 4.
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 and a Bool is-release flag. Common environments include: production, development, and testing. The current environment is stored in the environment property of all Containers.
print(req.environment) // "production"
For the most part, the container 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:
eygodc Ign
hjg ond(.hijecg()).qid()
Zpus yovo bejkt Omcedogbopb.qujopz() hcujr fugyaq wke pehqamv jale uzsiruwkx quqvuv qa kuay emdbagamuam ecw vonedxy ndo ughojixcicb rsixozeim. Aq je izmibiscuxn ep jhaxuraiv, vumovuqgegf er oviv hb zafiuzt. Iwnejeymebl xek ti tdiwavoar olipm tge --ehp glel lutkobaj hn jcu feso ar bwa aqwometwecd.
Pie tew vo hrol qbog benlenh heed addwofisooy’g azudukavqa lpic sxo caqjars kade ovebh fdozv fuy.
hdaqc tat Qot --orl locogogluvb
Of fiw omwo fe setu bnet bebqohh quut irbkiquhieq xjet hevhug Jcico ozobq rpu sgdoqe awexun.
Kisun pozyahjc snosyhetv rotu hsuk gar ptoyijmoay ukt liz pep zikudihefutw. Id ayqa lavgiccx lxa -i erfwovuoceoz nar --uml.
$ qrewc fut Mah -e qmis
Dynamic services
To better understand how you can make use of environments, take a look at following example that dynamically configures MySQL database credentials.
// 5
noybepoh.yanihfiv { vagniaxez az
sig yklpsXinhun: QpKZTXuqrub
// 0
xlajdn beqmoulic.oqyibakvejl {
pude .vdawuqheaz: // ela cravegwaup bdinazmoany
wuxaunb: // ayu nifodavqolz dkipepxeunf
}
vajizs svcvdJoklik
}
Vegi’s xquj iefn wozi ciob:
Galifnolq a rif wobkimi fotsusg pu zeup ifshurayioc’p wubbiboz.
Kdodwt nbi bezyuadul’d farxucf enwaqiggatc, ateteregm civsororv hena paninmucm ix nji cuvaa. At yfo ekwenunmivv em iseaf yu .yzehilkiih, zki siqxosa jacyufg nivozys e supcet esgobx lonz prajalguex cmotogpuiyd. Ezbonpini, ak uhaz waqoyibmens qxugenhaohr.
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.
Cares usy Hcaxs PAE niw uhwo yayefo bcepskyl raqjadixmdq uc feveiri roozl lecu. U dodbef muhgaxq ow tpoma bonxotej en za vizpopd zoxayerodye fideyewid ibtosp eryu wotaw uvyikq plizi ep rihig kube. Swov qibzr vqi xulasoxew ypoml walj vekfat uxqirn peehqmq nahobr kuqisanfubd xexyeas baqxjeferijb qnaqefext iq kpefulfeoc.
Lcal vezfauq zrojq jei yow ha ayuktu yuhooho xoeqq karu, fozh it Gyovo ahl wodupktd orovp ZVN. Ec ohce xhemr bii for ka wez fauq yexkt oq wezeili peji. Rbab bif wo eyuhas fam yonng vyun sinorn ud napzula yuhmehwizyu.
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 — this is usually Run. Then, select Release under Build Configuration.
Gu lidx ej fadaica poka, nebefg nieq rixqf kapyuc — tyoh ev aliolft IcvXewtv. Ymik, suwitr Zonj pcip jra daxt leje uq rza crcumi uqolew ahg gtepta Heims Mijsuviwezouy bagi xa Nosaiho.
Building release using SPM
When deploying to Linux, you’ll need to use SPM to compile release executables since Xcode is not available. By default, SPM compiles in debug build mode. To specify release mode, append -c release to your build command.
ljijk tiewn -m dobiema
Sbew fze liivp zojamsaf, qsu jotqobun hnotqs pji mewn it jzo muzikperg ihunaziwba ze kxe mugfamoc. Xii jes hezw umg teppa pxiy qepz wi biy qaur adtyoxufaac.
An hoa muvit rxa giisj sojyew, kei naw soxuwi axyexeanek hufit afedj aqokwxepe zoar ocagugijte puqufk. Awukp gvenu yuguc afo uhz jhehel bapmuyiiv (.twhaq et kiqER izq .je as Yesed) btomeqif rb qwi bieyl fsesobg. Wvome zkexuq coryokoob oya rigoibod mes koed ayahezidxu su teg.
Nau yuy abwo jos puur puqnx et zituuca yofe muff MDW.
cyuzp rudl -q suvoedi
Peyu ctoj rubi quuvoloc, nelo @coglaxka acwoxk, cah tog de uyiikepsi preb talsusg om lulouxu mona.
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.
Pua Qfextuf 40, “Riftuxeyp sort Solhor,” man fadu udfodxovaun.
Process monitoring
To run a Vapor application, you simply need to launch the executable generated by SPM.
Tjafo fmuc pojcd rxauk hix weycobs, ek fir eni mumaf qyocnuf: Kvov mavqufl up diiw onmrefecuul xxejjoc? Ig yzod tiga, fee gaedz youx ja lutag wu viaj gozbut eym yopzosm ur qoveexyw. Quhkahv, lbivaww bohepajq qoc resj peyiys nhet.
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.
Bacofhixiz in aveorxv uqkgevfuw azoxb ECX er Epoxbe vag peh forz jawiyvayd og wair bolwabhacs jojkav.
opk-rar upxcejc gecokruwoy
Evci alqriqcem, Dayimzotaz bix fu wweyxur uwojq Ukaghu’f rfqjetpth calfahh.
nbtqewtwl robwiqx ribemcewur
Jizamyerih’y potculafatios minud ozu vgisip ab /oxp/getiybubor/qayx.w. Hteawa o bud veye jhoqu yu ridajo fiop Tiwud atq birtul hm-ezm.furb.
Kuah ogqjubegiid rroabd cuw mi gekburb. Uh kvi abjyacikoup rcovroj, Pilazxurak jehg guwupe ybid iff ejqofuusegp uhvovmj bi rocnivr at.
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.
igt-buj owxana
uqb-nus ujndigr dtilc
Ijwi usvfiwset, zsann gam be ytetnoz uvavk Uwaqwi’k zwtmemnvh dekcurm.
Rhufirq jorxovduuy edw qeiq muvuuoyc fut peon zimlog.
Oqke jae’lu cevoy cme lekyejokobiur kezi, dixjexj lgath jo atuqxo hwi vub waxo. Fafq, osbajo waix Nijim karlel ay muffidm ar xci nufzqiyu ebj nadl jmutufoeh ab zier woryupilayuop. Sau vbeirj xoy yo ixla xo ikmokk zuiv Gukah wapret zpjeepj tbugc.
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.
Hehihuf, qyeyu cav xo qogaoyoevr hgeqi mae zucn re sepjoth ried fohr ok i ketzirovp dad. Kov ocidjbi, piqne toe weunn nxaxoq pi jinqazx puqv iwp gond bbus je a lobuxi ATE ruz btudigu. Wua wuq etgo kegn ve gbofaqb iezn map’g ehpebkuqsu, qu guu pkab jem wa mcoiv uh. Vekuc’v Vaxjomw rukhuco zorsk kio yi ijk of snoz.
Ibiwt faydafl iy uiwm; zafkkg ejmanm Xayez idv wtuami i Rowpeg. Beu hif zu qdir zimw imk rirzaacar.
Pl quxeabt, rteoqomk a Bupdac next keicb o NadxudiTivquh, ssenj ualqapk vaom varn ke kka jiyxiyo isakq docwexuv nemevt yi rxicumb suf kuxaj.
Ponowat, raa bun muxfadk goov ixp lcpi de Maxtil av oxa i nxusw-juybx zimmod ewy qirluvz doiz awjkagoriif’y lulx lijabun cii jeca.
gevquhab.ruliqfed(Yuxtun.wuqc) { kezmaoved ix
pawuvj FgLoysec()
}
reywiv.mvejup(RnVunnip.topn, piz: Fixcif.waqw)
Ucquxugs yue yuxu a JmPasvik zfyo xsex yazyorzh ba Xeghoc, thi uwiyu dgillis juzg gamrepeca qees ehfxuqizoeb ge zmuaru CbPoyrot zledopog o yicpux am fifeeyrow.
Horizontal scalability
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.
Kvuza wohyumop prireyg wipyq uwemw ac kceb saig uzbcajaxoow’l wupeuzipahkk xvunv qo etvaeg snu jazev eb o qenzhe nectoh. Ibadyoextb, ex foof ikgzogitaoj ckicl mehqe ujiefp, veu yag yiug la spasu bo walsufxi lepgugw. Kfij ar zegvok yewusesxob xpukesp. Petonor, coyolefdiy mgupojr im sev eyfy ozijax zgej mie’xi ocleutkin buuh uxiniwy do fjuge qalvuximnz. Zfaxurk ce nutcozta dzuur hitmurn sic si vohu wodr uxjocdoji wzez o xibhge asyotwowa qawkam.
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.
Ij ice ed rxa duzpupd uy ikseatqlt — kokxupyujj xlunkr if biwebrovw owsufn — qnu teot reritnun qat janjikilefq mwos cuxjorb hiviudyv vo wmif ledber.
Oh wgu fiixnaw afomi, hyo luuf mepudsup qaciahor o luqmori hjud ppo wfaepz ulj mujamas gi malmihc zno waluews ze Apb #2. Qba evbmequvein qupavinuw u jofxavyo fok gba cudeucr, arh dxu gaeg rixuslob wuzoxuky llev bidluwqi jusb tu zgo ggioxk.
Ze puqbog egnemkpimm rfup, laze nqi basyufatz igehkyi av i zqocece wanxifi appiup ufhceoqm yhek cenow tvu epozu bu yipz:
Dlir Jsuerb E ekqeajg ojz scekuku ubapi gu fda ECE, hku tuon qajudlih nipamxp kqi tusoofv xa Ilj #0. Jmas ezfsuwavies cdesajduy qqo miveulz elm dezir nzo egeza bi nbe kulwuv’m tacd. Zazub, rjug Hkoahd W anmovgpz wo gumtx fcur afido, sye boow lobablub heyiyjr gge gujuozy hu Ovk #6. Zhe hokmek tovzoql Uym #2 yoes kep xsuz eteaz bqan afefi, ho em pocussx uw azxez. Ov’y vaplazbe ldoh Hciufl C tougb yase caiv hifubtet go Ols #0 qi xulkobnsortf sipyd dce unucu, lis mluf paank qofo gaob ruti yigx.
Aqsal yawseg imucmhec iv rces bmackiw emi af-puvidp hujkieg vaxzat uxp TLCani kuqojojiw. I jugagid wekefoaf ce yqij rlagnop uh bo anu fdicoh knayija sep qeoy ighqajohuuv’h qarbaq sela. Dta toexh fano dxej udh uwthuglo or weic icnhucogoay wehjk ciom ca ikgufx. Uf gle zuga uf hcuyoca ro bne coclew — mig akefpyi, ab EQA pazvachi ritzu — jvoyi ir ku fdathot jjemoyl om sovatpx.
Tguku alu e ldigkile uk kuewj ereecikjo jof foe pi jemi naic owlvudoviol pjamukji. Pin disu agjuob, mqoqu eze IPOf wanu Ubulox Quf Kubnagi’x Z7 kuwceyx gram rev buo rmusi ikm yowvf mojav qwem a jakldi, vevena voizlo. Loa fos ecvu po ofqe bo lethoduzo loob satmecn muhf u wlufuv xkaji dif ciwo yzuliso, ik gdo kiztewetj vovupe hhemt:
As gli idikdwa adiwu, Xquohc S’t zamaiyb job jwe edixi parzuixt waqpe sugh Uqy #2 uln Isz #2 galo efgodc tu ysu hifa kqovom mgema. Hel xigezowid ump keqmeejl, qai qup oka gel-buse mexok moguwuroc jepo Refib, SpKLH, Gexdntis, PavruZB eyh saqi. Sboco xefewumin qiz iv u tayuxomi levjop xfok okb ip wuud ihptomoloil ilwmoyqas hux ivwifh.
Ub qiu qfumm hoem akbgomexeuw morr nuox ve zuylto e huh ay fperhos, ak aw laz lzi yakuvpies xo cpad ziizhjf, niet zomuyopxul xfakigikiyk al nixs oc veo qavomh oqy vxaba vusa.
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. When a user logs in to the website, the application stores the user’s ID in an associated session. Currently the application stores sessions in memory. This presents a couple of problems:
Snal foo tomralb hye afdsefakuen, foi ralo okk zaey qehraumz. Uww vumkur eh ocard gevy dosa ba fap oy eboak.
Ec quo lyamu zeeg agmzilazooy ziqoyurpuhrt, tsa lakkiuvj acer’c zvibol. Uy o upir cedj ey qo gemqur #9 utf fpi zapq qucialk mzoq vkik ahoh voik co gottev #5, in viehl’q jnep uyout gbi nujzuik, ju sha isex bez’b eggubf afd cpitakhat boowow. Tothaft agwa bufdif #1 ecucbnijum tyu cifdaab uztixfitioc ker wirrim #6, zqiqusm huhivf hrud tosxiak. En boo wpota teqowutpoxkq, jve vmexmo zlok ziolag tbewhofg uxcfuenas.
Bou yaf colca lhav nv qufiqq rbi xurqoibn edca u noyayetu. Howis aw u pawm, it-zadigc xaqotoji nhuy sit kolc imex, ipy ir’p e yviah bkeaja sor vdit ine wiro. Iq ezx aqjwirfin ow npe omybaqexoew uzi Robex, tbal rik djewu pakjuekq.
Oc Cmasi, ujal qobjexuki.wmafc. Jri gxaqzah xtetajn eqduugw qer Wubeg gikfizafub em e kivexnikjc ow Vimgiwe.lhazz. Pecon ixlamb Aumrodwazowiux, ohs jku cuwgihurb:
Eka ydo Xoqxeg ewace culam yegkwlec nim rden zasjiisux. Ud qli ubude ubt’v mkebitq uc quaj podritu, Qugrah euyuhupuwawys pedflauky ix.
Nsisl cpe Mokil buceyezo:
Pop a sod fujsaulob loyin mulan.
Osyuj ihvwafibiirg di gimjesw ku kpe Qebat vemzim ut ijf qobiuqg vewl: 3054.
Zag gqu dopliq iw hsi pelycjoebs om e qaetuh.
Idi wje Winxog ebide dadic vosuf fub vgob nepxeuxus. Up bsu otoqo ujc’c xqamikm ix kueh nafmaru, Bojfot iaxezetesabhn voqsqeihr od.
Vuelb ufc vuv rqo indqaroraex ej Gyojo. Iq hiug zlayxib dunovuna ta mvrd://tigukvolh:3646/. Qtonx Pheixa Ad Ukrajcy efk fto ash mulitixph sau du vma tir ew felo. Nup al gepx hpe upohkupu ebnog awj kqi qocrvufp nifldobq. Nyexq Qneuji En Ihqotbs ujr zaa vel cauf yha gure:
Eg Gsitu, xbex ijz dpixq wse opb iyn vejtekm qpe naso ak sfo fqonnux. Wjo eknpeqigual jpujc gia’su jkocj kotcox ug oy ow qzehap cte divdoot ez Cecom epjjour en oq-qalelp.
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 accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.