How To Deploy a Meteor.js Application on Ubuntu 14.04 with Nginx

-출처: https://www.digitalocean.com/community/tutorials/how-to-deploy-a-meteor-js-application-on-ubuntu-14-04-with-nginx

About Meteor.js

Meteor.js is a framework for JavaScript that allows web developers to write JavaScript code once and reuse it both client and server-side. This is possible thanks to Meteor’s unique build process (read more about structuring your application code and code sharing). This also solves the problem of needing a complicated deployment process between development mode, where developers code and debug, andproduction mode, that is secure enough for the public-facing version of the app. The Meteor framework provides a way for client-code and server-code as well as development and production to be closely related. It’s probably the easiest way for client-side developers to start working on server-side code!

To see this in action, you may want to view the introductory video on Meteor’s website.

Meteor.js allows you to develop projects like a website (web application), HTML5-based web-browser application (using AppCache), or mobile application (through integration with PhoneGap). All you need is knowledge of Javascript and HTML. Meteor includes support for MongoDB (a NoSQL database).Atmosphere hosts packages that can provide complete building blocks for your application to speed up the development even more.

At the end of this tutorial, we will have:

  • Installed Meteor.js
  • Created a deployment package that contains an entire Meteor application in a production-ready format (minus a web server and database backend)
  • Installed Nginx as our web server to pass HTTP requests to Meteor
  • Installed MongoDB as our database engine
  • Managed our application with Upstart
  • Configured daily database backups for the Meteor database

Throughout this tutorial, if you don’t have your own Meteor application yet, you can use the “Todo List” example application from the Meteor website.

Before You Begin

You should have:

  • An existing Meteor app on a separate development computer (you can view the example “Todo List” app here; instructions are provided later in the tutorial)
  • A fresh Ubuntu 14.04 server; existing Meteor installations should work in most cases
  • root access to the server to execute commands
  • Updated package lists. Execute:apt-get update
  • Replace todos.net with the domain name you are actually using (or leave it if you don’t have a domain and will be using an IP address instead)
  • Replace todos (without .net) with the name of your application

Step 1 — Setting Up an Nginx Web Server

We will install and set up Nginx because it allows us to encrypt web traffic with SSL, a feature that Meteor’s built-in web server does not provide. Nginx will also let us serve other websites on the same server, and filter and log traffic.

In our configuration, we will secure our site with an SSL certificate and redirect all traffic from HTTP to HTTPS. We will also utilize a few new security practices to enhance the security of the SSL connection.

In order to install Nginx we execute:

apt-get install nginx

Create a virtual host configuration file in /etc/nginx/sites-available.

Below is an annotated config file which we can create as /etc/nginx/sites-available/todos with the following contents. Explanations for all of the configuration settings are included in the comments in the file:

server_tokens off; # for security-by-obscurity: stop displaying nginx version

# this section is needed to proxy web-socket connections
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

# HTTP
server {
    listen 80 default_server; # if this is not a default server, remove "default_server"
    listen [::]:80 default_server ipv6only=on;

    root /usr/share/nginx/html; # root is irrelevant
    index index.html index.htm; # this is also irrelevant

    server_name todos.net; # the domain on which we want to host the application. Since we set "default_server" previously, nginx will answer all hosts anyway.

    # redirect non-SSL to SSL
    location / {
        rewrite     ^ https://$server_name$request_uri? permanent;
    }
}

# HTTPS server
server {
    listen 443 ssl spdy; # we enable SPDY here
    server_name todos.net; # this domain must match Common Name (CN) in the SSL certificate

    root html; # irrelevant
    index index.html; # irrelevant

    ssl_certificate /etc/nginx/ssl/todos.pem; # full path to SSL certificate and CA certificate concatenated together
    ssl_certificate_key /etc/nginx/ssl/todos.key; # full path to SSL key

    # performance enhancement for SSL
    ssl_stapling on;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 5m;

    # safety enhancement to SSL: make sure we actually use a safe cipher
    ssl_prefer_server_ciphers on;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:ECDHE-RSA-RC4-SHA:ECDHE-ECDSA-RC4-SHA:RC4-SHA:HIGH:!aNULL:!eNULL:!EXPORT:!DES:!3DES:!MD5:!PSK';

    # config to enable HSTS(HTTP Strict Transport Security) https://developer.mozilla.org/en-US/docs/Security/HTTP_Strict_Transport_Security
    # to avoid ssl stripping https://en.wikipedia.org/wiki/SSL_stripping#SSL_stripping
    add_header Strict-Transport-Security "max-age=31536000;";

    # If your application is not compatible with IE <= 10, this will redirect visitors to a page advising a browser update
    # This works because IE 11 does not present itself as MSIE anymore
    if ($http_user_agent ~ "MSIE" ) {
        return 303 https://browser-update.org/update.html;
    }

    # pass all requests to Meteor
    location / {
        proxy_pass http://127.0.0.1:8080;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade; # allow websockets
        proxy_set_header Connection $connection_upgrade;
        proxy_set_header X-Forwarded-For $remote_addr; # preserve client IP

        # this setting allows the browser to cache the application in a way compatible with Meteor
        # on every applicaiton update the name of CSS and JS file is different, so they can be cache infinitely (here: 30 days)
        # the root path (/) MUST NOT be cached
        if ($uri != '/') {
            expires 30d;
        }
    }
}

