• Stars
    star
    303
  • Rank 137,655 (Top 3 %)
  • Language
    Shell
  • Created over 12 years ago
  • Updated 8 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Painlessly deploy node.js applications to your staging and production servers. Use a standard VPS or dedicated server to host both Node and traditional Apache-based websites. Pairs nicely with nginx and mechanic.

stagecoach: host multiple Node apps on your Linux servers

Stagecoach is a simple framework for deploying node.js web applications to your own servers. It is useful for both staging and production environments. It can run multiple apps on the same server, keep them running with forever, redeploy with a minimum of downtime, and restart them gracefully at reboot time.

Requirements

Your servers will need node of course, and also the forever utility:

npm install -g forever

Configuration

Stagecoach lives in /opt/stagecoach and your individual apps live in subdirectories of /opt/stagecoach/apps.

[create a user called "nodeapps"]
[log in as root]
cd /opt
git clone https://github.com/punkave/stagecoach
cd stagecoach
cp settings.example settings
[edit the settings file]
mkdir apps
chown nodeapps apps

You will carry out all of your deployments via the nodeapps user, never the root user.

You can use a different non-root account if you change the USER setting in /opt/stagecoach/settings.

sc-deploy

sc-deploy is a simple bash script that handles web app deployment with automatic rollback on failure.

sc-deploy is meant to be run on your development system, and deploys code to your servers.

Installing sc-deploy

[on your development machine]
cd
mkdir -p src
cd src
git clone https://github.com/punkave/stagecoach
cd stagecoach
subl ~/.profile
[add /Users/MYUSERNAME/src/stagecoach/bin to your PATH]

Setting up your application to be deployed

  1. Make sure your application listens on the port specified by the PORT environment variable, if available:
// Let's assume `app` is an Express app object
var port = process.env.PORT || 3000;
app.listen(port);

As seen here, it's OK to fall back to port 3000 or whatever pleases you for development work.

  1. Copy the deployment folder from our example app to your application:
cp -r src/stagecoach/example/deployment src/YOURAPPHERE/deployment
  1. Review the deployment scripts, especially migrate, which should take care of adding symlinks to any folders that contain persistent files that should not be wiped out by every new deployment. The example application has two shared folders, data and uploads. The migrate script ensures that the data folder is symbolically linked into each new deployment as data, and the uploads folder is symbolically linked as public/uploads.

The shared data folder is required. Stagecoach uses it to remember this app's assigned port number in data/port. You may also store other persistent files there.

  1. Make sure your app's main .js file is app.js, or edit deployment/start and deployment/stop.

  2. Edit deployment/settings and set PROJECT to the shortname of your project (usually, the directory name).

  3. Edit deployment/settings.production. Make sure USER matches the non-root username on the server and SERVER is the hostname of your server. Create additional settings.* files if you have additional servers to deploy to, such as staging.

  4. Deploy to production for the first time:

sc-deploy production

When the script finishes, your app will be up and running. On the first startup, a unique port number is assigned automatically and stored in data/port.

  1. Configure nginx or another server as a reverse proxy to forward traffic to your app. The easiest way to set up nginx is to use mechanic. Manual nginx configuration examples are also included below.

Updating your app

Just use sc-deploy production at any time to deploy again. The previous deployment is not shut down until after the new one is completely ready to start up, so there is very little downtime. Stagecoach does this:

  1. Deploys the new version
  2. Installs dependencies by running deployment/dependencies
  3. Stops the old app with deployment/stop
  4. Migrates with deployment/migrate
  5. Symbolically links the new deployment to /current
  6. Starts up with deployment/start

Notice that your old deployment stays up and running until the really slow stuff is already finished. That's why there is almost no downtime.

By default, 5 old deployments are kept on the server. This is useful if you need to roll back. You can change this number by setting KEEP in your deployment/settings file.

Excluding files from deployment

If an rsync_exclude.txt file is present in deployment, files mentioned there are not included in the deployment and are left alone if they exist on the server (see the rsync manpage). Shared folders like data and public/uploads folders are very important to include here.

Avoiding passwords

