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

1
$ brew install awsebcli

Preparation

1
2
3
4
5
6
7
8
9
# Initialize
$ eb init
# Set DATABASE_URL to env variables
$ eb setenv DATABASE_URL=postgres://ID:[email protected]: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:

1
2
3
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:

1
2
3
4
5
6
7
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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

1
2
3
4
5
6
7
8
9
10
# Put Souce code to server
$ eb deploy
# Create Database
$ eb ssh
$ cd /var/app/current
$ RAILS_ENV=production DATABASE_URL=postgres://ID:[email protected]:PORT/DB_NAME rake db:create
# Deployment
$ eb deploy

Special Thanks