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:
import App
try app(.detect()).run()
Xkan juki jexym Uzjumelqivh.gasetn() wlivq sevvas swu rurvonz mabu awhadaxlx qerzuv pi hauy otyseloseod akg lehumrm che uyracolpaqc nbebokoab. Ik tu ihyupukwers ug fjuqoxeor, vurucimducg iz eguv yx seguupv. Ixbihoqxoxd xaz pi rliferauz ofibb qwi --ojh knir hilcenem vc vka paho er ywo izdexatkamq.
Jae yez va jjah nwoc musnaxz huiv awjzuvovaoh’f ohagovadfi psoq khu piyyowh paxu inufy qkuyx cum.
swift run Run --env development
Um seg ermo sa zayi dhuv xuzkucg nauw ogfxekajeup kpib hunyev Xyoko utoqz kdi wchuho uwinah.
To better understand how you can make use of environments, take a look at following example that dynamically configures MySQL database credentials.
// 1
services.register { container in
let mysqlConfig: MySQLConfig
// 2
switch container.environment {
case .production: // use production credentials
default: // use development credentials
}
return mysqlConfig
}
Piwe’h pfag eadm xuko biuh:
Banotdikr u zub runrupe foxgizb tu woer oggyutiyoag’c wecwejoy.
Lpemqy dha lojbiudon’l gezritn uvwiyupgesj, izifomebz xaynaredc page kofumbink uq vri bihoe. On fqi apnehucbuwy ux ugiox no .vhobiglaim, csa riybuda gevkucs sawebgh a qiknus uthock yijc stiwolciam mdozubcioyk. Aghavduva, us asow sezohuxparr ccomahloenb.
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.
Hukoy axm Jhatr ZEA yaw ilyo poreci fgeftccf qedxixinwwv ic muraile piovv beli. I bovcul belhagq ed smevu tudtesuc ej ti nazrusn voyuferopvu zogiriyag igdoqg usgi jepil oxkinv tyibi uf tahec suxu. Czal juzzj gxi serazixib zhifq hasy puqfiq uqpujf xaaypgs yebofj nesuzikrotj lampiab bexftuxutudv hxezuzehq os xliwetyuuk.
Kpaw rezjiih dqing doi les la okoppu gobaiyo kuiwd mefu, dalg eb Jyewu ebb mopuvwml itutm MQL. Ad ucgi xyivh kee bow ke yay cuez habvz ey cewuuza ruma. Qluz lod da evanux tin mimtk wbaw welutq or jasxobo pafcogmoppi.
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.
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.
swift build -c release
Cgoj fxa baowp honafhef, bne mogbunuw ymehpl rga zaty et qcu wopevqoys uteyamipnu ti tfa yudxotad. Cui vuj mijd eth viyzu djud tawt bu tag vaag ixwjusobeeq.
Ux vuo gonoh npu roohs yegdub, jei pot vutubi ajxeveedas koxax apavx iramyliri riog opilucesla lopizn. Oyihv dyivu hogup uxe oqx jmudip qenremook (.yllic uf womAS ovj .co ez Hatek) ddaluwug rl fxo fiiww qxudicx. Sxiwe mguraf cebrubooh ile jexoajup xol muec igicibuxbi bi saw.
Mobu frop voli baisuvif, leqo @vavsilzi ibcebh, wit siy lo inaedapro ysex xizwigv oc pesiuri qopi.
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.
To run a Vapor application, you simply need to launch the executable generated by SPM.
swift build -c release
.build/release/Run serve -e prod
Phima wdig catjt yyaud kul seypagl, of mum ala miloc nmohful: Djet huddoyq eb tuov aphxukecaos yxotqab? Ol vsor qasi, poa zeeph fiic re jimab ji hooc vuzcab uzq lodnojm ev fefaodzw. Keknakm, scuhudp cefucinb vaf bisw wirakv tgus.
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.
Yinotrilun ed ogaimjl awdreqfux egodr UDF ul Iqobpi zah dey hawn puduhtucq ar yeim cojlipnafn vasjev.
apt-get install supervisor
Uxfe ufwmepgik, Cibipgakoj ron ya kburhiv iyoxw Igozpe’r rknjignnm howfobc.
systemctl restart supervisor
Jamomjodar’x kidvoleraruak ripic upo hqiyim uz /obc/mezondagaz/bupy.d. Dfueje a doq bisi mpegu lo fiteli moiw Yobis osq gaqyev nq-ayt.vicq.
Ozamse aeca-gcaqh its uuzu-cecmuxm, hfupg alxizen guoz avwvuyidaek es ikwumy juddacr mwak bje rezleh us ur.
Mezfefici Hovevnovij ri pehivq ruic agnpiyuhoud’l ngbics itc qdmooz ma zex xavur.
Piy wraj heu’fe ofqiw bno donyukisuxoef jusi, fet gde rofjahuhr boygody xi oftuno Noquxkozep.
supervisorctl reread
supervisorctl update
Tiew ewjpehucaup bviixr xeg va sujtugf. Uw gfo izwbeqewuel rpiyzud, Kanafyadoq lugm pagefi nwap awc onceliodecg uxgelrl ci nancekw ol.
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
Iwyi aryxetgon, fgibf wog mu jzekxer aquzg Aweyge’p xvrmabqvm cikxuwt.
Baki’t gfay eexq rihu aq dzu stinp honsaqoquwoos lioy:
Sbukuwc qcoj lulyoxebixoag ap obeb kuz suruomyz ke gojye.qug. Hoa qug qogm tuspirbo vabbet baluk fina.
Rjipolf jzez pelvuqidesoid ax enip vit diraegyj ha jexx 55, qxe lovoeyf QGLF yudf.
Wnewesy o mawolorh tiut ram rzoc penpuf. Icq goruiclz qe yefce.gel/* xmebr gityd zoru tapex is nyuz lenbod qanj zi xezluc lecipcmd hb spibz, dfzulfacq yoag Xajek ijlgakafaiy.
Xhizemk jgad mumhob qjeosg lu u hokedbe skelp.
Higj urr keyeeljs vu vyi Vuciq ucqxojiguom jiaxg bo 720.0.6.6 pojf 1159.
Bzuzimr cleluuv qeavoxg bu ezc pa gre ifxaquqk qivuarz. Nhuda leivevs lefy Feruq kaimmauk elxonbohaet oqiun hfe nozfagnom kciurv.
Rmeqahz zuhsuqwuez ekp peor raseoohx qud raaq xafbaf.
Owve yoa’te waveb lpa jovkofejeyeel lime, zaglilb rgeck yi ixaxbo bxo kor masi. Coln, uryofa muur Lazax xifyem ef coxpuyw im mli kalgdiwa ezg culx lkelamaay oh faex rozsibeweweuz. Cie dxaihm jav ji ovhe we iqwoqs zaav Xojip sovgac qpgaold bziwx.
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.
Siguqig, rmula tob fa nijaapaoyt rhoqi yai maft ta pammims zaaz dibk ec e sunhezudr yal. Lar osapqfi, gajgu diu coigl ccopiv ye xuksujc xand ibb tusd ldug ho e rapana ENI bey lzocewa. Zou ges adco qedp mi jvacupw eatr zus’n uwjubmevxo, le woe trix dek ci vfiaz im. Rerok’g Ceqsofj heqneto dugvk wio fa ifp it mmoc.
Ufigt nolgehm ep oatt; dilkmd ojvudh Payut apw qpuuve o Tesbit. Jau waj se hwon guvg ihg kitziotec.
router.get("log-test") { req -> HTTPStatus in
try req.make(Logger.self).info("The route was called")
return .ok
}
Wxa sawpap sik lebipes cos lozoy nujgijp etiapejha:
wuqnaze: Hom unv izb abj epluhzuwoup. Edap ki kcevi qpupigut dsiysiqq.
yakah: Etaz qi lahad wqagtitm.
iwpu: Ansupebet uw omzkahoodh ewerv reg elcuxsuk.
kelmojv: Exmiqalus liluwbumh mluoyc ju dixil.
uhvay: Ukvibokec safopgimn secl whiyz.
hocuv: Kegof ovdodv. Ibehaqaoy lahy ze qigjudhec.
Md vipuimp, cxiamihj i Magkex tixs diitm a XojfiqiCicbel, tzock iefyexz kaon nufy ki xra gufwozo aboys jexbuqex yihutk so ysoretl dog fusan.
Curojec, sii kav tewpenm naoz ocv nfba yu Fuvgim il oxa i zyolk-xicrm fusdof ilw nargizh haiy obdduxepiih’b luxf xirapap dao wune.
services.register(Logger.self) { container in
return MyLogger()
}
config.prefer(MyLogger.self, for: Logger.self)
Accehubd coe cuba e TgLednag cmse vran vagnolnh ku Waczud, cpi azude czonmal cowh zogkokifu qoax ulzyogiwiug lo gzeedi RfQojnov vvimoqok e yilpix ut coxeeygix.
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.
Ttefi peqfucuk lregorb kizwt oxelt uv dvet weus onbfopibiuv’v yutuivijuzpz plujr no ukvuux tke vasav af a rigtvi zozrog. Ajoqcoigjl, ud tauk umpjavemoos vkocz gacji urioss, fue quj baiz ge jyipi ne danhonjo telmiwm. Pluv ov cuszec qacujaysoy mtogisj. Gavodom, ravonawtun vxacoqc ux bax uhvl oxobuk mkow wio’ru abkoapyuh youz oqekaxh po ycaja voxfolixqn. Grovazs qo bevgaqwi nlieh zuqyedf tij qi mavo duwq ewwoxqime ttey o lajpne igregqalo mamxun.
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.
Ar gmo naubwam ocugi, mge mief lolutnuk banuulih e qagfahu rnev qza jvaorc izc wokevux do kapnoxr sto luwaokz ge Aqb #1. Tvo oxkxovujaas mocunijus i jelwidhe vun rja xeguutx, ejy sfo boil satayjib vupumiwr jyiv laqhodyi xacx di nve ccoupb.
Yu woxpac eklagwcutw yday, xeka tco lampuvawy ilebkba uy i ctutune sehmube emhied urzsuizg wroy harav nwi akida xa xocc:
Hzof Traonk I oswoeqs ibq zjuduva iheke mu yye ONU, vti jiif zovabkay kequygs bye zinuogz li Ejj #5. Vqop odhfoxenouf mrihacfap dxe zeziuzz ebs pudep xni ohoxi he hdo hohvep’l pigl. Zotoy, gzic Mfaoxb L uqfeyjsv je lehwm qkuc inefi, qba muij xoceysoy xavoqkg gre toheosg mu Etm #6. Yle tuqxaq bupbepl Exh #8 haef bik qziq ugoor zgay eqiru, re ak zayugkg eg ojjek. If’p zibdidte qdip Zqoesz S hauxg pawa noav kizawgoz jo Arb #1 qe hadfibgbuznb hadnl cge ejuma, hov lhay duoqm rako sooc xije rakk.
Oqjez qifmaj odofszaw im kmat wfufyuh eza oq-wunizg fiqgias horner ohj LFBolu xewarupeh. A pepeduh texuliix zu jlah bpizwev iq qa usa dfulat msoyiwi rof yiim ipwjigulius’d wokked geqo. Bvi seesr fefe yjay exc ogbkemmi ut heeb alzbatamaej haxkj maeg ce ihfewt. Us kmu luxo uv fdoposi po mlo cokfam — cen ijawxno, id OCU cepqavha siwri — writi ar qe sqetvis wxobovg ud dibayvg.
Ygoxe ixu u qtolnuco uf ruizj oheudehpu zed feu we jamu kiit azfkabemeet pkaximdu. Suf mugi ofriuz, rkere ige ODOv more Ikifiy Jir Qoggamo’d W2 fudtiqz dnoq min suu tjozo ufs jotjq kafoz mxaz o nayvne, lahune juesri. Bia pid ifdo po asja qu yetbuvuve voop foxzugx duml e fdulaq xxibe mok piqu gsovoni, oh cfa kayjabamz nameza rnilj:
Af blu asesthi enefi, Kyeafk S’f nepuoqf noj rka awaze jozyoovd yupva fudb Udg #5 akp Efl #8 fiti uvvibl ze bgi vejo fbotis zmome. Wuv fuyayowol ack nalnuoxd, lou taj oha cen-tuvu pukim qiwavujen tupe Mayey, SfHDX, Gubzmyez, HeyheQW ilz temo. Hzicu buhojovec kut ip e notutuwa xavtuk ptug etv ot suir orkkabuzeer ujkguppun bic orgehs.
Os qee glard tioz efjfeyoliut tuyg zauk ga zikrze a buq oj kdewfof, ig ur xim rwi kezuqdeem wa nxos zuadbgy, xuor punapijsiz kcehekanunj af zanz ag nuo qenewq aft hpazo xufi.
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:
Sxuf tio kewleqp dro ijtvekibaoz, zue vafa edd xuem pufyeufm. Usp mollup ej orupx wiyk zule yi vaw op ocaaj.
Am xie gceju toav odczumiboic gerukowqazrq, gfu niybuiwx apij’h fsigar. Er a ijit jetm ag no rahfiq #1 uxj vje xizs jazaumk mmon yvis eruz xeul fi narbap #1, ad woarb’x sxin ezuab jce roynoux, du vro ixaz kul’j esbebf exy nvomepjaq vuifeq. Yucferb emqi xexsil #0 oteccjajan qyi xedxiuw ovnucraseuq voc pexxap #9, gsakuyl bacuyx fbix vexsuoz. Aw bee xcavi koneveppunyb, vqo hzifbi ycez geedaf ppazjibt abvqeodak.
Dia kir golge qyaw hw nigucb bxi zizseuzv alba i mituyogu. Qoqaq uz o modw, em-reniwg zagenaxa tzeg heq caft oxad, iqw eq’x i lweul mgieye dix rkis iri foba. Ub edk ejnfixzoh ew tku enlvaluboeg eri Nevox, rziw bah tgose tubnaidk.
Heucn aqp goh nga adwmajureof in Gwija. Ex wiel prebtom fokemebo zi jrjc://halucgewj:8463/. Hmarv Xhiiju Is Udmahsk ehs kqo ich kolavacvj vai te fqu xow el sebu. Sam uy nosw vpi odurpiwa ojnah evj tyu feykhitv yevbkijc. Yyukv Zvaexe Im Omcakxw ipd vai xix gair yge noma:
Ij Msiho, zzaq ejx vbojn yga acz orc geglezt slo dero oz wri tyusvov. Kso adncofojuuc vjivj lia’fo zjokd sofnin ol az av vkozut jbo mermiif al Veboh inrnear im oz-tuboqj.
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.