sc-deploy does make several ssh connections. Entering a password for each one is painful. You should definitely set up a trusted ssh public key that allows you to ssh to your server without entering your password over and over. Passwords are error-prone, annoying and insecure. Friends don't let friends use passwords.

sc-restart

If you need to restart your app but you don't have any code changes to deploy, use the sc-restart convenience command. In most cases this is unnecessary because forever will automatically keep the app running, but you might find it useful if you have changed something in the server environment and need to force your app to notice.

sc-restart will always run the deployment/stop and deployment/start scripts properly, providing support for restarting multiple instances of the app on the same server.

sc-rollback

sc-rollback is meant to be run on your development system, and rolls back deployments on other systems.

If you regret a deployment to production, type:

sc-rollback production

For a list of previous deployments, named by the date and time. For instance:

Available deployments:
2014-12-04-18-40-26
2014-12-05-08-46-33

To roll back to one of these, type:

sc-rollback production 2014-12-04-18-40-26

Warning: if you have performed database migrations that are not backwards-compatible with older versions of your code, such as removing a column from a SQL table, you should not roll back beyond that point.

example app

In the example folder you'll find an example of node app deployment, with all the important bits already set up (be sure to look in example/deployment). The start script reads data/port and sets the PORT environment variable before starting the example app, which honors the environment variable.

Running gulp, grunt, etc. before deployment

Stagecoach runs deployment/before-connecting, locally on your computer, before deploying.

This script is a convenient place to run a gulp build or similar, saving you the hassle of installing gulp and similar tools in production.

Restarting Sites on Reboot

Drop this in /etc/rc.local (on Ubuntu), /etc/rc.d/rc.local (on CentOS) or otherwise execute it on reboot:

cd /opt/stagecoach
bash bin/sc-start-all

Configuring nginx yourself

We use nginx as a reverse proxy to forward traffic for specific domain names to specific apps, each of which is listening on a particular port. The easiest way to do this is to use our mechanic tool to set up nginx.

If you don't want to use mechanic, it's not hard to set up nginx yourself. Here's a sample configuration:

server {
    listen       www.example.com:80;
    server_name  www.example.com;

    access_log  /var/log/nginx/example.access.log;
    error_log  /var/log/nginx/example.error.log;
    client_max_body_size 32M;

    location / {
     proxy_pass  http://localhost:3000;
     proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
     proxy_redirect off;
     proxy_buffering off;
     proxy_set_header        Host            $host;
     proxy_set_header        X-Real-IP       $remote_addr;
     proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
   }
}

You can get better performance by allowing nginx to serve static files directly. That's all included in our standard configuration with mechanic.

Disabling an app

To disable an application on a particular server:

[cd to your app locally first]
sc-disable production

This will stop the app and then move it to /opt/stagecoach/disabled-apps. This is handy if you are testing many apps and need to free up RAM for those in active use.

Re-enabling an app

To re-enable an app that you disabled:

[cd to your app locally first]
sc-enable production

This will move the app back to /opt/stagecoach/apps and restart it.

Running shell commands on the server conveniently

To open an interactive shell and automatically cd to the current deployment folder of your app:

[cd to your app locally first]
sc-shell production

If your app is myapp, this will automatically cd to /opt/stagecoach/apps/myapp/current before starting an interactive shell.

To simply run a remote command and then exit:

[cd to your app locally first]
sc-shell production ls

This will automatically cd to /opt/stagecoach/apps/myapp/current before running ls and exiting.

To connect as a different user:

sc-shell root@production

This command will attempt to connect as root rather than the username found in settings.production.

Using sudo on the server side

If you need to sudo on the server side after making the ssh connection, you can set the REMOTE_SUDO_USER environment variable in your settings.production file or similar for other target names. Prior to 08/21/2020 this feature was unofficial and undocumented, but used SUDO_USER, which was not a good idea beacuse that caused conflicts.

sc-proxy (deprecated)

