UNPKG

19 kBMarkdownView Raw
1## Extended mupx
2This package is the https://github.com/arunoda/meteor-up-legacy#mupx package with some modifications for our own use. Use under your own risk.
3
4# Errores conocidos y posibles soluciones
5https://github.com/BinPar/bi-mupx/blob/master/docs/troubleshoot.md
6
7
8# Cómo hacer un deploy correctamente
9Como convenio en BinPar hemos adoptado que los archivos necesarios para realizar los deploys van en directorios nombrados ".deploy". En el caso de requerir varios deploys a instancias distintas los nombraremos ".deploy-<identificador>" (i.e.: ".deploy-beta", ".deploy-prod" ).
10
11Lo primero que debéis hacer es aseguraros de tener la última versión de @binpar/mupx
12```
13sudo npm install -g @binpar/mupx
14```
15
16## Antes de realizar ningún setup
17Asegurarse de que el dominio que vamos a usar está apuntando al servidor en el que vamos a hacer el deploy.
18
19## Deploy meteor
20Dentro de los directorios de deploy tendremos dos archivos el `mup.json` y el `settings.json`.
21
22El `mup.json` contiene la configuración necesaria para el deploy y el `settings.json` son las settings con las que se ejecutará meteor en producción y las que posiblemente varíen entre un directorio de deploy y otro.
23
24## mup.json configuración básica
25 - server: Array de objetos. Información sobre el servidor
26 - host: String. IP o nombre de dominio del servidor
27 - username: String. Usuario ssh para login
28 - password: String. Password para el usuario
29 - pem: String. Ruta a una key para login ssh (No están admitidas keys con contraseña)
30 - sshOptions: Objeto. Permite especificar opciones para la conexión ssh como el puerto
31 - port: Number. Especifica el puerto ssh por el que se conectará al servidor.
32 - env: Objeto. Recoge todas las variables de entorno que se aplicarán al server
33 - setupMongo: Boolean. Indica cuando tiene que crear o no el docker con mongodb. Si es true se ignora la MONGO_URL de env.
34 - nodeVersion: String. Indica la versión de node que se instalará en el servidor.
35 - useMeteor4: Boolean. Sólo se pone a false si la versión de Meteor es anterior a 1.4
36 - publishNetwork: String. IP local en la que se publica la app
37 - dockerimage: String. Permite especificar una imagen de docker personalizada
38 - appName: String. Nombre de la aplicación, también será el nombre del docker y el nombre de la base de datos de Mongo si hemos especificado "setupMongo" a true
39 - app: Path relativo o absoluto hacia el directorio root de la app
40 - env: Objeto. Variables de entorno aplicadas a la app
41 - PORT: puerto al que se debe enrutar
42 - ROOT_URL: URL en la que escuchará
43 - MONGO_URL: URL de mongodb (no es tenido en cuenta si setupMongo es true)
44 - deployCheckWaitTime: Tiempo máximo de espera para que la verificación falle
45
46### Deploy Meteor antiguos servidores (sin contenedores)
47Para máquinas antiguas que no usan contenedores (i.e: Ada) el `mup.json` será algo parecido a esto:
48```js
49{
50 "servers": [
51 {
52 "host": "",
53 "username": "root",
54 "pem": "~/.ssh/id_rsa",
55 "env":{
56 }
57 }
58 ],
59 "setupMongo": true,
60 "setupNode": true,
61 "nodeVersion": "4.8.3",
62 "useMeteor4": true,
63 "appName": "NombreApp",
64 "app": "..",
65 "env": {
66 "PORT": "3000",
67 "ROOT_URL": "https://example.binpar.com"
68 },
69 "deployCheckWaitTime": 120,
70 "enableUploadProgressBar": true
71}
72```
73
74### Deploy Meteor nuevos servidores (con contenedores)
75**¡ATENCIÓN! MUY IMPORTANTE:**
76Para el setup del primer docker de un contenedor que aún no existe debemos de tener en cuenta una cosa muy importante: no tenemos ni puerto ni password de ese contenedor porque no existe. Por lo que nuestro `mup.json`, en el caso de servidores con contenedores tendrá configuraciones adicionales. Las más importantes son estas:
77```js
78{
79 "servers": [
80 {
81 "host": "",
82 "username": "root",
83 //{{PASSWORD}}
84 //{{SSH_OPTIONS}}
85 "env":{
86 }
87 }
88 ],
89 ...
90 "containersConfig": true,
91 "containerName": "NombreContenedor",
92 ...
93}
94```
95Podemos observar algo extraño: `//{{PASSWORD}}` y `//{{SSH_OPTIONS}}`. Esto le permite a mupx sustituir esas líneas por la configuración del contenedor una vez creado después de ejecutar el `mupx setup`.
96
97Todas las configuraciones que estén destinadas a un servidor con contenedores deben tener `containersConfig` a true y un `containerName` que al hacer `mupx setup` se creará si no existe.
98
99## Deploy NextJS and new node APIs
100Por último, la configuración de servidores NextJS es exactamente igual a los dos casos anteriores solo que especificaremos una nodeVersion superior a 6.11.0 y añadiremos la configuración `nextjs: true` quedando de la siguiente forma:
101```js
102{
103 "servers": [
104 {
105 "host": "host",
106 "username": "root",
107 //{{PASSWORD}}
108 //{{SSH_OPTIONS}}
109 "env":{
110 }
111 }
112 ],
113 "setupMongo": true,
114 "setupNode": true,
115 "nodeVersion": "8.4.0",
116 "nextjs": true,
117 "appName": "NombreApp",
118 "publishNetwork":"0.0.0.0",
119 "containersConfig": true,
120 "containerName": "ContainerName",
121 "app": "..",
122 "dirExclusions": ["design"],
123 "env": {
124 "PORT": "3000",
125 "ROOT_URL": "https://example.binpar.com"
126 },
127 "deployCheckWaitTime": 120,
128 "enableUploadProgressBar": true
129}
130
131```
132Como podéis ver es parecido al deploy de Meteor en servidores con contenedores con la diferencia de que en vez de useMeteor4 tenemos nextjs: true.
133
134También tenemos una configuración adicional en deploys de NextJS y nuevos proyectos node que es `dirExclusions`. Es un array de Strings que nos permite especificar **directorios de primer nivel que serán excluidos**. Siempre estarán excluidos por defecto los siguientes directorios además de **todos** los que empiezan por . (es decir, ocultos):
135```
136['node_modules', '__test__', 'coverage']
137```
138**¡NOTA!**
139Para el correcto funcionamiento de este deploy hay unos pre-requisitos:
1401. Los babel runtimes, presets y plugins necesarios para la transpilación del proyecto deben estar en `dependencies` y NO en `devDependencies`.
1412. Es obligatorio que exista un npm script llamado `build` que realice la transpilación del proyecto.
1423. Es obligatorio que el npm script `start` inicie el proyecto con la variable de entorno NODE_ENV=production y desde la ruta a la versión transpilada.
143
144**¡Importante!** el parámetro `nextjs` prevalece sobre `useMeteor4`
145
146
147---
148
149
150
151
152# OLD README
153
154#### Production Quality Meteor Deployments
155
156Meteor Up is a command line tool that allows you to deploy any [Meteor](http://meteor.com) app to your own server. It currently supports Ubuntu. There are plans to support other linux distros soon.
157
158You can use install and use Meteor Up from Linux, Mac and **Windows**.
159
160This version of Meteor Up is powered by [Docker](http://www.docker.com/) and it makes Meteor Up easy to manage. It also reduce a lot of server specific errors.
161
162**Table of Contents**
163
164- [Features](#features)
165- [Server Configuration](#server-configuration)
166- [Installation](#installation)
167- [Creating a Meteor Up Project](#creating-a-meteor-up-project)
168- [Example File](#example-file)
169- [Setting Up a Server](#setting-up-a-server)
170- [Deploying an App](#deploying-an-app)
171- [Build Options](#build-options)
172- [Additional Setup/Deploy Information](#additional-setupdeploy-information)
173 - [Server Setup Details](#server-setup-details)
174 - [Deploy Wait Time](#deploy-wait-time)
175 - [Multiple Deployment Targets](#multiple-deployment-targets)
176- [Accessing the Database](#accessing-the-database)
177- [Multiple Deployments](#multiple-deployments)
178- [Server Specific Environment Variables](#server-specific-environment-variables)
179- [SSL Support](#ssl-support)
180- [Updating](#updating)
181- [Troubleshooting](#troubleshooting)
182- [Migrating from Meteor Up 0.x](#migrating-from-meteor-up-0x)
183
184### Features
185
186* Single command server setup
187* Single command deployment
188* Multi server deployment
189* Environmental Variables management
190* Support for [`settings.json`](http://docs.meteor.com/#meteor_settings)
191* Password or Private Key(pem) based server authentication
192* Access, logs from the terminal (supports log tailing)
193* Support for multiple meteor deployments (experimental)
194
195### Server Configuration
196
197* Auto-Restart if the app crashed
198* Auto-Start after the server reboot
199* Runs with docker so gives us better security and isolation.
200* Revert to the previous version, if the deployment failed
201* Secured MongoDB Installation (Optional)
202* Pre-Installed PhantomJS
203
204### Installation
205
206 npm install -g mupx
207
208### Creating a Meteor Up Project
209
210 mkdir ~/my-meteor-deployment
211 cd ~/my-meteor-deployment
212 mupx init
213
214This will create two files in your Meteor Up project directory:
215
216 * mup.json - Meteor Up configuration file
217 * settings.json - Settings for Meteor's [settings API](http://docs.meteor.com/#meteor_settings)
218
219`mup.json` is commented and easy to follow (it supports JavaScript comments).
220
221### Example File
222
223```js
224{
225 // Server authentication info
226 "servers": [
227 {
228 "host": "hostname",
229 "username": "root",
230 "password": "password",
231 // or pem file (ssh based authentication)
232 // WARNING: Keys protected by a passphrase are not supported
233 //"pem": "~/.ssh/id_rsa"
234 // Also, for non-standard ssh port use this
235 //"sshOptions": { "port" : 49154 },
236 // server specific environment variables
237 "env": {}
238 }
239 ],
240
241 // Install MongoDB on the server. Does not destroy the local MongoDB on future setups
242 "setupMongo": true,
243
244 // Application name (no spaces).
245 "appName": "meteor",
246
247 // Location of app (local directory). This can reference '~' as the users home directory.
248 // i.e., "app": "~/Meteor/my-app",
249 // This is the same as the line below.
250 "app": "/Users/arunoda/Meteor/my-app",
251
252 // Configure environment
253 // ROOT_URL must be set to your correct domain (https or http)
254 "env": {
255 "PORT": 80,
256 "ROOT_URL": "http://myapp.com"
257 },
258
259 // Meteor Up checks if the app comes online just after the deployment.
260 // Before mup checks that, it will wait for the number of seconds configured below.
261 "deployCheckWaitTime": 15,
262
263 // show a progress bar while uploading.
264 // Make it false when you deploy using a CI box.
265 "enableUploadProgressBar": true
266}
267```
268
269### Setting Up a Server
270
271 mupx setup
272
273This will setup the server for the `mupx` deployments. It will take around 2-5 minutes depending on the server's performance and network availability.
274
275### Deploying an App
276
277 mupx deploy
278
279This will bundle the Meteor project and deploy it to the server. Bundling process is very similar to how `meteor deploy` do it.
280
281### Other Utility Commands
282
283* `mupx reconfig` - reconfigure app with new environment variables and Meteor settings
284* `mupx stop` - stop the app
285* `mupx start` - start the app
286* `mupx restart` - restart the app
287* `mupx logs [-f --tail=50]` - get logs
288
289### Build Options
290
291When building the meteor app, we can invoke few options. So, you can mention them in `mup.json` like this:
292
293~~~js
294...
295"buildOptions": {
296 // build with the debug mode on
297 "debug": true,
298 // mobile setting for cordova apps
299 "mobileSettings": {
300 "public": {
301 "meteor-up": "rocks"
302 }
303 },
304 // executable used to build the meteor project
305 // you can set a local repo path if needed
306 "executable": "meteor"
307}
308...
309~~~
310
311### Additional Setup/Deploy Information
312
313#### Deploy Wait Time
314
315Meteor Up checks if the deployment is successful or not just after the deployment. By default, it will wait 15 seconds before the check. You can configure the wait time with the `deployCheckWaitTime` option in the `mup.json`
316
317#### SSH keys with paraphrase (or ssh-agent support)
318
319> This only tested with Mac/Linux
320
321It's common to use paraphrase enabled SSH keys to add an extra layer of protection to your SSH keys. You can use those keys with `mup` too. In order to do that, you need to use a `ssh-agent`.
322
323Here's the process:
324
325* First remove your `pem` field from the `mup.json`. So, your `mup.json` only has the username and host only.
326* Then start a ssh agent with `eval $(ssh-agent)`
327* Then add your ssh key with `ssh-add <path-to-key>`
328* Then you'll asked to enter the paraphrase to the key
329* After that simply invoke `mup` commands and they'll just work
330* Once you've deployed your app kill the ssh agent with `ssh-agent -k`
331
332#### Ssh based authentication with `sudo`
333
334**If your username is `root` or using AWS EC2, you don't need to follow these steps**
335
336Please ensure your key file (pem) is not protected by a passphrase. Also the setup process will require NOPASSWD access to sudo. (Since Meteor needs port 80, sudo access is required.)
337
338Make sure you also add your ssh key to the ```/YOUR_USERNAME/.ssh/authorized_keys``` list
339
340You can add your user to the sudo group:
341
342 sudo adduser *username* sudo
343
344And you also need to add NOPASSWD to the sudoers file:
345
346 sudo visudo
347
348 # replace this line
349 %sudo ALL=(ALL) ALL
350
351 # by this line
352 %sudo ALL=(ALL) NOPASSWD:ALL
353
354When this process is not working you might encounter the following error:
355
356 'sudo: no tty present and no askpass program specified'
357
358#### Server Setup Details
359
360Meteor Up uses Docker to run and manage your app. It uses [MeteorD](https://github.com/meteorhacks/meteord) behind the scenes. Here's how we manage and utilize the server.
361
362* your currently running meteor bundle lives at `/opt/<appName>/current`.
363* we've a demonized docker container running the above bundle.
364* docker container is started with `--restart=always` flag and it'll re-spawn the container if dies.
365* logs are maintained via Docker.
366* If you decided to use MongoDB, it'll be also running as a Docker conatiner. It's bound to the local interface and port 27017 (you cannot access from the outside)
367* the database is named `<appName>`
368
369For more information see [`lib/taskLists.js`](https://github.com/arunoda/meteor-up/blob/mupx/lib/taskLists/linux.js).
370
371#### Multiple Deployment Targets
372
373You can use an array to deploy to multiple servers at once.
374
375To deploy to *different* environments (e.g. staging, production, etc.), use separate Meteor Up configurations in separate directories, with each directory containing separate `mup.json` and `settings.json` files, and the `mup.json` files' `app` field pointing back to your app's local directory.
376
377### Accessing the Database
378
379You can't access the MongoDB from the outside the server. To access the MongoDB shell you need to log into your server via SSH first and then run the following command:
380
381 docker exec -it mongodb mongo <appName>
382
383> Later on we'll be using a separate MongoDB instance for every app.
384
385### Server Specific Environment Variables
386
387It is possible to provide server specific environment variables. Add the `env` object along with the server details in the `mup.json`. Here's an example:
388
389~~~js
390{
391 "servers": [
392 {
393 "host": "hostname",
394 "username": "root",
395 "password": "password"
396 "env": {
397 "SOME_ENV": "the-value"
398 }
399 }
400
401 ...
402}
403~~~
404
405By default, Meteor Up adds `CLUSTER_ENDPOINT_URL` to make [cluster](https://github.com/meteorhacks/cluster) deployment simple. But you can override it by defining it yourself.
406
407### Multiple Deployments
408
409Meteor Up supports multiple deployments to a single server. Meteor Up only does the deployment; if you need to configure subdomains, you need to manually setup a reverse proxy yourself.
410
411Let's assume, we need to deploy production and staging versions of the app to the same server. The production app runs on port 80 and the staging app runs on port 8000.
412
413We need to have two separate Meteor Up projects. For that, create two directories and initialize Meteor Up and add the necessary configurations.
414
415In the staging `mup.json`, add a field called `appName` with the value `staging`. You can add any name you prefer instead of `staging`. Since we are running our staging app on port 8000, add an environment variable called `PORT` with the value 8000.
416
417Now setup both projects and deploy as you need.
418
419### Changing `appName`
420
421It's pretty okay to change the `appName`. But before you do so, you need to stop the project with older `appName`
422
423### Custom configuration and settings files
424
425You can keep multiple configuration and settings files in the same directory and pass them to mup using the command parameters `--settings` and `--config`. For example, to use a file `mup-staging.json` and `staging-settings.json` add the parameters like this:
426
427 mup deploy --config=mup-staging.json --settings=staging-settings.json
428
429### SSL Support
430
431Meteor Up can enable SSL support for your app. It's uses the latest version of Nginx for that.
432
433To do that just add following configuration to your `mup.json` file.
434
435~~~js
436{
437 ...
438
439 "ssl": {
440 "certificate": "./bundle.crt", // this is a bundle of certificates
441 "key": "./private.key", // this is the private key of the certificate
442 "port": 443 // 443 is the default value and it's the standard HTTPS port
443 }
444
445 ...
446}
447~~~
448
449Now, simply do `mup setup` and then `mup deploy`. Now your app is running with a modern SSL setup.
450
451To learn more about the SSL setup refer to the [`mup-frontend-server`](https://github.com/meteorhacks/mup-frontend-server) project.
452
453### Updating Mup
454
455To update `mupx` to the latest version, just type:
456
457 npm update mupx -g
458
459You should try and keep `mupx` up to date in order to keep up with the latest Meteor changes.
460
461### Troubleshooting
462
463#### Check Logs
464If you suddenly can't deploy your app anymore, first use the `mupx logs -f` command to check the logs for error messages.
465
466One of the most common problems is your Node version getting out of date. In that case, see “Updating” section above.
467
468#### Verbose Output
469If you need to see the output of `mupx` (to see more precisely where it's failing or hanging, for example), run it like so:
470
471 DEBUG=* mupx <command>
472
473where `<command>` is one of the `mupx` commands such as `setup`, `deploy`, etc.
474
475### Migrating from Meteor Up 0.x
476
477`mupx` is not fully backward compatible with Meteor Up 0.x. But most of the `mup.json` remain the same. Here are some of the changes:
478
479* Docker is the now runtime for Meteor Up
480* We don't have use Upstart any more
481* You don't need to setup NodeJS version or PhantomJS manually (MeteorD will take care of it)
482* We use a mongodb docker container to run the local mongodb data (it uses the old mongodb location)
483* It uses a Nginx and a different SSL configurations
484* Now we don't re-build binaries. Instead we build for the `os.linux.x86_64` architecture. (This is the same thing what meteor-deploy does)
485
486#### Migration Guide
487
488> Use a new server if possible as you can. Then migrate DNS accordingly. That's the easiest and safest way.
489
490Let's assume our appName is `meteor`
491
492* stop the app with `stop meteor`
493* Then remove upstrat config file: `rm /etc/init/meteor.conf`
494* stop stud if you are using SSL: `stop stud`
495* Then remove upstrat config file: `rm /etc/init/stud.conf`
496* Stop mongodb if you are using: `stop mongod`
497* Remove MongoDB with: `apt-get remove mongodb`
498
499Then do `mupx setup` and then `mupx deploy`.
500
\No newline at end of file