If you’d like to adapt the configuration file to your needs, and for more explanation, have a look at this tutorial on Nginx virtual hosts.

As seen in the virtual host config file, Nginx will expect a valid SSL certificate and key in/etc/nginx/ssl. We need to create this directory and secure it:

mkdir /etc/nginx/ssl
chmod 0700 /etc/nginx/ssl

Then we can create the files containing the certificate (and chain certificate if required) and the key in the locations we defined in the configuration above:

  • certificate: /etc/nginx/ssl/todos.pem
  • key: /etc/nginx/ssl/todos.key

If you do not have an SSL certificate and key already, you should now create a self-signed certificate using this tutorial on creating self-signed SSL certificates for Nginx. Remember that you’ll want to use the same names from the configuration file, like todos.key as the key name, and todos.pem as the certificate name. While a self-signed certificate is fine for testing, it is recommended to use a commercial, signed certificate for production use. A self-signed certificate will provoke Nginx warnings connected to ssl_stapling, and a security warning in the web browser.

When you’re done creating or obtaining your certificate, make sure you have the todos.pem andtodos.key files mentioned above.

Next, we should disable the default vhost:

rm /etc/nginx/sites-enabled/default

And enable our Meteor vhost:

ln -s /etc/nginx/sites-available/todos /etc/nginx/sites-enabled/todos

Test that the vhost configuration is error free (you will see an error related to ssl_stapling if you have a self-signed certificate; this is okay):

nginx -t

If everything is looking good we can apply the changes to Nginx:

nginx -s reload

At this point, you can use your web browser to visit https://todos.net (or your IP address). It will show us502 Bad Gateway. That is OK, because we don’t have Meteor running yet!

Step Two — Setting Up a MongoDB Database

We will install MongoDB from the regular Ubuntu repository. The standard configuration should be fine. There is no authentication required to connect to the database, but connections are only possible from localhost. This means that no external connections are possible, and thus the database is safe, as long as we don’t have untrusted users with SSH access to the system.

Install the MongoDB server package:

apt-get install mongodb-server

This is everything we need to do to get MongoDB running. To be sure that access from external hosts is not possible, we execute the following to be sure that MongoDB is bound to 127.0.0.1. Check with this command:

netstat -ln | grep -E '27017|28017'

Expected output:

tcp        0      0 127.0.0.1:27017         0.0.0.0:*               LISTEN
tcp        0      0 127.0.0.1:28017         0.0.0.0:*               LISTEN
unix  2      [ ACC ]     STREAM     LISTENING     6091441  /tmp/mongodb-27017.sock

In order to have daily backups available in case something goes wrong, we can optionally install a simple command as a daily cron job. Create a file /etc/cron.d/mongodb-backup:

@daily root mkdir -p /var/backups/mongodb; mongodump --db todos --out /var/backups/mongodb/$(date +'\%Y-\%m-\%d')

Step 3 — Installing the Meteor Application

First, we need to install Node.js. Since Meteor typically requires a version of Node.js newer than what’s available in the standard repository, we will use a custom PPA (at the time of writing, Ubuntu 14.04 provides nodejs=0.10.25~dfsg2-2ubuntu1 while Meteor 0.8.3 requires Node.js 0.10.29 or newer).

Execute the following to add a PPA with Node.js, and confirm by pressing Enter:

add-apt-repository ppa:chris-lea/node.js

Output:

 Evented I/O for V8 javascript. Node's goal is to provide an easy way to build scalable network programs
 More info: https://launchpad.net/~chris-lea/+archive/ubuntu/node.js
Press [ENTER] to continue or ctrl-c to cancel adding it

gpg: keyring `/tmp/tmphsbizg3u/secring.gpg' created
gpg: keyring `/tmp/tmphsbizg3u/pubring.gpg' created
gpg: requesting key C7917B12 from hkp server keyserver.ubuntu.com
gpg: /tmp/tmphsbizg3u/trustdb.gpg: trustdb created
gpg: key C7917B12: public key "Launchpad chrislea" imported
gpg: Total number processed: 1
gpg:               imported: 1  (RSA: 1)
OK

Now we must refresh the repository cache, and then we can install Node.js and npm (Node.js package manager):

