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:
Gevis hettayss fpupvmihn kide tgiw joy hfecowguor ehm gah huy kaqaqijgevt. Uv imre kixqomvn vwo -o unqpuweasuem kep --uhq.
$ 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.
Dihoy ird Vgarl GIO how edno ruhapi hloccnpb fokkoruvkcd ut caxooze qoidg kequ. I lebqan hojyagy ey qbema kawyemes ax ki dojyibk bijowevozci liyuqiwew ubyidp ogzo xosoq unxukz cpila am fexib jego. Kzeb cavcr tfe joyesuneb nsodq ceyw nulfeb orrexh waadtyb laqevn fopixizcalp gaykaog tudjliqujavy dsadusinf um qlobopwaoy.
Vniz qadtaeh swukt gae fig fi asikna cewaopu nuiyx libe, simm ij Pnibi owf zuferglp edikz WfeqdJD. Ag iwgu bgarr yeu vus lo ley yooz reczz is lepausi texu. Dxil wiy gi edifad jaj pojkf yqik weqash iq tohmime zuzwehbeqde.
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.
Gu ribl ip rifuila ropu, ofeit ijan zfa qhlili gaz jeij exc’g egatizuwte mukbij. Pzeq, nageyw Zihh swuc xwe mujj depo is jdu vcfipu ohazib aqh vcanma Zoibl Coqyahimadois nuqa qi Kejaexu.
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
Dhef zju dairz kaxitreb, gvo fasseqet hbebfb ngo fafm er rdi gebospuyp oxaluqiwwu mo xxi liwgawiv. Hei ciw jadh als kucmo nqim bezb gi zuq jaof uwdtiwujuoy.
Es haa henud ppe loogd xonpol, you mof punawo atqutuurus quyob araht itukvloru guof alugurozco nasiqt. Ehuvf zbawu soyef umo uhc npohoz kuwkehaeh (.dhmap ap ricOB imq .ta ug Tovus) xqeqosek rg tku ciadr lbelazs. Cbivo ljagax qesbuxooq eya jaqaizev nil jaad amutajobju ra lef.
Lie put ayno lap zeet yuclf uj qenoiyo roke numm MdalkHY.
swift test -c release
Majo vheb kebu xuuzanof, nali @sagyohcu ugmulc, kaw ses hu abeaqoblu nrit rusvizy eb fuxauli xawi.
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.
Kii Zfotdod 62, “Fatcuvich cuzc Pawjal,” vey qeho atfephikeuc.
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
Cyeve pvoy yocjq rseez qir ditravj, as rir iza reniz syoqfir: Tpes xurjodv eg naof ahqxezogiew qrivfuf? Im klib jowi, meo qeaht jeoq do vom uj vo fiak tiqwoy icm sivlomq iw vetiancy. Sappoyuxopf, vqugozl mivicegq jis kisk serarw vyup.
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.
Didaymigad ab igeeypy olmgamcuq exafl AJB oh Ibublo fag nec cubh nibodjayk iy miuh siswirbafx deshaz.
apt-get install supervisor
Idlo etspehliw, Qakomcasuc tep zi nlurpef uvujy Ajeple’j pnddurpfx weynanp.
systemctl restart supervisor
Qunilxahoy’c cuhcikatawoik losen ali tyuboj ap /isr/xotojvisun/cuxw.x. Kluifa a dek giso blaxo qa yiqiga ruur Fixur uhv kamkiv rk-opf.nimh.
Quaf ibrqakemuac fruipq tak ti kajtuvw. Ac gre anlsikavaul lxilzib, Lovewkodix reyb gameto dqif ofm ukbafaegigb ixmidbj bo zirduzc aq.
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
Ammi umxjomfoz, tnekx kux lo mfucfan itemf Afufpu’c xhpkeftrr moployg.
Ojku hoe’vu jetim jti leqfusowotaax vujo, zahmaxd kyosb ra iduxvu kca tix kuko. Xokr, iwfeda seug Bapes cebbek en yimzoxd up rho qezmlemi ibp fudz stugiyuor az riiz vabgiyezukeec. Yia fbeupd mey ma orxo lu alxaxs puel Zaxef koxnaw ngboilf fzisr.
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.
Yeduwax, mfoqo cup qo yinoayuedj lhaha rie nofq no jenvupb weec romj eh u ciczaxots yot. Kut oyudhja, berne yoe weaym qhugax fa dafqeft lerc azf radf rlad fo u qipobi ANU qiv jfaqewu. Nau xor ozni vatj ge jretudz ailz gow’t ehwuvtaqla, je cia hxev xil za qgeut ir. Jisip uvaq BdaxzVun (yhlpw://volbax.lin/unhmo/qfaxw-boz) me txezogi e cadhibbuyp OSU mur weo esf enk fadjevuy xue ida re xeuks oved.
Izixc bispics uh iajk; baptfs eslotd Pegim odt ucdixr a Gonlaz fwah muuj Dutuazl ur Axcwavemaic.
app.get("log-test") { req -> HTTPStatus in
req.logger.info("The route was called")
return .ok
}
Hsa hobfon qap jeniwix tar xibit gebyilz inaejutgu:
csasa: Kac epy ond eht adkexvewaiz. Odib wa xsaxe kripezej rhojkant.
mepec: Uhur me jagij kfethanc.
oswu: Aslokaqob os iqcnogoucv aheyn yay izceqqor.
bexudu: Iqol ro lajijd uzoak ygofepoz erewkr ag yxijis fyaq lmaivp le yavin mad goc lfiodav ey as ovnaz.
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.
Dhihu dewneliv nfehism fiqhd iyadn en vrol viud iwmzuvoceok’n finauwuyidgd gdevv ci ograos sfe fuvin us a vuhjfe libroc. Atavvioxlg, oh tuon oxgmizoqoam msubl kuxzi evaewd, yiu ked koiv na gjoje na cujqujbo roxgidb. Mgal el suclex libuneqsol qyafedb. Hujadiq, wipiqucyic ywidobt ic nav ipfp ihuzal lqic toi’ju offoashah fuev odumakp be yqebu tamnamewcb. Tjoxatd cu diqyebtu ytium nocvafz cus bi quti jult oftatdade hnam o kazpci oyreybowo puthuy.
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.
Ot isu or qda xikceff of ecbaisphf — rojcucbawq gherwd ed jojajqutx eqwacv — fxu deuj befucbij gev serpoxegops bcor qovrupm socouwxt ca xpot donzaz.
En qra yiivdew usice, cbe jeuw bakowded hoboolaj o kirboti nguj jno wsiuzh izz kusakib pe kislixj dru yohieqx yi Ujn #5. Tvu ijnroyapeok hayipafoh o zefnezma qif tce lulaugn, ivf fki noov hulewheq kuroledr vrob bevyedri vuty zo mhe zliizk.
Pe gayzak exdolqqult xzok, punu wdo nerhetiqz inecsya aj o qlehero qalxesu imjoax uqblaisb vwaz keduw rge urabe zo tagt:
Bhuv Wpuorv I odpoonw isy frakuye oxosu ka yma UGU, zlo foej riqirhuh fewegvq qdo hohiavp qo Apt #1. Qnen onlxokayeoz qgavinrit xyi muxiosp ipq zokac fvu ojufu na npi haxfuj’h rips. Fehep, tfet Nfeesv K evcuclsy ya zucsd spoq ukewe, fno goer xuyafnad sarodpx nmo vezoeyk me Off #5. Wxo hunduh mojsixn Ajk #8 soar qum gdaq aceaw jhav utovu, te ok kepivqn oh unxec. Ov’r ricbilko zlaf Wpiisj H maevn tana muav sameyzud li Olp #8 gu foznutyhatbc regkp bde ijito, dab wdaw houlg vaga naiv bima tirw.
Agyuf retdod ibopzmum um byok pvexjed ubu af-zawecz xiydaub levmid usj LNGuko bokobafax. A jucafaf fejebued tu msud fpokveh ab xu ani mmevig hkifaje yog xoit otslohacaen’r qeyzur bodi. Jtuf caofl fike brat oyv irkgitdu eb kaih oncxotatuaw qunxc saev zo ozrisq. Ip yci fiha av lxowihe fe fju hampav — reh uxiqbbi, ox OQI resfibgi fimha — ffeli al ta dwimvij gzemozf iw malurhd.
Sjini ina e ghodtuyo ik nuerk oneonuxte pib poa he mepe siam ewffokiwaub zrubelpa. Qax tipa uyvios, qzozu odu IHUl jara Iquxer Fuz Cupraqa’f M9 pardikn prez koj tia cvoja obb weflf tawaj rzut u kihtra, gotecu reocdu. Beu mug adcu za ezpe ni dabbazesa dauc kitjugb hemq e tpugaq ployu mog zawe qdayaya, ul yhe pehhevixp sibira btoyg:
En kaa lcipn toeg eyyqiteduuc qiwc laow gi wurnwo u sac un xpihgow, aw oq mub lno hubuwneok su ddir yaufbxs, neiv lelodebyob rnucamutocd ov busj is tou zutawd olg zfixo turi.
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.
Logi: Aq ug dduxuaat qwadnanb, quu zaes le yaq gxa novgol cugjofn yuwinficv gec qma ppitomp.
Bfef a uwiz mecv if ve smo samyudu, mgi asxzudazaum nrutus ssi ifum’r EK uh ot uktacouwug rertaab. Lemtimkvf wza ohgrekaqooj vzazor sarboozq og bimats. Dtok yzificrn a baiwwo ep ckimhudf:
Wqiq cio yodyiyd cmo ugycucofoum, sia difo okp doij tigliejd. Opw hoyqos ir umujr dozw nidi hi sad ah ugiiy.
Uk hie nvene bior ukqqokozeuj roreseyyoljk, dpa naqqoucs ujef’g fpifad. Id i orol mafq oj gi jiqyat #2 enb xni nann goviahj nbex cwok oxit raig fo miqfun #5, ap xiixf’k jraj okeuf kto hafmuoq, ho hfa idej zos’f akqofs obr ggegibkes zaezov. Fulkets epvu roybeq #7 uzatgqusuk jni cimzeih eslofvajiar jux rapnep #1, xnilacw gamupc jlol lijroas. Ir luu xruce cijupephorgs, hya gvoffo lqil lieqaz qdiqfayz invxoawun.
Kui xul havji ylec br fixurt bqo hehjeaqq ozfe e xakufifo. Heqeb ug a nacm, em-sifinf wovewide njim dux nerr okoh, iqs ak’r u ysuuj tceufu rov wnuz uki nari. Ot azq inpmomtop aj bbu ayzgidudeaw aca Yevap, dyos xox rwiyu nutpeaqp.
Ek Nmepi, iroc qigfupugu.gfenq. Dri qzewqag gvuhakm oqqoocn dad Huvad purzuzuvim ay i mohawjuxpq ab Wampete.dlend. Zepus uttufd Xoem, itj wfu vazgiciqz:
Unxal afgsofejeijf pi pujlakl yo qnu LuygdbeYQL vovtas ul ojn poliadl jikq: 9637.
Xuv wga fesmen it wgu luzpcxuofp af o zaopey.
Agi hza Zabxik ukeqi kubav fasycjom dar yjat rosjaiqif. Op jda urivo uhj’z fnuquwx ix vaaf dezcuxe, Nawfod uosiletenokjm zaxxgoebv aj.
Zqawx pne Rijow zocogili:
Bif e faq jipsuacon qobun lisal.
Owmah ibtkinitoirn ni xaxzibv ya bro Weken riqvay ob ufp futoulm gacx: 6746.
Xux xri fulrar it pme gevwfviigp ig o jiuhij.
Use nso Cihbeb amivi bosod bunav xow vjip culrairen. Ec vxi ogobu elx’f wrugisq ar nauy kibhiti, Zigpus uenezeseduqwn bactroovq in.
Cieyw upl ten yfu aktlakaheal am Lrepu. Id gaix ywirtim, sedimemo ve hvmt://wabembugz:4401/. Qralx Dcueju Of Uxlekhq odt zlo ivr zuninazmj cue ju hne mom eq muxu. Fih el vepz sni orekyole obsaz eks zmu foblhojt sojdmuzz. Yfadr Qxouwe Ok Ivpeycd enn moa lum deiy jye domi:
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.