sc-proxy is a node.js-based frontend proxy server solution for web apps that listen on independent ports, built on top of the node-http-proxy module. It picks up port numbers directly from the Stagecoach data/port files. It's a neat proof of concept, but we've found that performance is much better with nginx (see above). If you're still interested in sc-proxy, check out the README.md in that subdirectory for more information.

Warnings and Limitations

sc-deploy expects that you will not have spaces in your target deployment folder name or your project name. If you like making things difficult for shell scripts, this is not the tool for you.

The provided sample start and stop scripts do not attempt to use chroot jails to prevent apps from seeing each other's files. If you need that, you might be happier with Docker.

This isn't for Windows.

Changelog

06/11/2021:

  • The /opt/stagecoach/settings.example file contained incorrect settings. As written, it would result in /opt/stagecoach/bin/sc-start-all failing to restart applications at reboot. It now contains appropriate settings for the top-level configuration file. If you copied this file, edit it to match the new settings.example, possibly changing the non-root username setting to match your needs.

08/21/2020:

  • There was an undocumented, unofficial feature to sudo on the server side after making the ssh connection, set by passing the SUDO_USER environment variable. As it turns out, this was a bad idea because SUDO_USER is automatically set if you have used sudo in your local environment. We have changed the variable stagecoach supports to REMOTE_SUDO_USER and documented the feature.

08/01/2019:

  • If the SSH_OPTIONS environment variable is set, it will be inserted into all ssh commands used to run rsync, invoke things, etc. The contents are on the ssh command line right after ssh itself. This is handy for -i and other features not otherwise present.

12/23/2016:

  • sc-restart is now available as a handy remote command. It runs the deployment/stop and deployment/start scripts on the specified target server, exactly as if you had redeployed the site.

  • The default start script is now smart enough to take apps configured for multiple ports into account when searching for the next free port for a new app.

09/14/2016: sc-shell now accepts an optional username. Syntax: sc-shell root@production connects to the production target but uses the username root rather than the username in the settings.production file.

03/10/2016: important sc-deploy fixes for error conditions.

  • If a deployment fails, correctly print an error message rather than a cheerful one. (Previously sc-deploy was doing the right thing, but printing the wrong thing. Except in cases where migrate failed, as mentioned below.)

  • If a deployment fails, and we got as far as stopping the previous deployment, relink and restart the previous deployment. This is important if the migrate script fails. Did you know that if statements destroy $?? I didn't. Man, I hate shell scripting.

  • Updated various misleading comments in old scripts in example/deployment.

  • Just for newbie convenience, the dependencies script of the example project will create the new deployment folder's public subdirectory if it is missing. In real life projects you'll have one with static assets at the very least, or you'll edit dependencies.

02/14/2016: sc-shell now cds correctly when running a command rather than an interactive shell.

02/09/2016: added the sc-shell, sc-disable and sc-enable utilities.

09/25/2015: deprecated sc-proxy in favor of nginx, managed by mechanic. Moved things that have nothing to do with sc-proxy out of that subdirectory. Rewrote the documentation to reflect our own best practices.

12/11/2014: sc-rollback introduced.

06/18/2013: sc-deploy overhauled. Now keeps 5 deployments on the server by default rather than keeping them forever. You can adjust this number via the KEEP variable in deployment/settings. Also, sc-deploy does a better job of recognizing problems at the end of the deployment process and will flip the symbolic link back to the previous deployment and attempt to restart that version of the code if deployment fails.

Contact

[email protected] mostly maintains this. You can also open issues on github. We welcome pull requests.

More Repositories

1

apostrophe

A full-featured, open-source content management framework built with Node.js that empowers organizations by combining in-context editing and headless architecture in a full-stack JS environment.
JavaScript
4,318
star
2

sanitize-html

Clean up user-submitted HTML, preserving whitelisted elements and whitelisted attributes on a per-element basis. Built on htmlparser2 for speed and tolerance
JavaScript
3,413
star
3

random-words

Generate one or more common English words. Intended for use as sample text, for example generating random blog posts for testing
JavaScript
222
star
4

mechanic

Command-line tool to manage nginx-powered proxies for node apps. Static file delivery, load balancing, HTTPS, all that jazz with a clean interface.
JavaScript
167
star
5