apt-get update
apt-get install nodejs

It’s a good practice to run our Meteor application as a regular user. Therefore, we will create a new system user specifically for that purpose:

adduser --disabled-login todos

Output:

Adding user `todos' ...
Adding new group `todos' (1001) ...
Adding new user `todos' (1001) with group `todos' ...
Creating home directory `/home/todos' ...
Copying files from `/etc/skel' ...
Changing the user information for todos
Enter the new value, or press ENTER for the default
        Full Name []: 
        Room Number []: 
        Work Phone []: 
        Home Phone []: 
        Other []: 
Is the information correct? [Y/n]

Step Four — Configuring Upstart

Now we are ready to create the Upstart service to manage our Meteor app. Upstart will automatically start the app on boot and restart Meteor in case it dies. You can read more about creating Upstart service files in this tutorial.

Create the file /etc/init/todos.conf. Once again, it is annotated in-line:

# upstart service file at /etc/init/todos.conf
description "Meteor.js (NodeJS) application"
author "Daniel Speichert <daniel@speichert.pro>"

# When to start the service
start on started mongodb and runlevel [2345]

# When to stop the service
stop on shutdown

# Automatically restart process if crashed
respawn
respawn limit 10 5

# we don't use buil-in log because we use a script below
# console log

# drop root proviliges and switch to mymetorapp user
setuid todos
setgid todos

script
    export PATH=/opt/local/bin:/opt/local/sbin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
    export NODE_PATH=/usr/lib/nodejs:/usr/lib/node_modules:/usr/share/javascript
    # set to home directory of the user Meteor will be running as
    export PWD=/home/todos
    export HOME=/home/todos
    # leave as 127.0.0.1 for security
    export BIND_IP=127.0.0.1
    # the port nginx is proxying requests to
    export PORT=8080
    # this allows Meteor to figure out correct IP address of visitors
    export HTTP_FORWARDED_COUNT=1
    # MongoDB connection string using todos as database name
    export MONGO_URL=mongodb://localhost:27017/todos
    # The domain name as configured previously as server_name in nginx
    export ROOT_URL=https://todos.net
    # optional JSON config - the contents of file specified by passing "--settings" parameter to meteor command in development mode
    export METEOR_SETTINGS='{ "somesetting": "someval", "public": { "othersetting": "anothervalue" } }'
    # this is optional: http://docs.meteor.com/#email
    # commented out will default to no email being sent
    # you must register with MailGun to have a username and password there
    # export MAIL_URL=smtp://postmaster@mymetorapp.net:password123@smtp.mailgun.org
    # alternatively install "apt-get install default-mta" and uncomment:
    # export MAIL_URL=smtp://localhost
    exec node /home/todos/bundle/main.js >> /home/todos/todos.log
end script

One thing to notice in this configuration file is the METEOR_SETTINGS parameter. If you use meteor --settings config.json when launching Meteor’s development mode, then you should paste the contents of config.json as a variable in METEOR_SETTINGS.

The MAIL_URL must be a valid SMTP URL only if you plan to use Meteor’s Email package. You can use MailGun (as recommended by Meteor), a local mail server, etc.

As we can see in the file, the log will be saved to /home/todos/todos.log. This file will not rotate andWILL GROW over time. It’s a good idea to keep an eye on it. Ideally, there should not be a lot of content (errors) in it. Optionally, you can set up log rotation or replace >> with > at the end of Upstart scripts in order to overwrite the whole file instead of appending to the end of it.

Don’t start this service yet as we don’t have the actual Meteor application files in place yet!

Step Five — Deploying the Meteor Application

Optional: If you do not have a Meteor project yet

If you don’t have a Meteor project yet and would like to use a demo app, that’s not a problem!

Do this next step on your home computer or a development Linux server. Commands may vary based on your OS. Move to your home folder:

cd ~

First, install Meteor’s development version:

curl https://install.meteor.com | /bin/sh

Then create an application from an example, called Todo List:

meteor create --example todos

Now enter the directory of your application and you are ready to continue:

cd todos

All Meteor projects

It’s time to create a production-version bundle from our Meteor app. The following commands should be executed on your home computer or development Linux server, wherever your Meteor application lives. Go to your project directory:

cd /app/dir

And execute:

meteor build .

This will create an archive file like todos.tar.gz in the directory /app/dir. Copy this file to your ~directory on your Droplet.

scp todos.tar.gz root@todos.net:~

Now go back to your Droplet. Create a project directory and move the archive project file into it. Note that this is the home folder for the project user that we created previously, not your root home folder:

mkdir /home/todos
mv todos.tar.gz /home/todos

Move into the project directory and unpack it:

cd /home/todos
tar -zxf todos.tar.gz

Take a look at the project README:

cat /home/todos/bundle/README

The bundle includes a README file with contents:

This is a Meteor application bundle. It has only one external dependency:
Node.js 0.10.29 or newer. To run the application:

  $ (cd programs/server && npm install)
  $ export MONGO_URL='mongodb://user:password@host:port/databasename'
  $ export ROOT_URL='http://example.com'
  $ export MAIL_URL='smtp://user:password@mailhost:port/'
  $ node main.js

Use the PORT environment variable to set the port where the
application will listen. The default is 80, but that will require
root on most systems.

Find out more about Meteor at meteor.com.

This recipe is reflected in our /etc/init/todos.conf file. There is still one more thing mentioned in the README that we need to do.

Now we need to install some required npm modules. To be able to build some of them, we also need to install g++ and make:

apt-get install g++ make
cd /home/todos/bundle/programs/server
npm install

You should see output like this:

npm WARN package.json meteor-dev-bundle@0.0.0 No description
npm WARN package.json meteor-dev-bundle@0.0.0 No repository field.
npm WARN package.json meteor-dev-bundle@0.0.0 No README data

> fibers@1.0.1 install /home/todos/bundle/programs/server/node_modules/fibers
> node ./build.js

`linux-x64-v8-3.14` exists; testing
Binary is fine; exiting
underscore@1.5.2 node_modules/underscore

semver@2.2.1 node_modules/semver

source-map-support@0.2.5 node_modules/source-map-support
└── source-map@0.1.29 (amdefine@0.1.0)

fibers@1.0.1 node_modules/fibers

The reason we need to do this is because our application bundle does not contain modules and libraries that are platform-dependent.

We are almost ready to run the application, but since we operated on files as root, and they should be owned by the todos user, we need to update the ownership of the project directory:

chown todos:todos /home/todos -R

Step Six — Showtime

At this point we have everything we need to run our Meteor application:

  • Node.js environment installed
  • Application installed in its project directory
  • Upstart service configured to run the application
  • MongoDB database
  • Nginx proxy server in front of our Meteor application to provide SSL encryption

To start our application, let’s execute this command from the project directory:

start todos

Now you should be able to view your application in the browser at https://todos.net.

Re-deploying the Application

When you make changes in the development mode (and you will; we are developers after all!), you can simply repeat Step Five (starting from meteor build) and go through most of the steps until therestart todos command, which will reload your application via Upstart.

This way you can push a new version with no downtime. Clients (visitors to your website) will automatically pull the new version of code and refresh their page – that is Meteor’s magic!

If you want to test this, you can make a simple change to the text in the todos/client/todos.htmlpage in your development copy of the app on your home computer or development server.

Development server:

Build:

meteor build /app/dir

Upload:

scp todos.tar.gz root@todos.net:/home/todos

Production server:

Expand:

tar -zxf /home/todos/todos.tar.gz

Move into the project folder:

cd /home/todos/bundle/programs/server

Update the npm modules (you may see a few warnings):

npm install

Restart the app:

restart todos

Troubleshooting

If something goes wrong, here are a few hints on where to look for problems:

  • Check /home/todos/todos.log if your application starts and dies; it should throw an appropriate error message (e.g. in case of a programming error).
  • Check /var/log/nginx/error.log if you see an HTTP error in stead of your application.
  • Check /var/log/mongodb/mongodb.log if you think there might a problem with the database.

Finally, check if all services are running:

status todos
service nginx status
status mongodb

Run multiple apps in one server

-출처: https://sungwoncho.io/run-multiple-apps-in-one-droplet/

It is possible to run more than one apps in a single virtual private server.

Having used Platform-as-a-Service products like Heroku most of the time, this basic idea was so foreign to me. Now that I am running several apps in my server, I would like to share how I am doing so.

I am using Nginx as a HTTP server. I am also using Digital Ocean, but this post can be generalized to any infrastructure providers.

Our goal

We want to run two apps in our server: a NodeJS and a Meteor app. We want to make it so that users can go to node_app.com to use NodeJS app, and meteor_app.com to use Meteor app.

Reverse proxy

What we want to do in this situation is to set up a reverse proxy using Nginx. A reverse proxy is like a traffic light that lets users connect to multiple applications or servers.

In our case, we can have Nginx listen on port 80 using node_app.com and meteor_app.com as server_name.

This way, when a request comes in for node_app.com, Nginx routes it to the NodeJS app. A request for meteor_app.com will be routed to Meteor app.

Here are the steps to set it up:

1. Run apps on different ports

Using forever, we run the NodeJS app by executing the following in the app root directory.

NODE_ENV=production forever start [app_file_name]

We could do the same with the Meteor app.

forever start [app_file_name]

Let us say that the node app was running on the port 2368, and Meteor app on the port 3000.

