Skip to content

Instantly share code, notes, and snippets.

@gaurish
Created December 3, 2012 17:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gaurish/4196493 to your computer and use it in GitHub Desktop.
Save gaurish/4196493 to your computer and use it in GitHub Desktop.
Part of Rails Server Bootstrap Script
#
# Based upon the NCSA server configuration files originally by Rob McCool.
#
# This is the main Apache server configuration file. It contains the
# configuration directives that give the server its instructions.
# See http://httpd.apache.org/docs/2.2/ for detailed information about
# the directives.
#
# Do NOT simply read the instructions in here without understanding
# what they do. They're here only as hints or reminders. If you are unsure
# consult the online docs. You have been warned.
#
# The configuration directives are grouped into three basic sections:
# 1. Directives that control the operation of the Apache server process as a
# whole (the 'global environment').
# 2. Directives that define the parameters of the 'main' or 'default' server,
# which responds to requests that aren't handled by a virtual host.
# These directives also provide default values for the settings
# of all virtual hosts.
# 3. Settings for virtual hosts, which allow Web requests to be sent to
# different IP addresses or hostnames and have them handled by the
# same Apache server process.
#
# Configuration and logfile names: If the filenames you specify for many
# of the server's control files begin with "/" (or "drive:/" for Win32), the
# server will use that explicit path. If the filenames do *not* begin
# with "/", the value of ServerRoot is prepended -- so "/var/log/apache2/foo.log"
# with ServerRoot set to "" will be interpreted by the
# server as "//var/log/apache2/foo.log".
#
### Section 1: Global Environment
#
# The directives in this section affect the overall operation of Apache,
# such as the number of concurrent requests it can handle or where it
# can find its configuration files.
#
#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# NOTE! If you intend to place this on an NFS (or otherwise network)
# mounted filesystem then please read the LockFile documentation (available
# at <URL:http://httpd.apache.org/docs-2.1/mod/mpm_common.html#lockfile>);
# you will save yourself a lot of trouble.
#
# Do NOT add a slash at the end of the directory path.
#
ServerRoot "/etc/apache2"
#
# The accept serialization lock file MUST BE STORED ON A LOCAL DISK.
#
#<IfModule !mpm_winnt.c>
#<IfModule !mpm_netware.c>
LockFile /var/lock/apache2/accept.lock
#</IfModule>
#</IfModule>
#
# PidFile: The file in which the server should record its process
# identification number when it starts.
# This needs to be set in /etc/apache2/envvars
#
PidFile ${APACHE_PID_FILE}
#
# Timeout: The number of seconds before receives and sends time out.
#
Timeout 100
#
# KeepAlive: Whether or not to allow persistent connections (more than
# one request per connection). Set to "Off" to deactivate.
#
KeepAlive On
#
# MaxKeepAliveRequests: The maximum number of requests to allow
# during a persistent connection. Set to 0 to allow an unlimited amount.
# We recommend you leave this number high, for maximum performance.
#
MaxKeepAliveRequests 100
#
# KeepAliveTimeout: Number of seconds to wait for the next request from the
# same client on the same connection.
#
KeepAliveTimeout 5
##
## Server-Pool Size Regulation (MPM specific)
##
# prefork MPM
# StartServers: number of server processes to start
# MinSpareServers: minimum number of server processes which are kept spare
# MaxSpareServers: maximum number of server processes which are kept spare
# MaxClients: maximum number of server processes allowed to start
# MaxRequestsPerChild: maximum number of requests a server process serves
<IfModule mpm_prefork_module>
StartServers 5
MinSpareServers 5
MaxSpareServers 10
MaxClients 161
MaxRequestsPerChild 300
</IfModule>
# worker MPM
# StartServers: initial number of server processes to start
# MaxClients: maximum number of simultaneous client connections
# MinSpareThreads: minimum number of worker threads which are kept spare
# MaxSpareThreads: maximum number of worker threads which are kept spare
# ThreadsPerChild: constant number of worker threads in each server process
# MaxRequestsPerChild: maximum number of requests a server process serves
<IfModule mpm_worker_module>
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxClients 161
MaxRequestsPerChild 0
</IfModule>
# event MPM
# StartServers: initial number of server processes to start
# MaxClients: maximum number of simultaneous client connections
# MinSpareThreads: minimum number of worker threads which are kept spare
# MaxSpareThreads: maximum number of worker threads which are kept spare
# ThreadsPerChild: constant number of worker threads in each server process
# MaxRequestsPerChild: maximum number of requests a server process serves
<IfModule mpm_event_module>
StartServers 2
MaxClients 161
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestsPerChild 0
</IfModule>
# These need to be set in /etc/apache2/envvars
User ${APACHE_RUN_USER}
Group ${APACHE_RUN_GROUP}
#
# AccessFileName: The name of the file to look for in each directory
# for additional configuration directives. See also the AllowOverride
# directive.
#
AccessFileName .htaccess
#
# The following lines prevent .htaccess and .htpasswd files from being
# viewed by Web clients.
#
<Files ~ "^\.ht">
Order allow,deny
Deny from all
Satisfy all
</Files>
#
# DefaultType is the default MIME type the server will use for a document
# if it cannot otherwise determine one, such as from filename extensions.
# If your server contains mostly text or HTML documents, "text/plain" is
# a good value. If most of your content is binary, such as applications
# or images, you may want to use "application/octet-stream" instead to
# keep browsers from trying to display binary files as though they are
# text.
#
DefaultType text/plain
#
# HostnameLookups: Log the names of clients or just their IP addresses
# e.g., www.apache.org (on) or 204.62.129.132 (off).
# The default is off because it'd be overall better for the net if people
# had to knowingly turn this feature on, since enabling it means that
# each client request will result in AT LEAST one lookup request to the
# nameserver.
#
HostnameLookups Off
# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here. If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
ErrorLog /var/log/apache2/error.log
#
# LogLevel: Control the number of messages logged to the error_log.
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
#
LogLevel warn
# Include module configuration:
Include /etc/apache2/mods-enabled/*.load
Include /etc/apache2/mods-enabled/*.conf
# Include all the user configurations:
Include /etc/apache2/httpd.conf
# Include ports listing
Include /etc/apache2/ports.conf
#
# The following directives define some format nicknames for use with
# a CustomLog directive (see below).
# If you are behind a reverse proxy, you might want to change %h into %{X-Forwarded-For}i
#
LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined
LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %O" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent
#
# Define an access log for VirtualHosts that don't define their own logfile
CustomLog /var/log/apache2/other_vhosts_access.log vhost_combined
# Include of directories ignores editors' and dpkg's backup files,
# see README.Debian for details.
# Include generic snippets of statements
Include /etc/apache2/conf.d/
# Include the virtual host configurations:
Include /etc/apache2/sites-enabled/
NameVirtualHost *:80
Include passenger.conf
require 'bundler/capistrano'
# you can configure your Rails
# app to use this deployment recipe by doing the following:
#
# 1. Add `gem 'capistrano'` to your Gemfile.
# 2. Run `bundle install --binstubs --path=vendor/bundles`.
# 3. Run `bin/capify .` in your app's root directory.
# 4. Replace your new config/deploy.rb with this file's contents.
# 5. Configure the two parameters in the Configuration section below.
# 6. Run `git commit -a -m "Configured capistrano deployments."`.
# 7. Run `git push origin master`.
# 8. Run `bin/cap deploy:setup`.
# 9. Run `bin/cap deploy:migrations` or `bin/cap deploy`.
#
# Note: You may also need to add your local system's public key to
# your GitHub repository's Admin / Deploy Keys area.
#
# Note: When deploying, you'll be asked to enter your server's root
# password. To configure password-less deployments, see below.
#############################################
## ##
## Configuration ##
## ##
#############################################
REPOSITORY_URL = ''
SERVER_HOSTNAME = ''
#############################################
#############################################
# General Options
set :bundle_flags, "--deployment"
set :application, "railsrumble"
set :deploy_to, "/var/www/apps/railsrumble"
set :normalize_asset_timestamps, false
set :rails_env, "production"
set :user, "root"
set :runner, "www-data"
set :admin_runner, "www-data"
# Password-less Deploys (Optional)
#
# 1. Locate your local public SSH key file. (Usually ~/.ssh/id_rsa.pub)
# 2. Execute the following locally: (You'll need your server's root password.)
#
# cat ~/.ssh/id_rsa.pub | ssh root@SERVER_HOSTNAME "cat >> ~/.ssh/authorized_keys"
#
# 3. Uncomment the below ssh_options[:keys] line in this file.
#
# ssh_options[:keys] = ["~/.ssh/id_rsa"]
# SCM Options
set :scm, :git
set :repository, REPOSITORY_URL
set :branch, "master"
# Roles
role :app, SERVER_HOSTNAME
role :db, SERVER_HOSTNAME, :primary => true
# Add Configuration Files & Compile Assets
after 'deploy:update_code' do
# Setup Configuration
run "cp #{shared_path}/config/database.yml #{release_path}/config/database.yml"
# Compile Assets
run "cd #{release_path}; RAILS_ENV=production bundle exec rake assets:precompile"
end
# Restart Passenger
deploy.task :restart, :roles => :app do
# Fix Permissions
sudo "chown -R www-data:www-data #{current_path}"
sudo "chown -R www-data:www-data #{latest_release}"
sudo "chown -R www-data:www-data #{shared_path}/bundle"
sudo "chown -R www-data:www-data #{shared_path}/log"
# Restart Application
run "touch #{current_path}/tmp/restart.txt"
end
#!/bin/bash
#
# StackScript Bash Library
#
# Copyright (c) 2010 Linode LLC / Christopher S. Aker <caker@linode.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice, this
# list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
#
# * Neither the name of Linode LLC nor the names of its contributors may be
# used to endorse or promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
# SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
# TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
# DAMAGE.
###########################################################
# System
###########################################################
function system_update {
apt-get update
apt-get -y install aptitude
aptitude -y full-upgrade
}
function system_primary_ip {
# returns the primary IP assigned to eth0
echo $(ifconfig eth0 | awk -F: '/inet addr:/ {print $2}' | awk '{ print $1 }')
}
function get_rdns {
# calls host on an IP address and returns its reverse dns
if [ ! -e /usr/bin/host ]; then
aptitude -y install dnsutils > /dev/null
fi
echo $(host $1 | awk '/pointer/ {print $5}' | sed 's/\.$//')
}
function get_rdns_primary_ip {
# returns the reverse dns of the primary IP assigned to this system
echo $(get_rdns $(system_primary_ip))
}
###########################################################
# Postfix
###########################################################
function postfix_install_loopback_only {
# Installs postfix and configure to listen only on the local interface. Also
# allows for local mail delivery
echo "postfix postfix/main_mailer_type select Internet Site" | debconf-set-selections
echo "postfix postfix/mailname string localhost" | debconf-set-selections
echo "postfix postfix/destinations string localhost.localdomain, localhost" | debconf-set-selections
aptitude -y install postfix
/usr/sbin/postconf -e "inet_interfaces = loopback-only"
#/usr/sbin/postconf -e "local_transport = error:local delivery is disabled"
touch /tmp/restart-postfix
}
###########################################################
# Apache
###########################################################
function apache_install {
# installs the system default apache2 MPM
aptitude -y install apache2
a2dissite default # disable the interfering default virtualhost
# clean up, or add the NameVirtualHost line to ports.conf
sed -i -e 's/^NameVirtualHost \*$/NameVirtualHost *:80/' /etc/apache2/ports.conf
if ! grep -q NameVirtualHost /etc/apache2/ports.conf; then
echo 'NameVirtualHost *:80' > /etc/apache2/ports.conf.tmp
cat /etc/apache2/ports.conf >> /etc/apache2/ports.conf.tmp
mv -f /etc/apache2/ports.conf.tmp /etc/apache2/ports.conf
fi
}
function apache_tune {
# Tunes Apache's memory to use the percentage of RAM you specify, defaulting to 40%
# $1 - the percent of system memory to allocate towards Apache
if [ ! -n "$1" ];
then PERCENT=40
else PERCENT="$1"
fi
aptitude -y install apache2-mpm-prefork
PERPROCMEM=10 # the amount of memory in MB each apache process is likely to utilize
MEM=$(grep MemTotal /proc/meminfo | awk '{ print int($2/1024) }') # how much memory in MB this system has
MAXCLIENTS=$((MEM*PERCENT/100/PERPROCMEM)) # calculate MaxClients
MAXCLIENTS=${MAXCLIENTS/.*} # cast to an integer
sed -i -e "s/\(^[ \t]*MaxClients[ \t]*\)[0-9]*/\1$MAXCLIENTS/" /etc/apache2/apache2.conf
touch /tmp/restart-apache2
}
function apache_virtualhost {
# Configures a VirtualHost
# $1 - required - the hostname of the virtualhost to create
if [ ! -n "$1" ]; then
echo "apache_virtualhost() requires the hostname as the first argument"
return 1;
fi
if [ -e "/etc/apache2/sites-available/$1" ]; then
echo /etc/apache2/sites-available/$1 already exists
return;
fi
mkdir -p /srv/www/$1/public_html /srv/www/$1/logs
echo "<VirtualHost *:80>" > /etc/apache2/sites-available/$1
echo " ServerName $1" >> /etc/apache2/sites-available/$1
echo " DocumentRoot /srv/www/$1/public_html/" >> /etc/apache2/sites-available/$1
echo " ErrorLog /srv/www/$1/logs/error.log" >> /etc/apache2/sites-available/$1
echo " CustomLog /srv/www/$1/logs/access.log combined" >> /etc/apache2/sites-available/$1
echo "</VirtualHost>" >> /etc/apache2/sites-available/$1
a2ensite $1
touch /tmp/restart-apache2
}
function apache_virtualhost_from_rdns {
# Configures a VirtualHost using the rdns of the first IP as the ServerName
apache_virtualhost $(get_rdns_primary_ip)
}
function apache_virtualhost_get_docroot {
if [ ! -n "$1" ]; then
echo "apache_virtualhost_get_docroot() requires the hostname as the first argument"
return 1;
fi
if [ -e /etc/apache2/sites-available/$1 ];
then echo $(awk '/DocumentRoot/ {print $2}' /etc/apache2/sites-available/$1 )
fi
}
###########################################################
# mysql-server
###########################################################
function mysql_install {
# $1 - the mysql root password
if [ ! -n "$1" ]; then
echo "mysql_install() requires the root pass as its first argument"
return 1;
fi
echo "mysql-server-5.1 mysql-server/root_password password $1" | debconf-set-selections
echo "mysql-server-5.1 mysql-server/root_password_again password $1" | debconf-set-selections
apt-get -y install mysql-server mysql-client
echo "Sleeping while MySQL starts up for the first time..."
sleep 5
}
function mysql_tune {
# Tunes MySQL's memory usage to utilize the percentage of memory you specify, defaulting to 40%
# $1 - the percent of system memory to allocate towards MySQL
if [ ! -n "$1" ];
then PERCENT=40
else PERCENT="$1"
fi
sed -i -e 's/^#skip-innodb/skip-innodb/' /etc/mysql/my.cnf # disable innodb - saves about 100M
MEM=$(awk '/MemTotal/ {print int($2/1024)}' /proc/meminfo) # how much memory in MB this system has
MYMEM=$((MEM*PERCENT/100)) # how much memory we'd like to tune mysql with
MYMEMCHUNKS=$((MYMEM/4)) # how many 4MB chunks we have to play with
# mysql config options we want to set to the percentages in the second list, respectively
OPTLIST=(key_buffer sort_buffer_size read_buffer_size read_rnd_buffer_size myisam_sort_buffer_size query_cache_size)
DISTLIST=(75 1 1 1 5 15)
for opt in ${OPTLIST[@]}; do
sed -i -e "/\[mysqld\]/,/\[.*\]/s/^$opt/#$opt/" /etc/mysql/my.cnf
done
for i in ${!OPTLIST[*]}; do
val=$(echo | awk "{print int((${DISTLIST[$i]} * $MYMEMCHUNKS/100))*4}")
if [ $val -lt 4 ]
then val=4
fi
config="${config}\n${OPTLIST[$i]} = ${val}M"
done
sed -i -e "s/\(\[mysqld\]\)/\1\n$config\n/" /etc/mysql/my.cnf
touch /tmp/restart-mysql
}
function mysql_create_database {
# $1 - the mysql root password
# $2 - the db name to create
if [ ! -n "$1" ]; then
echo "mysql_create_database() requires the root pass as its first argument"
return 1;
fi
if [ ! -n "$2" ]; then
echo "mysql_create_database() requires the name of the database as the second argument"
return 1;
fi
echo "CREATE DATABASE $2;" | mysql -u root -p$1
}
function mysql_create_user {
# $1 - the mysql root password
# $2 - the user to create
# $3 - their password
if [ ! -n "$1" ]; then
echo "mysql_create_user() requires the root pass as its first argument"
return 1;
fi
if [ ! -n "$2" ]; then
echo "mysql_create_user() requires username as the second argument"
return 1;
fi
if [ ! -n "$3" ]; then
echo "mysql_create_user() requires a password as the third argument"
return 1;
fi
echo "CREATE USER '$2'@'localhost' IDENTIFIED BY '$3';" | mysql -u root -p$1
}
function mysql_grant_user {
# $1 - the mysql root password
# $2 - the user to bestow privileges
# $3 - the database
if [ ! -n "$1" ]; then
echo "mysql_create_user() requires the root pass as its first argument"
return 1;
fi
if [ ! -n "$2" ]; then
echo "mysql_create_user() requires username as the second argument"
return 1;
fi
if [ ! -n "$3" ]; then
echo "mysql_create_user() requires a database as the third argument"
return 1;
fi
echo "GRANT ALL PRIVILEGES ON $3.* TO '$2'@'localhost';" | mysql -u root -p$1
echo "FLUSH PRIVILEGES;" | mysql -u root -p$1
}
###########################################################
# PHP functions
###########################################################
function php_install_with_apache {
aptitude -y install php5 php5-mysql libapache2-mod-php5
touch /tmp/restart-apache2
}
function php_tune {
# Tunes PHP to utilize up to 32M per process
sed -i'-orig' 's/memory_limit = [0-9]\+M/memory_limit = 32M/' /etc/php5/apache2/php.ini
touch /tmp/restart-apache2
}
###########################################################
# Wordpress functions
###########################################################
function wordpress_install {
# installs the latest wordpress tarball from wordpress.org
# $1 - required - The existing virtualhost to install into
if [ ! -n "$1" ]; then
echo "wordpress_install() requires the vitualhost as its first argument"
return 1;
fi
if [ ! -e /usr/bin/wget ]; then
aptitude -y install wget
fi
VPATH=$(apache_virtualhost_get_docroot $1)
if [ ! -n "$VPATH" ]; then
echo "Could not determine DocumentRoot for $1"
return 1;
fi
# download, extract, chown, and get our config file started
cd $VPATH
wget http://wordpress.org/latest.tar.gz
tar xfz latest.tar.gz
chown -R www-data: wordpress/
cd $VPATH/wordpress
cp wp-config-sample.php wp-config.php
chown www-data wp-config.php
chmod 640 wp-config.php
# database configuration
WPPASS=$(randomString 20)
mysql_create_database "$DB_PASSWORD" wordpress
mysql_create_user "$DB_PASSWORD" wordpress "$WPPASS"
mysql_grant_user "$DB_PASSWORD" wordpress wordpress
# configuration file updates
for i in {1..4}
do sed -i "0,/put your unique phrase here/s/put your unique phrase here/$(randomString 50)/" wp-config.php
done
sed -i 's/database_name_here/wordpress/' wp-config.php
sed -i 's/username_here/wordpress/' wp-config.php
sed -i "s/password_here/$WPPASS/" wp-config.php
# http://downloads.wordpress.org/plugin/wp-super-cache.0.9.8.zip
}
###########################################################
# Other niceties!
###########################################################
function goodstuff {
# Installs the REAL vim, wget, less, and enables color root prompt and the "ll" list long alias
aptitude -y install wget vim less
sed -i -e 's/^#PS1=/PS1=/' /root/.bashrc # enable the colorful root bash prompt
sed -i -e "s/^#alias ll='ls -l'/alias ll='ls -al'/" /root/.bashrc # enable ll list long alias <3
}
###########################################################
# utility functions
###########################################################
function restartServices {
# restarts services that have a file in /tmp/needs-restart/
for service in $(ls /tmp/restart-* | cut -d- -f2-10); do
/etc/init.d/$service restart
rm -f /tmp/restart-$service
done
}
function randomString {
if [ ! -n "$1" ];
then LEN=20
else LEN="$1"
fi
echo $(</dev/urandom tr -dc A-Za-z0-9 | head -c $LEN) # generate a random string
}
##
## passenger.conf -- Passenger configuration file
##
##
# This is the Passenger configuration file. It contains the
# configuration directives for Passenger. See
# <URL:http://www.modrails.com/documentation/Users guide.html>
# for detailed information about the directives.
# Passenger Settings for Ruby Enterprise
LoadModule passenger_module /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.17/ext/apache2/mod_passenger.so
PassengerRoot /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.17
PassengerRuby /usr/local/bin/ruby
## PassengerLogLevel
#
# Specify how much information Phusion Passenger should write to the
# Apache error log file. A higher log level value means that more
# information will be logged.
#
# 0: Show only errors and warnings. This is the default setting.
# 1: Show the most important debugging information. This might be useful
# for system administrators who are trying to figure out the cause
# of a problem.
# 2: Show more debugging information. This is typically
# only useful for developers.
# 3: Show even more debugging information.
# PassengerLogLevel 0
# PassengerUseGlobalQueue
PassengerUseGlobalQueue on
## PassengerUserSwitching
#
# Enable User Switching Support. This option starts your application
# as the owner of the file config/environment.rb. The owner of
# environment.rb must have read access to the Rails application's
# folder, and read/write access to the Rails application's logs folder.
# This feature is only available if Apache is started by root.
#
# Options: <on|off>
# PassengerUserSwitching on
## PassengerDefaultUser
#
# Specify the user Passenger must run as. This option allows you
# to specify which user your application will run as if user
# switching fails or is disabled.
# PassengerDefaultUser deploy
## PassengerMaxPoolSize
#
# Set the maximum number of application instances that can be
# simultaneously active. A larger number results in higher
# memory usage, but improved ability to handle concurrent HTTP clients.
# The optimal value depends on your system's hardware and the server's
# average load. You should experiment with different values. Generally
# speaking, the value should be at least equal to the number of CPUs
# (or CPU cores) that you have. If your system has 2 GB of RAM, then
# we recommend a value of 30. If your system is a Virtual Private
# Server (VPS) and has about 256 MB RAM, and is also running other
# services such as MySQL, then we recommend a value of 2.
PassengerMaxPoolSize 8
## PassengerMaxInstancesPerApp
#
# Set the maximum number of application instances that may
# be simultaneously active for a single application. This helps to
# make sure that a single application will not occupy all available
# slots in the application pool. This value must be less than
# PassengerMaxPoolSize. A value of 0 means that there is no limit
# placed on the number of instances a single application may use,
# i.e. only the global limit of PassengerMaxPoolSize will be enforced.
# PassengerMaxInstancesPerApp 0
## PassengerPoolIdleTime
#
# Set the maximum number of seconds that your application instance
# may be idle. That is, if an application instance hasn't done anything
# after the given number of seconds, then it will be shutdown in order
# to conserve memory. Decreasing this value means that applications
# will have to be spawned more often. Since spawning is a relatively
# slow operation, some visitors may notice a small delay when they
# visit your website. However, it will also free up resources used by
# applications more quickly. The optimal value depends on the average
# time that a visitor spends on a single Rails/Rack web page. We
# recommend a value of 2 * x, where x is the average number of seconds
# that a visitor spends on a single web page. But your mileage may vary.
# PassengerPoolIdleTime 300
##
## The following options are Rails specific options. They may occur
## here in the global configuration or in your VirtualHost entry.
##
## RailsAutoDetect
#
# Set whether Phusion Passenger should automatically detect whether
# a virtual host's document root is a Ruby on Rails application.
# The default is on.
# Options: <on|off>
# RailsAutoDetect on
## RailsBaseURI
#
# Specify that the given URI is a Rails application. It is allowed to
# specify this option multiple times. Do this to deploy multiple
# Rails applications in different sub-URIs under the same virtual host.
# RailsBaseURI <uri>
## RailsAllowModRewrite
#
# Passenger will not override mod_rewrite rules if this option
# is enabled.
# Options: <on|off>
# RailsAllowModRewrite off
## RailsEnv
#
# Use this option to specify the default RAILS_ENV value. The default
# setting is production.
# RailsEnv production
## RailsSpawnMethod
#
# Internally, Phusion Passenger spawns multiple Ruby on Rails processes
# in order to handle requests. But there are multiple ways with which
# processes can be spawned, each having its own set of pros and cons.
# Supported spawn methods are:
# smart
# When this spawn method is used, Phusion Passenger will attempt
# to cache Ruby on Rails framework code and application code for
# a limited period of time.
#
# conservative
# This spawning method is similar to the one used in Mongrel Cluster.
# It does not perform any code caching at all.
# RailsSpawnMethod smart
## PassengerMaxRequests
#
# Restarts each Passenger process after n number of requests processed.
# PassengerMaxRequests 100
#!/bin/bash
wget "https://gist.github.com/raw/4196493/9466e20501f3127fcb151c6b222eaf90f35f8aec/functions.sh"
chmod a+x functions.sh
source functions.sh
db_password="garycricket99"
db_name="railsapp_production"
logfile="/root/log.txt"
RUBY_VERSION='1.9.3-p327'
RUBYGEMS_VERSION='1.8.24'
RAILS_VERSION='3.2.9'
PASSENGER_VERSION='3.0.17'
export logfile
echo "BootstrapScript Starting" >> $logfile
echo "********************" >> $logfile
system_update
echo "System Updated" >> $logfile
echo "" >> $logfile
postfix_install_loopback_only
echo "Configured: postfix_install_loopback_only" >> $logfile
echo "" >> $logfile
mysql_install "$DB_PASSWORD" && mysql_tune 40
echo "Installed: MySQL" >> $logfile
echo "" >> $logfile
mysql_create_database "$DB_PASSWORD" "$DB_NAME"
echo "Configured: MySQL" >> $logfile
echo "" >> $logfile
apache_install && apache_tune 40 && apache_virtualhost_from_rdns && a2enmod rewrite
echo "Installed: apache" >> $logfile
echo "" >> $logfile
goodstuff
echo "Installed: goodstuff" >> $logfile
echo "" >> $logfile
apt-get -y install build-essential
apt-get -y install libssl-dev
apt-get -y install libreadline5-dev
apt-get -y install zlib1g-dev
apt-get -y install libyaml-dev
apt-get -y install libxslt-dev
apt-get -y install git
apt-get -y install git-core
apt-get -y install memcached
apt-get -y install libcurl4-openssl-dev
apt-get -y install apache2-prefork-dev
apt-get -y install libapr1-dev
apt-get -y install libaprutil1-dev
apt-get -y install libreadline-dev
echo "Installed: various libraries" >> $logfile
echo "" >> $logfile
# Install Ruby
echo "Installing: Ruby"
echo "$RUBY_VERSION.tar.gz" >> $logfile
echo "$RUBY_VERSION" >> $logfile
echo "" >> $logfile
echo "Downloading: (from calling wget ftp://ftp.ruby-lang.org/pub/ruby/1.9/$RUBY_VERSION.tar.gz)" >> $logfile
echo "" >> $logfile
wget ftp://ftp.ruby-lang.org/pub/ruby/1.9/$RUBY_VERSION.tar.gz >> $logfile
echo "" >> $logfile
echo "tar output:" >> $logfile
tar xzf $RUBY_VERSION.tar.gz >> $logfile
rm $RUBY_VERSION.tar.gz
cd $RUBY_VERSION
echo "" >> $logfile
echo "Current Directory:" >> $logfile
pwd >> $logfile
echo "" >> $logfile
echo "Ruby configure output: (from calling ./configure --enable-pthread --enable-shared --disable-rpath --sysconfdir=/etc --prefix=/usr/local)" >> $logfile
echo "" >> $logfile
./configure --enable-pthread \
--enable-shared \
--disable-rpath \
--sysconfdir=/etc \
--prefix=/usr/local >> $logfile
echo "" >> $logfile
echo "Ruby make output: (from calling make)" >> $logfile
echo "" >> $logfile
make >> $logfile
echo "" >> $logfile
echo "Ruby make install output: (from calling make install)" >> $logfile
echo "" >> $logfile
make install >> $logfile
cd
rm -rf $RUBY_VERSION
echo "" >> $logfile
echo "Downloading Ruby Gems with wget http://production.cf.rubygems.org/rubygems/rubygems-$RUBYGEMS_VERSION.tgz" >> $logfile
echo "" >> $logfile
wget http://production.cf.rubygems.org/rubygems/rubygems-$RUBYGEMS_VERSION.tgz >> $logfile
echo "" >> $logfile
echo "tar output:" >> $logfile
tar xzvf rubygems-$RUBYGEMS_VERSION.tgz >> $logfile
rm rubygems-$RUBYGEMS_VERSION.tgz
echo "" >> $logfile
echo "Installing: RubyGems" >> $logfile
cd rubygems-$RUBYGEMS_VERSION
ruby setup.rb >> $logfile
cd
rm -rf rubygems-$RUBYGEMS_VERSION
echo "" >> $logfile
echo "gem update --system:" >> $logfile
gem update --system >> $logfile
gem install rails --version $RAILS_VERSION --no-ri --no-rdoc >> $logfile
gem install passenger --version $PASSENGER_VERSION --no-ri --no-rdoc >> $logfile
echo "Installed: rails, passenger gems" >> $logfile
echo "" >> $logfile
echo "Installing: passenger" >> $logfile
passenger-install-apache2-module --auto
wget https://gist.github.com/raw/4196493/712a4917bd48a16ed7484dbc5601b6127d70cdb6/apache2.conf >> $logfile
wget https://gist.github.com/raw/4196493/4949258c1bc6551e19021b950d84b80be7badd5d/passenger.conf >> $logfile
mv apache2.conf /etc/apache2/apache2.conf
mv passenger.conf /etc/apache2/passenger.conf
echo "" >> $logfile
echo "Configured: apache, passenger" >> $logfile
echo "" >> $logfile
echo "Deployment Setup:" >> $logfile
mkdir -p /var/www/apps/railsapp/releases
mkdir -p /var/www/apps/railsapp/shared/config
mkdir -p /var/www/apps/railsapp/shared/log
chown www-data:www-data -R /var/www/apps
echo "Setup: Deployment Directory" >> $logfile
touch /var/www/apps/railsapp/shared/config/database.yml
echo "production:
adapter: mysql2
encoding: utf8
reconnect: false
database: $DB_NAME
pool: 5
username: root
password: $DB_PASSWORD
host: localhost
socket: /var/run/mysqld/mysqld.sock" >> /var/www/apps/railsapp/shared/config/database.yml
echo "Configured: database.yml" >> $logfile
ssh -T -oStrictHostKeyChecking=no bitbucket.org
echo "Configured: bitbucket.org as known host" >> $logfile
mkdir -p ~/.ssh
ssh-keygen -N '' -f ~/.ssh/deploy-key -t rsa -q
echo "Generated: SSH key for deployment (you need to add ~/.ssh/deploy-key.pub to your Git repository's deploy keys)" >> $logfile
touch ~/.ssh/config
echo "Host bitbucket.org
IdentityFile ~/.ssh/deploy-key" >> ~/.ssh/config
echo "Configured: ~/.ssh/config (this ensures the above deploy key is used for bitbucket.org)" >> $logfile
touch ~/.ssh/authorized_keys
curl http://dl.dropbox.com/u/1292743/gaurish_ssh_key.pub >> ~/.ssh/authorized_keys
chmod 0700 ~/.ssh/
chmod 0644 ~/.ssh/authorized_keys
echo "Configured: ~/.ssh/authorized_keys" >> $logfile
restartServices
echo "********************" >> $logfile
echo "Rails Server Bootstrap Finished" >> $logfile
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment