Deploy Rails 5 App to ElasticBeanstalk


“Elasticbeanstalk” supports quickly deploying and managing applications in the AWS Cloud without worrying about the infrastructure that runs those applications.

This article explains “How to deploy Rails App to Elasticbeanstalk”.


🎳 Create IAM

  • 1) Go to “IAM Console
  • 2) Goto “Users” > “Create New Users”
  • 3) Create user “elasticbean-deploy” and get Access Key ID & Secret Access Key
  • 4) Setup attachment policy

🚜 Create SSH Key

  • 1) Go to “EC2 Console
  • 2) Goto “Key Pairs” > “Create Key Pair”
  • 3) Get SSH Key(“xxx.pem” file)

🍣 Create New Environement

  • 1) Go to “Elasticbeanstalk Console
  • 2) Goto “Action” > “Create New Environement” > “Web server environment”
  • 3) Set configuration and create RDS instance

🎉 Istallation EB CLI

$ brew install awsebcli

🐯 Preparation

# Initialize
$ eb init

# Set DATABASE_URL to env variables
$ eb setenv DATABASE_URL=postgres://ID:PASSWORD@HOST:PORT/DB_NAME

# Set SECRET_KEY_BASE to env variables
$ bundle exec rake secret #=> xxxx
$ eb setenv SECRET_KEY_BASE=xxxx

🐰 Set Custom Configuration

Setup Tizezone

Add the following .ebextensions/00-set-timezone.config to your project:

commands:
set_time_zone:
command: ln -f -s /usr/share/zoneinfo/Japan /etc/localtime

Setup Swap Space

Add the following .ebextensions/01-set-swap-space.config to your project if you want to use crontab:

commands:
000_dd:
command: dd if=/dev/zero of=/swapfile bs=1M count=3072
001_mkswap:
command: mkswap /swapfile
002_swapon:
command: swapon /swapfile

Setup Crontab

Add the following .ebextensions/02-set-crontab.config to your project if you want to use crontab:

files:
"/tmp/cron_jobs" :
mode: "000777"
content: |
0 1 * * * /var/script/something.sh > /dev/null 2>&1
encoding: plain
container_commands:
01_delete_cron_jobs:
command: "crontab -r || exit 0"
02_add_cron_jobs:
command: "crontab /tmp/cron_jobs"
leader_only: true
option_settings:
- option_name: RAILS_ENV
value: production
- option_name: RACK_ENV
value: production

🏈 Deployment

# Put Souce code to server
$ eb deploy

# Create Database
$ eb ssh
$ cd /var/app/current
$ RAILS_ENV=production DATABASE_URL=postgres://ID:PASSWORD@HOST:PORT/DB_NAME rake db:create

# Deployment
$ eb deploy

🍄 Special Thanks

🖥 Recommended VPS Service

VULTR provides high performance cloud compute environment for you. Vultr has 15 data-centers strategically placed around the globe, you can use a VPS with 512 MB memory for just $ 2.5 / month ($ 0.004 / hour). In addition, Vultr is up to 4 times faster than the competition, so please check it => Check Benchmark Results!!