By the way, forever is a handy tool to keep the script running, well… forever.

2. Make Nginx configuration files

In /etc/nginx/sites-available, we make two configuration files.

node_app.conf

server {  
  listen 80;
  server_name node_app.com

  location / {
    proxy_pass         http://127.0.0.1:2368;
    proxy_http_version 1.1;
    proxy_set_header   Upgrade $http_upgrade;
    proxy_set_header   Connection "upgrade";
    proxy_set_header   X-Real-IP $remote_addr;
    proxy_set_header   Host      $http_host;
  }
}

meteor_app.conf

server {  
  listen 80;
  server_name meteor_app.com

  location / {
    proxy_pass         http://127.0.0.1:3000;
    proxy_http_version 1.1;
    proxy_set_header   Upgrade $http_upgrade;
    proxy_set_header   Connection "upgrade";
    proxy_set_header   X-Real-IP $remote_addr;
    proxy_set_header   Host      $http_host;
  }
}

All we are doing is making Nginx listen on the port 80 using different server_name, and routing the requests to either port 2368 or 3000 depending on the server_namethat request is hitting.

server_name is an Nginx directive. The official doc says:

Server names are defined using the server_name directive and determine which server block is used for a given request.

3. Restart Nginx

To apply the changes, you need to restart Nginx by running:

sudo service nginx restart

Before you do that, you can test if all the configurations are valid by running:

nginx -t

If Nginx fails to restart for some reason, you can always check the log at /var/log/nginx/error.log. It is the default path for error logs unless you specify one in the config.

Conclusion

You can set up a reverse proxy using Nginx to listen on port 80 and route requests to other ports on which different apps are running. All this can be done in one server.

Host Multiple Meteor, and Ghost Instances on DigitalOcean

-출처: http://odlaner.com/host-multiple-meteor-and-ghost-instances-on-digitalocean/

I currently have a couple of Ghost Blogs and Meteor instances running all on the same ($5) droplet on DigitalOcean. Yes I can be cheap, and since I know I’m not the only one, I thought I would share the knowledge.

I was able to accomplish this using Meteor Up for easy configuration and deploy, Nginx for reverse proxy, and Forever to start/stop Ghost.

Let’s get started.

DigitalOcean Droplets

Head over to DigitalOcean and create a droplet with the Ubuntu 12 image. Create > Select Image > Linux Distribution > Ubuntu 12.04. The size of the Droplet is up to you, but I have found that even the $5 droplet goes a long way.

Meteor Up (MUP)

To install Meteor Up, simply do the following command in your terminal:

$ npm install mup -g

Once the installation is over, cd into your meteor application directory, and create a new director where we will create a MUP project.

$ mkdir .deploy/
$ cd .deploy
$ mup init

This will create 2 files, settings.json and mup.json, inside the .deploy/directory.

If you are using version control, you may not want to check in .deploy/. If this is the case, simply add it to your .gitignore.

$ echo '.deploy/*' >> .gitignore

settings.json is where you put your meteor settings. if you don’t have any, leave it empty:

{
 "public": {}
}

mup.json is where the configuration settings for our droplet goes. It should look a bit like this:

{
  // Server authentication info
  "servers": [
    {
      "host": "DROPLET_IP_ADDRESS",
      "username": "root",
      "password": "YOUR_PASSWORD_WAS_EMAILED_TO_YOU"
      // or pem file (ssh based authentication)
      "pem": "~/.ssh/id_rsa"
    }
  ],

  // Install MongoDB in the server, does not destroy local MongoDB on future setup
  "setupMongo": true,

  // WARNING: Node.js is required! Only skip if you already have Node.js installed on server.
  "setupNode": true,

  // WARNING: If nodeVersion omitted will setup 0.10.28 by default. Do not use v, only version number.
  "nodeVersion": "0.10.31",

  // Install PhantomJS in the server
  "setupPhantom": true,

  // Application name (No spaces)
  "appName": "YOUR_APP_NAME",

  // Location of app (local directory)
  "app": "../",

  // Configure environment
  "env": {
    "ROOT_URL": "http://YOUR_DOMAIN_NAME.com",
    "PORT": 3000
  },

  // Meteor Up checks if the app comes online just after the deployment
  // before mup checks that, it will wait for no. of seconds configured below
  "deployCheckWaitTime": 15
}

If you are using password-based authentication, you will need to installsshpass.

Once you have filled mup.json according to your droplet settings, and installedsshpass, we can start deployment.

You will need two commands for the first time deploy. Run these commands inside your .deploy/ directory, and that is it.

$ mup setup

and

$ mup deploy

If you have to deploy a second meteor app, repeat the process above (you don’t have to re-run mup setup) but make sure to use a different port (i.e 3001).