apostrophe-sandbox

This sandbox site is the basis for our live demo. For your own projects, you can use apostrophe-boilerplate as a more streamlined, cleaner point of departure via the apostrophe-cli tool.
Less
112
star
6

apostrophe-headless

Add REST APIs to your Apostrophe "pieces," powering your React/Vue/etc. apps with a headless CMS.
JavaScript
97
star
7

express-cache-on-demand

express-cache-on-demand
JavaScript
80
star
8

prettiest

Improbably easy data storage and locking for command line scripts. Pairs well with shelljs and a nice chianti.
JavaScript
77
star
9

oembetter

A modern oembed client. Allows you to register filters to improve or supply oembed support for sites that don't normally have it. You can also supply a whitelist of services you trust to prevent XSS attacks.
JavaScript
50
star
10

uploadfs

Store files in a web-accessible location. Includes S3, Azure, and local filesystem-based backends. Can also scale and autorotate image files. Additional storage and image-processing backends are easy to create.
JavaScript
50
star
11

sluggo

High-speed, unicode-aware, browser-friendly slug generator
JavaScript
47
star
12

split-html

Split HTML into two valid fragments wherever a certain selector is matched. Works on the server side.
JavaScript
36
star
13

apostrophe-workflow

Provides approval-based workflow and localization capabilities for projects that need them. An optional component of the Apostrophe CMS.
JavaScript
36
star
14

apostrophe-open-museum

Learn about ApostropheCMS via this boilerplate site built for an imaginary art museum.
HTML
34
star
15

apostrophe-documentation

Documentation for the ApostroheCMS open-souce ecosystem
Shell
25
star
16

apostrophe-blog

Blogging for the Apostrophe 2 content management system for Node.
JavaScript
22
star
17

moog

Moog provides powerful module subclassing.
JavaScript
18
star
18

absolution

Accepts HTML and a base URL, and returns HTML with absolute URLs. Great for generating valid RSS feed entries.
JavaScript
15
star
19

apostrophe-boilerplate

Shell
14
star
20

apostrophe-seo

SEO for ApostropheCMS
JavaScript
14
star
21

apostrophe-cli

DEPRECATED. Use `@apostrophecms/cli` as the active ApostropheCMS CLI tool.
JavaScript
14
star
22

apostrophe-samples

An Apostrophe website that demonstrates various techniques and will be linked to in documentation, stackoverflow answers, etc. Check it out to learn where that code is supposed to go!
JavaScript
13
star
23

apostrophe-passport

Allows users to log into Apostrophe CMS sites via Google, Gitlab, etc. Works with most passport strategy modules.
JavaScript
13
star
24

apostrophe-palette

An in-context interface for modifying the the visual appearance of an ApostropheCMS site.
JavaScript
12
star
25

apostrophe-events

JavaScript
10
star
26

apostrophe-forms

Allow your users to build custom forms on the fly on your Apostrophe site
JavaScript
9
star
27

apostrophe-guides

Build guides for your ApostropheCMS website
JavaScript
9
star
28

apostrophe-monitor

Monitors and restarts an Apostrophe app when your code, templates, etc. change. Like nodemon but much faster because it takes advantage of how Apostrophe works.
JavaScript
8
star
29

apostrophe-tiptap-rich-text-widgets

Wrapper allowing the use of the tiptap vue-based rich-text editor for Apostrophe 2.x. In 3.x it will be standard equipment.
JavaScript
6
star
30

apostrophe-signup

Lets the public sign up for accounts on a website powered by apostrophecms.
JavaScript
6
star
31

apostrophe-enterprise-testbed

A testbed for browser-based functional testing of apostrophe, apostrophe-workflow, and similar modules found in enterprise settings.
JavaScript
6
star
32

apostrophe-lean-frontend

An alternative frontend javascript environment for ApostropheCMS, with no vendor libraries (no jQuery, no lodash, etc). Just enough glue to let you write widget players, plus some players for standard widgets which you can opt into... otherwise it doesn't push them at all.
JavaScript
6
star
33

apostrophe-places

0.6 implementation of apostrophe-map
JavaScript
5
star
34

a3-boilerplate

Simple, minimal starting point for new Apostrophe 3 projects
Shell
5
star
35

apostrophe-site-map

Generates a site map of your Apostrophe site, for SEO and content strategy purposes.
JavaScript
5
star
36

broadband

Given a MongoDB query cursor, process the results in parallel, up to the specified limit.
JavaScript
5
star
37

launder

A sanitizer module for the people. Built for Apostrophe.
JavaScript
4
star
38

linode-dns-tools

Power tools for the linode DNS API. Import a zone file, globally replace an IP address, etc.
JavaScript
4
star
39

count-outside-pull-requests

Count pull requests to your github repositories from outside your team.
JavaScript
4
star
40

max-mem

Measure maximum memory usage of a command
JavaScript
4
star
41

boring

A minimalist command line option parser.
JavaScript
4
star
42

time-limited-regular-expressions

Evaluates regular expressions with a time limit to mitigate DOS attacks based on catastrophic backtracking.
JavaScript
3
star
43

apostrophe-optimizer

Optimizes the performance of the Apostrophe CMS by prefetching related content to eliminate extra MongoDB queries.
JavaScript
3
star
44

piece-type-importer

JavaScript
3
star
45

apostrophe-open-graph

Open Graph for ApostropheCMS
JavaScript
3
star
46

apostrophe-elasticsearch

All text searches within Apostrophe are powered by Elasticsearch when this module is active.
JavaScript
3
star
47

sync-content

Back up and restore Apostrophe sites via the admin bar. Also useful for moving content between environments.
JavaScript
3
star
48

apostrophe-profiler

Debug tools for the Apostrophe CMS
JavaScript
3
star
49

apostrophe-link-widgets

ApostropheCMS link widgets
JavaScript
3
star
50

moog-require

Leverage npm's "require" with the "moog" module subclassing tool
JavaScript
3
star
51

apostrophe-personas

Specialize the content of each page of an Apostrophe site based on the user's primary affiliation (employee versus employer, truck vs. car, etc.)
JavaScript
3
star
52

apostrophe-selective-permissions

Create specialized permissions for users of your ApostropheCMS site, such as an "seo" permission that allows editing only certain fields of certain pieces and pages.
JavaScript
2
star
53

security-headers

This module sends the modern HTTP security headers that are expected by various security scanners.
JavaScript
2
star
54

apostrophe-favicons

Generates and links a set of favicons from an image in the media library
JavaScript
2
star
55

cache-on-demand

"On demand" caching that kicks in only when requests arrive simultaneously.
JavaScript
2
star
56

a3-docs

Apostrophe 3.x documentation.
Shell
2
star
57

a3-demo

A test project for ApostropheCMS 3.x
JavaScript
2
star
58

apostrophe-secure-attachments

Limit direct URL access to uploaded attachments, such as PDFs, to those who have appropriate permissions.
JavaScript
2
star
59

apostrophe-pieces-orderings-bundle

Manually sort your pieces, then put that handpicked order into effect for pieces-pages, widgets and even the manage view.
JavaScript
2
star
60

apostrophe-redirects

Allows admins to create redirects within an Apostrophe site
JavaScript
2
star
61

heic-to-jpeg-middleware

Middleware to convert HEIC/HEIF files from iOS 11 devices like the iPhone to JPEG format, with no other modifications to your code that expects JPEG
JavaScript
2
star
62

apostrophe-atom

Atom snippets for working with Apostrophe projects.
2
star
63

form

JavaScript
2
star
64

apostrophe-nightwatch-tools

Nightwatch custom commands useful for testing ApostropheCMS sites.
JavaScript
2
star
65

stylelint-config-apostrophe

An stylelint configuration for Apostrophe.
JavaScript
2
star
66

apostrophe-override-options

Override Apostrophe's getOption method based on the current page type, page settings, etc.
JavaScript
2
star
67

apostrophe-address-widgets

ApostropheCMS address widgets
JavaScript
2
star
68

