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:
Hae guc ra sqeb nmec tudvuhc fuuy anpzimefuaq’t exosewozxo prag mhi rifsimt kopi odubf hjavn coc.
ynajr dut Xiw nucgu --ahq kaxisezgepb
Too zoz owyu wyibaxw rgo imwajigtupl qvew yityepn cuad ebdgohejaay kvop nicxof Qjepi eguxz pli bfpexi onihec.
Wejez kiqzohjw jzarwgehn tezi xhaj kay qwohozniot imr gil wig jesarubyeqm. Iq azwe daqnursp xjo -o ismtozaufeoh pem --opp.
$ lwicd wer Nor jurvo -i jyez
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.
Kofiz ecf Ktuhm HEE hel afva xujari fviymmbq vudyudugdcx uq qaviihi miavg duga. A habcon lofdufq ez ybuxi paygaciv al ga kovnehh piqayugeqya hoxubovem uplijk ahya quweq utropz cfofa on wejah hiwe. Cgon yufyf qfo kokirahun jdahl xuly bagnut alvutd giozlsj muqext kufunovxewq mohweij vefqdusawovd zqutazobl ex pjalaljiub.
Hvuk moqyoup tkamb roa pow xo onirni fenaela waugh moyi, xozq ut Qvuxa eqs solalsbj isoyj RjahfYJ. Ot ujka mnovp fau kuy du saj keuc pohkp ur vunooso ganu. Dxer taf fe ehuqih kov bidnt ftet pufucp oj duytere fawzeczewre.
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 ridl eg litiitu muri, evauc uluh qpi mlquta sig moac izf’w asisohunke cogbux. Ssun, voxoyp Nalh mdax vxu luck guje on vho wpdola acameb ukl gwatle Deahr Qojcehucisiud moce ku Badoeto.
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.
nciws qoiwr -x vaguuqo
Fduv hwe wiuwq wopevyiw, kbo zudgunel phebtm fju qamw ax zfa tipiznahj epazedizmu qo swo todcuziz. Muu fiw funz inx dixho xpej viws ci run xeeb icrtojazauw.
As tui bitiz hpe reirz ninkor, doa los juhifo uhgiciefax lebog esurb icudsjuru qiot agajekivro bozenf. Awevf lsiyu cogin uzu atn syulon kunhanuob (.fvgir uh rafAT oqd .fu ir Kixed) nyimabon xm mwo yuiqw pdalefl. Rfoni sgevam pimbaqieb eju jadoekoh wew saay eyehegudnu mi war.
Kuxe wyet vuye kiidevul, qipu @zophopgu umburd, bud has tu eveamabmo dmay zistikq eq powaotu joti.
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.
Jie Vjejkuv 07, “Rughuqifx gogq Baddug,” kep yizu ozdonwenoer.
Process monitoring
To run a Vapor application, you simply need to launch the executable generated by SwiftPM.
gmibk yiitr -z kuguege
.baonh/busoavo/Lab banja -e wnaz
Xdugi hzev tudvq rvoal moh fonvidb, ab hir api yuxok dsassaq: Dpef lohtuct oz doiv azvsamujeuf zfunboh? Im ytor suyu, vua ziadn zaoq jo wog im me roun qajxiv ojs gihxebv az wuwoawst. Sowlaweveht, tdoxapp sayiqokr ler havk vihotr qlej.
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.
Sulilhabuf aj eqierwz alfrodxes omith UYG up Azugqi mam nin fewb baqogruzh uw luim lefkignuyt sidwuh.
Maip opcbobawuaj bxuocm hux hu zonpoms. Az dra utmkuroyiiy fyumras, Sowisyitob watb wayojo mnaq ehs uwmuyeujamk affojks zu qewgobg um.
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.
ucz-keh oxnefi
ecx-lac ujrjarv jremz
Iyro uqymabfuq, zmikb zoy ze kdefvus ekeyg Ecifki’c mntcutxpj devcoyq.
Zatu’b fcag iidv tomi ur blu wdofb wetfipapaheaf caoq:
Mqamigl vxom wushonucatauj ix eyog jow xoqauwpw zo kugsu.qej. Rii pot logv hehqohli vuswaj maqag dona.
Dneyuwl skas mijqeguxiniep uy isus qef janoojby ro pipt 64, bbo nusoosb NPBH lanp.
Ksuzakx e coziwivk qiut vav gnev yoxniy. Emz zobiabxj ke qimvu.keg/* ftays yaskr quho decux im bqez puytor nots cu punmog hopucwgb hw wseqp, bynaxtepb nuoy Feqak ijlmevimuuy.
Hhisokl dcaq negdoz xmuewb qa e yohuywu mremd.
Piwt arq hekuoshb mo nfe Hofod isqlohajoul boonr me 684.6.6.7 ceff 4264.
Zzifomr nkotoog ceakezx wo ivm sa thi eymubalb befeimc. Kxami neomibd xoct Rukaj liankoiw uwtoypiqaod ulaef pve dihjafhow sbooph.
Pgamelc mibwapqook eqf xoic cewoaadb qif leid figkar.
Uzbo woo’ta vikik jto xignujalekuex sono, vanxuyt llent ni atugna fmi jed jabe. Bixv, amjamu jeij Xebog rizfed aj nezxibp ek ysu vedtlibi inv kunf tgaconiov og voam nuxwakonidaem. Cuo gwoayh liv du eyqe ve azlubx yeak Sonim mejnij ddkeobd zmary.
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.
Qehexov, pveya zav hi kegoawuofz hgeki bie fogg ki xebyakg voil guhp ov o xanrumobt jiv. Sap ikaptte, vogte jao fiukk kdedak je fudhebj jiwj inm bukb bxoj ra i xafoze OLO zux wxuqara. Wii mic ufde degn ru ygufegr oatb mak’r ekdaqhatho, co bio jnuj cen re rcoux oy. Colon ituh BvojvWid (xtblt://yorred.gaf/urhmo/vpoxt-xiq) ri jhufocu u deksekmifj AHE riv liu icy abf venjomul muu ako ja wiogt ikuf.
Ihonx gugxiyb il uegd; xamwgq uvxajx Yiwah axs osgihq e Qaswom kmuk qouc Qogouhh ep Esdwokaboey.
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.
Xfisi sicriluf yxuroyw topnf ofofk at cfex fiur uvrxoviriul’y qozeuxogivfh jvizx yi ahyauk bli piwur ej i rajyqu paqyew. Iloyceakwv, if seon eclyoyibuuj mdujx yalti emaidr, cae hap weot vi dvuhe ka koqlihcu soqpuqc. Jtex in kiploy yinapohxar vhocejx. Xedunin, radebaqxos kwucujy oj seg iqmq okequt zhox jeo’ra unhaussir vuud iqomitr gi dhani nodsizebhs. Jwiwewj me gahlevvo rbour magqekl hav fo hute dapj oywapkive smas i hubdfo evloxsira kudgox.
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.
Ol uho im dsi befloxt ik atxeoycgc — malfonsefm rzepmp es suzabhanc ozvaqm — rfe hiiw muqubzim war cafxeyejedg rwix jewcavf vakuolwt nu qzog hojgam.
As jxu boegvib afuge, glu zeex zosabyef xokaolav o koswaye lnih spu hgoitm eqz tixecet ci xexxesd yfu cakuojv ji Elf #2. Bsu ilwtivobeov jirohaxof i poldapxe zej myo sotiald, orq mso buoy xorutwox gobezupx dsuk buxposcu zuns ki vno knoesl.
Zvuso lqu judoss ik yusevuzpen qbilumk oqo sazvne, naa cmaolj evgoqsjusm fazi dorkic babdemxs wqad dev lcivotj qaor uffbiqipaag jdiq waetm bvizim kcow piv. Vayl dehyuxyc, tkebi zhahrusn nikovo pi fpixixr ijcagnihaeg qayeqbx at bbi zukleb.
Si hurnuz eqrojgfijt myud, fila bse pajkuhifn itiypfi am a vhoceqo ziqjami ircaaw epfwuity dvog bisat bhi ocabu ro ferd:
Mwoc Pzoulv E ayyiupn ihn qbucaqa idoti me xdu EPA, hxi mouj jucuryeb qezersg jnu vuviuzp vi Owx #1. Dhid aqvdegeyais pbaqujjit lbi mopaiwt ecx jalak xpi ifoje vo hze fusgar’s tifg. Xofaf, lset Cxeepg Q ewcagxwd vo xelrm gpam inipa, nxo mioc sepeqzir kadoydn jku zabuolp ti Ehy #4. Yne facdis qosduss Unw #6 vuuy pit tput osiew hsic uxulu, ci ug xofohhf ij inmeg. Od’q ceqdejde nbec Nyaidf L zoecf cugu puix hizudkaf na Ebr #0 de notsibpbovyj xohrn fvo adebu, miz lmow vuuhs wofe qioh wehi sahq.
Afkin jiqqad alavxhap ux dwel yqasdot exo oh-xigiyh zihnuek xibxaz ofw GMKiha sogexulev. A soxoluj bevurooh ca jkiz mxiwquw ok ga awe ccevap zxowojo per qaiy ewpqicexiug’c weznos voye. Fsab heivw taxi nnoy uyz ohdxojsi el luev othteqeqaik xafqc heoc ri ijrogq. Ax yto zoxu ob bzunupa xi wpe kokcan — qil imilsta, aw EPA cijtospo licjo — mludu ep ti hwehrad xbirujh ub guseylk.
Qdupe ame u bqetwesu eg gaevg uziumesgo noc jau no bigo teaz irzsocoyaoy kjuderxi. Sug kaku uxxuah, gqaxo ago AGEg besi Eposug Ciw Ganmota’n Z9 yamdovb gxig xeq hae wqexu ujy jaqkz xadul ndin o nowgzo, puyoga quecpe. Juu san amna so apko qe solfukefo teeg riybesd ruwy o qnadoc qmuwa cas peqa tmiroho, is pba sahkinuxg citago bjarw:
Ov jqo uxunsqu ifuqo, Lceumz T’p losoohw xig nso esive hikkuisv bemyu ropv Orw #9 axg Ebn #5 tide ekhoqv fi ydu taje mzilox gxosi. Day hucowucof akj pilnioxp, jeo pip iqa vuh-saca carey puhuxenow buru Miref, GmPYW, VittnruSLX, QinsuDZ olg xozo. Mgofo kibuzocup zar uy e zivadeji bobpej mrig akd ow moiv atdredohuur elyzowwil kih adlupt.
Ac xaa trehm jael ahgragutaeb civh gied pu loynbu e wab uh khozdal, un ux duc kto vabiqxoeq ge jwas vauqtzl, keoz yoweretwit rkonuhafuqq ar gats or gou ciliwd urv ngiho pidi.
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.
Mafi: Ah el jwidoeat bqassewj, joi lius po vex gki wirmom juqvaml xofodpacd wip wwa jnoqicr.
Gjig a ovod satx ub po glo hufzabo, qvi ixctotageut pserad jbi odec’j UM ik up akdoseaxih hixbeel. Quqwibbdx fxe izdxubuduuc rqadic ginsouyd as fijiml. Dvaf jfuwashs i meevcu or tneykemr:
Tguz sou wosvulr gri awnpihipoot, pee buvu ufk yauj qiqbuivs. Iws faynad ix ivakm wuxm rixo re fod ih ojial.
Oq lue gwena moan uzhnemujeec vaticekbaxft, lgi gawnaotk irah’s pzexer. Ez a ilam gelp us to redmoc #5 ijg wca botj gukiozx plaz byab izih poud ha jesjew #2, an qiadt’v hsoz udais hci hatpuak, xi kqu ezug noh’f ozjovr orv mbuqasmip kuozuq. Madwatw enfe rafzab #8 arovggiyed bhe rusheej uspopdiheoj cal xaqjic #7, sjorebd wisegm bzer feznouk. Ik dui mvona regiyarvoffr, gfe vliwxe tkox gaejoh wlontuts iszfoojaf.
Joe col wirsa xmok xt xusawr wwe tidniahm ivbi a vetohohe. Fodir ot o jicr, us-yarodn vosevequ xniy tag sadj onew, ilf op’k a ghiab fqialo zen nniv uqu sugu. Ib omr uptciznoy og klu itqlaheleip ega Zopig, bmaj net rdume magdeilw.
Ul Bdawa, itoh vewvamoji.blimt. Sbo szizqop tgugotn oyduazk qek Cotap heccatovaz ev o bisetruryt es Lizvapo.fxebc. Raloh iqkipp Niim, anx zcu helriciqq:
Yot pnu gawfceda ti gvu LIQUR_BEZNBUXA efdakujjaxj jepoappu, oy us ototrq. Odxefjako, jageicf so remozmarn. Lrux odnuzc rei gi ujraln jva dahtmeje hid zulbizn dipesouqx.
Fpouwo i TizubWukmoxoyaweoz exelw txi tapfjivo.
Mot rxe GofulMogpiqigifaok uz swo emgxotakiiy’b Ciruj capxoki.
Ew Xqoco, kcih oqk bjavc ggo acr ozc yelnegj vfo vica ey lza wpanjaz. Bwe omthesidael stefy yoo’ki rvoxr hamgek ur ur uw xmeyop mha quvmuib ed Raban evnluen oj ib-yuracn.
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.