At this point, you should be able to see your app running under http://YOUR_DOMAIN.com:3000. But I doubt any of you want to refer to your app that way “awesome app dot com colon 3000”. So we are going to use Nginx to reverse proxy.

Nginx Reverse Proxy (meteor)

If you don’t already have Nginx installed on your droplet, check out this great tutorial from DigitalOcean on how to install it.

If you do already have Nginx installed, ssh into your droplet and make sure it’s at least version 1.3. Earlier version do not support websockets, and they are critical for your meteor app to run correctly.

$ nginx -v

Proceed once you have the correct version of Nginx.

Create a configuration file for each meteor application. I recommend you name them something meaningful, like your domain name.

$ cd /etc/nginx/conf.d/
$ vi your-domain-name.conf

Inside the configuration file, add the following:

server {  
 listen 80;
 server_name your-domain-name.com;

 location / {
    proxy_pass http://localhost:3000;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
 }
}

Update the port accordingly.

Ghost

If you’d also like to host your ghost blog on the same droplet, you simply need to download and install ghost, and set up another nginx configuration file for the reverse proxying.

$ mkdir /var/www/
$ cd /var/www/
$ sudo wget https://ghost.org/zip/ghost-latest.zip  
$ unzip -d ghost ghost-latest.zip    
$ cd ghost/
$ sudo npm install --production

Once it is done installing, you need to setup ghost. Copy the config.example.jsfile as config.js and change the host to your droplet’s IP.

$ cp config.example.js config.js  
$ sudo vi config.js

On your new Nginx configuration file, add this:

server {  
    listen 80;
    server_name BLOG_DOMAIN_NAME.com;
    location / {
        proxy_set_header   X-Real-IP $remote_addr;
        proxy_set_header   Host      $http_host;
        proxy_pass         http://DROPLET_IP_ADDRESS:2368;
    }
}

Make sure that the proxy_pass address port matches the port in your ghostconfig.js under production.

Forever to start & stop Ghost

Install Forever with npm install forever -g. cd into your ghost directory, and start ghost with NODE_ENV=production forever start index.js. You can stop ghost with forever stop index.js

If you power cycle your droplet, you will have to start ghost manual again – if anyone knows of a way about that, I would love to hear it. Mup will handle your meteor instances however.

That’s all

I hope these information were useful to some of you. I would love to read your comments below.

How To Install Nginx on Ubuntu 14.04 LTS

– 출처: https://www.digitalocean.com/community/tutorials/how-to-install-nginx-on-ubuntu-14-04-lts

Introduction

Nginx is one of the most popular web servers in the world and is responsible for hosting some of the largest and highest-traffic sites on the internet. It is more resource-friendly than Apache in most cases and can be used as a web server or a reverse proxy.

In this guide, we’ll discuss how to get Nginx installed on your Ubuntu 14.04 server.

Prerequisites

Before you begin this guide, you should have a regular, non-root user with sudo privileges configured on your server. You can learn how to configure a regular user account by following steps 1-4 in our initial server setup guide for Ubuntu 14.04.

When you have an account available, log in as your non-root user to begin.

Step One — Install Nginx

We can install Nginx easily because the Ubuntu team provides an Nginx package in its default repositories.

Since this is our first interaction with the apt packaging system in this session, we should update our local package index before we begin so that we are using the most up-to-date information. Afterwards, we will install nginx:

sudo apt-get update
sudo apt-get install nginx

You will probably be prompted for your user’s password. Enter it to confirm that you wish to complete the installation. The appropriate software will be downloaded to your server and then automatically installed.

Step Two — Check your Web Server

In Ubuntu 14.04, by default, Nginx automatically starts when it is installed.

You can access the default Nginx landing page to confirm that the software is running properly by visiting your server’s domain name or public IP address in your web browser.

If you do not have a domain name set up for your server, you can learn how to set up a domain with DigitalOcean here.

If you do not have a spare domain name, or have no need for one, you can use your server’s public IP address. If you do not know your server’s IP address, you can get it a few different ways from the command line.

Try typing this at your server’s command prompt:

ip addr show eth0 | grep inet | awk '{ print $2; }' | sed 's/\/.*$//'

You will get back one or two lines. You can try each in your web browser to see if they work.

An alternative is typing this, which should give you your public IP address as seen from another location on the internet:

curl http://icanhazip.com

When you have your servers IP address or domain, enter it into your browser’s address bar:

http://server_domain_name_or_IP

You should see the default Nginx landing page, which should look something like this:

Nginx default page

This is the default page included with Nginx to show you that the server is installed correctly.

Step Three — Manage the Nginx Process

Now that you have your web server up and running, we can go over some basic management commands.

To stop your web server, you can type:

sudo service nginx stop

To start the web server when it is stopped, type:

sudo service nginx start

To stop and then start the service again, type:

sudo service nginx restart

We can make sure that our web server will restart automatically when the server is rebooted by typing:

sudo update-rc.d nginx defaults

This should already be enabled by default, so you may see a message like this:

System start/stop links for /etc/init.d/nginx already exist.

This just means that it was already configured correctly and that no action was necessary. Either way, your Nginx service is now configured to start up at boot time.

Conclusion

Now that you have your web server installed, you have many options for the type of content to serve and the technologies you want to use to create a richer experience.

Learn how to use Nginx server blocks here. If you’d like to build out a more complete application stack, check out this article on how to configure a LEMP stack on Ubuntu 14.04.

By Justin Ellingwood

mup with Ubuntu 14.04.3

Server Settings

/etc/sudoers

%sudo    ALL=(ALL:ALL) NOPASSWD:ALL

mup

$ mup init

Meteor Up: Production Quality Meteor Deployments
------------------------------------------------

Empty Project Initialized!

mup.json

{
  // Server authentication info
  "servers": [
    {
      "host": "hostname",
      "username": "root",
      "password": "password"
      // or pem file (ssh based authentication)
      //"pem": "~/.ssh/id_rsa"
    }
  ],

  // Install MongoDB in the server, does not destroy local MongoDB on future setup
  "setupMongo": true,

  // WARNING: Node.js is required! Only skip if you already have Node.js installed on server.
  "setupNode": true,

  // WARNING: If nodeVersion omitted will setup 0.10.36 by default. Do not use v, only version number.
  "nodeVersion": "0.10.36",

  // Install PhantomJS in the server
  "setupPhantom": true,

  // Show a progress bar during the upload of the bundle to the server. 
  // Might cause an error in some rare cases if set to true, for instance in Shippable CI
  "enableUploadProgressBar": true,

  // Application name (No spaces)
  "appName": "app_name",

  // Location of app (local directory)
  "app": "/path/to/the/app",

  // Configure environment
  "env": {
    "PORT": 80,
    "ROOT_URL": "http://myapp.com",
    "MONGO_URL": "mongodb://localhost:27017/app_name"
  },

  // Meteor Up checks if the app comes online just after the deployment
  // before mup checks that, it will wait for no. of seconds configured below
  "deployCheckWaitTime": 15
}
$ mup setup

Meteor Up: Production Quality Meteor Deployments
------------------------------------------------

“ Checkout Kadira!
 It's the best way to monitor performance of your app.
 Visit: https://kadira.io/mup ”


Started TaskList: Setup (linux)
[hostname] - Installing Node.js
[hostname] - Installing Node.js: SUCCESS
[hostname] - Installing PhantomJS
[hostname] - Installing PhantomJS: SUCCESS
[hostname] - Setting up Environment
[hostname] - Setting up Environment: SUCCESS
[hostname] - Copying MongoDB configuration
[hostname] - Copying MongoDB configuration: SUCCESS
[hostname] - Installing MongoDB
[hostname] - Installing MongoDB: SUCCESS
[hostname] - Configuring upstart
[hostname] - Configuring upstart: SUCCESS

$ mup deploy

Meteor Up: Production Quality Meteor Deployments
------------------------------------------------

“ Checkout Kadira!
 It's the best way to monitor performance of your app.
 Visit: https://kadira.io/mup ”

Building Started: /path/to/the/app

Started TaskList: Deploy app 'app_name' (linux)
[hostname] - Uploading bundle
[hostname] - Uploading bundle: SUCCESS
[hostname] - Setting up Environment Variables
[hostname] - Setting up Environment Variables: SUCCESS
[hostname] - Invoking deployment process
[hostname] - Invoking deployment process: SUCCESS

$ mup start

Meteor Up: Production Quality Meteor Deployments
------------------------------------------------


Started TaskList: Starting Application (linux)
[hostname] - Starting app
[hostname] - Starting app: SUCCESS

$ mup stop

Meteor Up: Production Quality Meteor Deployments
------------------------------------------------


Started TaskList: Stopping Application (linux)
[hostname] - Stopping app
[hostname] - Stopping app: SUCCESS

mup with CentOS 6

Server Settings

centos

yum -y update  
yum -y install gcc-c++ openssl-devel  
ln -s /sbin/stop /usr/local/bin/stop  
ln -s /sbin/start /usr/local/bin/start    

nodejs

curl --silent --location https://rpm.nodesource.com/setup | bash -
yum -y install nodejs

mongodb

/etc/yum.repos.d/mongodb-org-2.6.repo

[mongodb-org-2.6]
name=MongoDB 2.6 Repository  
baseurl=http://downloads-distro.mongodb.org/repo/redhat/os/x86_64/  
gpgcheck=0  
enabled=1  
yum install -y mongodb-org  
service mongod start  

nginx

