How to use puma in production mode by set production environment? - sinatra

I made a little Sinatra app. In my Gemfile add gem 'puma' in the production group
group :production do
gem 'puma'
gem 'dm-postgres-adapter'
end
And I set production mode in config.ru
set :environment, :production
But after I run backup, the default webrick web server run instead.
How can I solve this?

Just use puma :)
$ puma config.ru
You can run your Sinatra application with Puma from the command line like this:
$ ruby app.rb -s Puma
Or you can configure your application to always use Puma:
require 'sinatra'
configure { set :server, :puma }
You can pass it as an option to rackup:
$ rackup -s Puma
Alternatively, you can modify your config.ru to choose Puma by default, by adding the following as the first line:
#\ -s puma
More documentation on puma.

Related

PG: ERROR: relation "admin_users" does not exist

I am currently getting the following error when I run heroku logs, after trying to login to the admin/login part of my production URL:
ActiveRecord::StatementInvalid (PG::UndefinedTable: ERROR: relation “admin_users" does not exist
I have tried followed this thread :https://github.com/gregbell/active_admin/issues/753, i.e. specifically the following suggested steps (suggested to be performed on a "new install" which I am unclear what that means!)
rails g active_admin:devise
rails g active_admin:install
(If install fails because of #2414, remove duplicate ActiveAdmin.routes(self) from routes file, then run rails g active_admin:assets)
remove add_devise_to_admin_users migration file
rake db:migrate
I have done the above steps w/o adhering to the "new install" portion but am still getting the same error.
Here is the copy of my database.yml file:
# SQLite version 3.x
# gem install sqlite3
#
# Ensure the SQLite 3 gem is defined in your Gemfile
# gem 'sqlite3'
development:
adapter: postgresql
database: myapp_development
pool: 5
timeout: 5000
password:
# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
adapter: postgresql
encoding: unicode
database: myapp_test
pool: 5
timeout: 5000
password:
production:
adapter: postgresql
database: myapp_production
username:
password:
pool: 5
timeout: 5000
Here is the copy of my Gemfile
source 'https://rubygems.org'
ruby "2.1.1"
gem 'rails', '4.0.4'
gem 'sass-rails', '~> 4.0.2'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.0.0'
gem 'jquery-rails'
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 1.2'
group :doc do
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', require: false
end
gem 'activeadmin', github: 'gregbell/active_admin'
group :production do
gem 'pg'
gem 'rails_12factor'
end
After you push your code to Heroku via git, switch to your project root and run:
$ heroku run rake db:migrate
This will run rake db:migrate on your production server.

What is a faster alternative to Python's http.server (or SimpleHTTPServer)?

Python's http.server (or SimpleHTTPServer for Python 2) is a great way of serve the contents of the current directory from the command line:
python -m http.server
However, as far as web servers go, it's very slooooow...
It behaves as though it's single threaded, and occasionally causes timeout errors when loading JavaScript AMD modules using RequireJS. It can take five to ten seconds to load a simple page with no images.
What's a faster alternative that is just as convenient?
http-server for node.js is very convenient, and is a lot faster than Python's SimpleHTTPServer. This is primarily because it uses asynchronous IO for concurrent handling of requests, instead of serialising requests.
Installation
Install node.js if you haven't already. Then use the node package manager (npm) to install the package, using the -g option to install globally. If you're on Windows you'll need a prompt with administrator permissions, and on Linux/OSX you'll want to sudo the command:
npm install http-server -g
This will download any required dependencies and install http-server.
Use
Now, from any directory, you can type:
http-server [path] [options]
Path is optional, defaulting to ./public if it exists, otherwise ./.
Options are [defaults]:
-p The port number to listen on [8080]
-a The host address to bind to [localhost]
-i Display directory index pages [True]
-s or --silent Silent mode won't log to the console
-h or --help Displays help message and exits
So to serve the current directory on port 8000, type:
http-server -p 8000
I recommend: Twisted (http://twistedmatrix.com)
an event-driven networking engine written in Python and licensed under the open source MIT license.
It's cross-platform and was preinstalled on OS X 10.5 to 10.12. Amongst other things you can start up a simple web server in the current directory with:
twistd -no web --path=.
Details
Explanation of Options (see twistd --help for more):
-n, --nodaemon don't daemonize, don't use default umask of 0077
-o, --no_save do not save state on shutdown
"web" is a Command that runs a simple web server on top of the Twisted async engine. It also accepts command line options (after the "web" command - see twistd web --help for more):
--path= <path> is either a specific file or a directory to be
set as the root of the web server. Use this if you
have a directory full of HTML, cgi, php3, epy, or rpy
files or any other files that you want to be served up
raw.
There are also a bunch of other commands such as:
conch A Conch SSH service.
dns A domain name server.
ftp An FTP server.
inetd An inetd(8) replacement.
mail An email service
... etc
Installation
Ubuntu
sudo apt-get install python-twisted-web (or python-twisted for the full engine)
Mac OS-X (comes preinstalled on 10.5 - 10.12, or is available in MacPorts and through Pip)
sudo port install py-twisted
Windows
installer available for download at http://twistedmatrix.com/
HTTPS
Twisted can also utilise security certificates to encrypt the connection. Use this with your existing --path and --port (for plain HTTP) options.
twistd -no web -c cert.pem -k privkey.pem --https=4433
go 1.0 includes a http server & util for serving files with a few lines of code.
package main
import (
"fmt"; "log"; "net/http"
)
func main() {
fmt.Println("Serving files in the current directory on port 8080")
http.Handle("/", http.FileServer(http.Dir(".")))
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
Run this source using go run myserver.go or to build an executable go build myserver.go
Try webfs, it's tiny and doesn't depend on having a platform like node.js or python installed.
If you use Mercurial, you can use the built in HTTP server. In the folder you wish to serve up:
hg serve
From the docs:
export the repository via HTTP
Start a local HTTP repository browser and pull server.
By default, the server logs accesses to stdout and errors to
stderr. Use the "-A" and "-E" options to log to files.
options:
-A --accesslog name of access log file to write to
-d --daemon run server in background
--daemon-pipefds used internally by daemon mode
-E --errorlog name of error log file to write to
-p --port port to listen on (default: 8000)
-a --address address to listen on (default: all interfaces)
--prefix prefix path to serve from (default: server root)
-n --name name to show in web pages (default: working dir)
--webdir-conf name of the webdir config file (serve more than one repo)
--pid-file name of file to write process ID to
--stdio for remote clients
-t --templates web templates to use
--style template style to use
-6 --ipv6 use IPv6 in addition to IPv4
--certificate SSL certificate file
use "hg -v help serve" to show global options
Here's another. It's a Chrome Extension
Once installed you can run it by creating a new tab in Chrome and clicking the apps button near the top left
It has a simple gui. Click choose folder, then click the http://127.0.0.1:8887 link
https://www.youtube.com/watch?v=AK6swHiPtew
I found python -m http.server unreliable—some responses would take seconds.
Now I use a server called Ran https://github.com/m3ng9i/ran
Ran: a simple static web server written in Go
Also consider devd a small webserver written in go. Binaries for many platforms are available here.
devd -ol path/to/files/to/serve
It's small, fast, and provides some interesting optional features like live-reloading when your files change.
If you have PHP installed you could use the builtin server.
php -S 0:8080
give polpetta a try ...
npm install -g polpetta
then you can
polpetta ~/folder
and you are ready to go :-)
Using Servez as a server
Download Servez
Install It, Run it
Choose the folder to serve
Pick "Start"
Go to http://localhost:8080 or pick "Launch Browser"
Note: I threw this together because Web Server for Chrome is going away since Chrome is removing support for apps and because I support art students who have zero experience with the command line
Yet another node based simple command line server
https://github.com/greggman/servez-cli
Written partly in response to http-server having issues, particularly on windows.
installation
Install node.js then
npm install -g servez
usage
servez [options] [path]
With no path it serves the current folder.
By default it serves index.html for folder paths if it exists. It serves a directory listing for folders otherwise. It also serves CORS headers. You can optionally turn on basic authentication with --username=somename --password=somepass and you can serve https.
I like live-server. It is fast and has a nice live reload feature, which is very convenient during developpement.
Usage is very simple:
cd ~/Sites/
live-server
By default it creates a server with IP 127.0.0.1 and port 8080.
http://127.0.0.1:8080/
If port 8080 is not free, it uses another port:
http://127.0.0.1:52749/
http://127.0.0.1:52858/
If you need to see the web server on other machines in your local network, you can check what is your IP and use:
live-server --host=192.168.1.121
And here is a script that automatically grab the IP address of the default interface. It works on macOS only.
If you put it in .bash_profile, the live-server command will automatically launch the server with the correct IP.
# **
# Get IP address of default interface
# *
function getIPofDefaultInterface()
{
local __resultvar=$1
# Get default route interface
if=$(route -n get 0.0.0.0 2>/dev/null | awk '/interface: / {print $2}')
if [ -n "$if" ]; then
# Get IP of the default route interface
local __IP=$( ipconfig getifaddr $if )
eval $__resultvar="'$__IP'"
else
# Echo "No default route found"
eval $__resultvar="'0.0.0.0'"
fi
}
alias getIP='getIPofDefaultInterface IP; echo $IP'
# **
# live-server
# https://www.npmjs.com/package/live-server
# *
alias live-server='getIPofDefaultInterface IP && live-server --host=$IP'
I've been using filebrowser for the past couple of years and it is the best alternative I have found.
Features I love about it:
Cross-platform: It supports Linux, MacOs and Windows (+). It also supports docker (+).
Downloading stuff is a breeze. It can automatically convert a folder into zip, tar.gz and etc. for transferring folders.
You can file or folder access to every use.

How to start a play2 application on a remote machine using capistrano

I'm trying to deploy a play2 application with capistrano, but I can't figure out how to (re)start the play2 application after a successful deployment. Just triggering 'play start' will cause the process to be hanging waiting for me to press ctrl+D
I've created a start script in the play app root folder
#!/bin/bash
nohup bash -c "/var/lib/play2/play start &>> /tmp/myapp.log 2>&1" &> /dev/null &
It works great when I run this on the server. When I try to call this from my local machine over ssh it also works. But when I am using capistrano, it doesn't seem to do anything. My capistrano config looks like this:
namespace :deploy do
task :restart do
stop
sleep 1
start
end
task :start do
run "cd #{current_release}/trip-api && ./start.sh"
end
task :stop do
run "cd #{current_release}/trip-api && ./stop.sh"
end
end
What's the best way to start a play2 application on a remote machine? How to get it working with capistrano?
Have a look at play documentation on deploying your application on production
The recommended way is to package your app with
play clean compile stage
And then run it with
$ target/start
To stop it, have a look at the docs:
The server’s process id is displayed at bootstrap and written to the
RUNNING_PID file. To kill a running Play server, it is enough to send
a SIGTERM to the process to properly shutdown the application.
In this quickstart for Openshift, it shows another way to start play as a service and how to stop it.
basically you do something like this to start:
APP_COMMAND="${OPENSHIFT_REPO_DIR}target/start $PLAY_PARAMS "\
"-Dhttp.port=${OPENSHIFT_INTERNAL_PORT} "\
"-Dhttp.address=${OPENSHIFT_INTERNAL_IP} "\
"-Dconfig.resource=openshift.conf"
echo $APP_COMMAND &>> $LOG_FILE
nohup bash -c "${APP_COMMAND} &>> ${LOG_FILE} 2>&1" &> /dev/null &
and to stop it
pid=`cat RUNNING_PID`
echo "Stopping play application" >> $LOG_FILE
kill -SIGTERM $pid
There are few fresh topics about running application available at Google Groups:
Start an application as a background process
When deployed on Ubuntu 10.04 cant detach from console
It's good idea to follow or join them
I would suggest using runit. We are currently running a bunch of services in production and it works great.
It only involves creating a simple shell script named run, pointing runit to its containing directory and then start it. Services should not daemonize by themselves and runit controls pid files, etc.
There is a command ( sv ) to start, stop and query services. ( sv start|stop|status|restart yourapp ).
A cursory google search got me this http://rubygems.org/gems/capistrano-runit though I do not use capistrano at all so I can't vouch for it's usefulness.
http://smarden.org/runit/
The faq is the best place to start: http://smarden.org/runit/faq.html
In debian you just apt-get install runit and are good to go.
update-service --add /your/service/dir/ will register the service with runit.
On deployment we stop services, change binaries and start services; it is really simple.

Capistrano doesn't use sudo despite :use_sudo, true

I'm brand new to Capistrano, working with an existing server that was previously using chef to run deployments.
I have set :use_sudo, true in my deploy.rb, and yet "cap deploy:check" claims "You do not have permissions to write to '/srv/app/'"
My deployment user is correctly configured to sudo without a password prompt. If I manually run "sudo test -w /srv/app" on the server, it succeeds.
Why isn't Capistrano using sudo?
The command fails because the directory does not exist. You should first run cap deploy:setup After that cap deploy:check succeeds.

Problem creating more than one Rails app using MongoDB

I properly installed MongoDB and got it running on my OSX. The first app I created using MongDB and Rails3 was titled 'todo". Per the
instructions on railscasts, I created a file (config/initilializers/
mongo.rb) and added this line:
MongoMapper.database = "todo-
#{Rails.env}"
Presumably, this created the files that appeared in my /data/db/ file entitled "todo-
development". When I used the generate command in Rails to create the
models, the data was correctly stored in this file. All good, up to this
point.
The problem now is that I can't seem to create NEW files in the /data/db file when
I create new apps with Rails. (I think) the data file should be
created from the initializer file (ex:
MongoMapper.database = "newproject-
#{Rails.env}"
that I add to each new app. But it
is not.
Here's my gemfIle (that worked with my first app!:
require 'rubygems'
gem 'mongo', '1.0'
source 'http://gemcutter.org'
gem 'rails', '3.0.0.beta4'
gem "mongo_mapper"
gem 'bson_ext', '1.0'
Any help would be appreciated!
Finally figured this out with the help Kristian Mandrup in a Google Group. Thanks Kristian. I needed to uncomment the config.generator in my application.rb file and change orm from active_record to mongo_mapper. (btw, the error I was getting before when trying to run the generator was ""No value provided for required options '--orm'.")
More here: http://www.viget.com/extend/rails-3-generators-hooks/
For what it's worth, I'm including the entire process that I needed to take in order to get MongoDB and Rails 3 working together properly.
Install MongoDB on OSX
$ sudo port install mongodb
Create a data directory:
$ sudo mkdir -p /data/db
Set permissions for data directory:
$sudo chown `id -u` /data/db
Start Mongo in Terminal:
$ mongod run
Visit local host to verify that MongoDB is running:
http://localhost:28017/
Create new project with Rails 3:
$ rails new projectname --skip-activerecord
Add this to the gemfile:
require 'rubygems'
gem 'mongo', '1.0'
source 'http://gemcutter.org'
gem 'rails', '3.0.0.beta4'
gem "mongo_mapper"
gem 'bson_ext', '1.0'
uncomment out (and modify) these lines in application.rb file:
config.generators do |g|
g.orm :mongo_mapper
end
Create config/initializer/mongo.rb file:
MongoMapper.connection = Mongo::Connection.new('localhost', 27017)
MongoMapper.database = "projectname-#{Rails.env}"
Create a lib/tasks/mongo.rake file:
namespace :db do
namespace :test do
task :prepare do # Stub out for MongoDB
end
end
end
Install gems:
$bundle install
Create first model:
$rails generate scaffold Product name:string --skip-migration
Create models/product.rb file:
class Product
include MongoMapper::Document
key :name, string
end