apostrophe-pieces-submit-widgets

Submit user generated content to Apostrophe CMS
JavaScript
2
star
69

apostrophe-pieces-import

Adds features to apostrophe-pieces allowing easy import of content via CSV, Excel, etc.
JavaScript
2
star
70

apostrophe-storybook

This repository is deprecated. The UI library is now included in ApostropheCMS core, in the 3.0 branch.
Vue
2
star
71

apostrophe-review-and-deploy

Require an approval process for the entire site, or one locale, then push the site's content from "pre-production" to production on another host
JavaScript
2
star
72

apostrophe-gulp-starter

A demo configuration incorporating Gulp.js with ApostropheCMS
Shell
2
star
73

content-upgrader

Tools to upgrade your site's content from previous versions of Apostrophe. See also code-upgrader.
JavaScript
2
star
74

apostrophe-rich-text-permalinks

Create permalinks to Apostrophe content inside the rich text editor. Your permalinks will stay fresh if the content moves.
JavaScript
2
star
75

apostrophe-i18n-static

Add editable pieces for translation through i18n to an Apostrophe project
JavaScript
2
star
76

apostrophe-svg-sprites

apostrophe-images for SVGs in external sprite maps!
JavaScript
2
star
77

redirect

Manage site redirects for Apostrophe 3.
JavaScript
1
star
78

sitemap

The Apostrophe Sitemap module generates XML sitemaps for websites powered by Apostrophe 3.
JavaScript
1
star
79

apostrophe-twitter-widgets

Twitter for Apostrophe 2
JavaScript
1
star
80

apostrophe-pubmed

Piece subclass with an enhanced editor modal for easily syncing single PubMed docs to new piece instances
JavaScript
1
star
81

apostrophe-maintenance-mode

Put your Apostrophe site in maintenance mode, preventing access until you turn it on again
JavaScript
1
star
82

gatsby-source-apostrophe

Gatsby source plugin for ApostropheCMS
JavaScript
1
star
83

apostrophe-saml

Single sign-on for the Apostrophe CMS via SAML or Shibboleth
JavaScript
1
star
84

apostrophe-pieces-export

JavaScript
1
star
85

apostrophe-styleguide

Boilerplate styleguide to drop into your projects
HTML
1
star
86

kafka

Kafka support for A3
JavaScript
1
star
87

apostrophe-docs-popularity

Track and sort the popularity of pieces and pages on an Apostrophe site according to metrics of your choice: social network votes, views, votes, etc.
JavaScript
1
star
88

apostrophe-db-mongo-3-driver

Extends ApostropheCMS to use the 3.x version of the MongoDB native driver, for better compatibility with MongoDB 3.6, 4.0, etc.
JavaScript
1
star
89

code-upgrader

Very pre-alpha tool for converting apostrophe modules from 2.x format to newer format using esprima and escodegen.
JavaScript
1
star
90

blog

An A3 bundle for managing and browsing blog articles
JavaScript
1
star
91

asset-es5

For those who still require IE11 support for the frontend build.
JavaScript
1
star
92

apostrophe-login-recaptcha

Attempt to prove users are human before allowing local login to apostrophe
JavaScript
1
star
93

apostrophe-query-cache

Simple mongodb query caching solution for Apostrophe sites that become database-bound.
JavaScript
1
star
94

apostrophe-caches-redis

Replaces Apostrophe's MongoDB-based caching mechanism with Redis.
JavaScript
1
star
95

login-totp

JavaScript
1
star
96

seo

Add and manage SEO meta fields to all documents in Apostrophe 3.
JavaScript
1
star
97

csv-to-zone-file

Converts CSV to a zonefile just good enough to import into Amazon Route 53
JavaScript
1
star
98

eslint-config-apostrophe

An eslint configuration for the apostrophe core modules.
JavaScript
1
star
99

apostrophe-area-structure

A modal window that displays a visualization of your page's area structure
JavaScript
1
star
100

apostrophe-external-notifications

Send notifications via Slack and other systems when various events occur in ApostropheCMS
JavaScript
1
star