/etc/yum.repos.d/nginx.repo

[nginx]
name=nginx repo  
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/  
gpgcheck=0  
enabled=1  
yum install nginx  

mup

mup setup  
mup deploy  

Simple Meteor Deployment for CentOS 6+

– 출처: https://github.com/creatorkuang/meteor-please

meteor-please for centos 6

npm version

Simple Meteor Deployment for CentOS 6+

Installation

npm install -g mplzc6

Usage

1. Initialise

Simply run in your Meteor project’s directory:

mplzc6

You’ll get a prompt to automatically configure a mplz.json for your project.

2. Setup Your Environment

Once you’ve got a configuration file, you can spin up your server, then use this command inside your project directory to install the production environment (nodejs, mongodb, nginx):

mplzc6 setup

Now go grab a coffee, because it will probably take some time for all the things to install.

3. Deploy Your App

After the server setup is done, you can run this command to deploy your app:

mplzc6 deploy

Easy!

Commands

mplzc6 init Reconfigures your app’s mplz.json settings file.

mplzc6 setup Sets up your server according to your mplz.json settings.

mplzc6 deploy Deploys your app according to your mplz.json settings.

mplzc6 reconfig Apply any configuration changes if your mplz.json has been modified since last setup.

mplzc6 start Starts your app. (systemd)

mplzc6 stop Stops your app. (systemd)

mplzc6 restart Restarts your app. (systemd)

mplzc6 delete Deletes your app from the deployment directory.

TODOs

  • SSL
  • Multiple instances/load balancing/oplog tailing
  • Prompt cleanup/validation
  • Support for node apps
  • Exclude folders

Installing Node.js via package manager

– 출처: https://nodejs.org/en/download/package-manager/

Enterprise Linux and Fedora

Including Red Hat® Enterprise Linux® / RHEL, CentOS and Fedora.

Node.js is available from the NodeSource Enterprise Linux and Fedora binary distributions repository. Support for this repository, along with its scripts, can be found on GitHub at nodesource/distributions.

Note that the Node.js packages for EL 5 (RHEL5 and CentOS 5) depend on the EPEL repository being available. The setup script will check and provide instructions if it is not installed.

Run as root on RHEL, CentOS or Fedora, for Node.js v4 LTS Argon:

curl --silent --location https://rpm.nodesource.com/setup_4.x | bash -

Alternatively for Node.js v5:

curl --silent --location https://rpm.nodesource.com/setup_5.x | bash -

Alternatively for Node.js 0.10:

curl --silent --location https://rpm.nodesource.com/setup | bash -

Then install, as root:

yum -y install nodejs

How To Install Node.js on a CentOS 7 server

– 출처: https://www.digitalocean.com/community/tutorials/how-to-install-node-js-on-a-centos-7-server

Install Node Using the Node Version Manager

Another way of installing Node.js that is particularly flexible is through NVM, the Node version manager. This piece of software allows you to install and maintain many different independent versions of Node.js, and their associated Node packages, at the same time.

To install NVM on your CentOS 7 machine, visit the project’s GitHub page. Copy the curl or wgetcommand from the README file that displays on the main page. This will point you towards the most recent version of the installation script.

Before piping the command through to bash, it is always a good idea to audit the script to make sure it isn’t doing anything you don’t agree with. You can do that by removing the | bash segment at the end of the curl command:

curl https://raw.githubusercontent.com/creationix/nvm/v0.13.1/install.sh

Take a look and make sure you are comfortable with the changes it is making. When you are satisfied, run the command again with | bash appended at the end. The URL you use will change depending on the latest version of NVM, but as of right now, the script can be downloaded and executed by typing:

curl https://raw.githubusercontent.com/creationix/nvm/v0.13.1/install.sh | bash

This will install the nvm script to your user account. To use it, you must first source your .bash_profile:

source ~/.bash_profile

Now, you can ask NVM which versions of Node it knows about:

nvm list-remote
. . .
v0.10.29
v0.10.30
 v0.11.0
 v0.11.1
 v0.11.2
 v0.11.3
 v0.11.4
 v0.11.5
 v0.11.6
 v0.11.7
 v0.11.8
 v0.11.9
v0.11.10
v0.11.11
v0.11.12
v0.11.13

You can install a version of Node by typing any of the releases you see. For instance, to get version 0.10.30, you can type:

nvm install v0.10.30

You can see the different versions you have installed by typing:

nvm list
->  v0.10.30
      system

You can switch between them by typing:

nvm use v0.10.30
Now using node v0.10.30

To set this version as the default, type:

nvm alias default v0.10.30
default -> v0.10.30

You can verify that the install was successful using the same technique from the other sections, by typing:

node --version
v0.10.30

From the version number output, we can tell that Node is installed on our machine as we expected.