Multiple Rails (and non Rails) Shell Environment Without Headache

Karuna Murti
FiNC Tech Blog
Published in
2 min readDec 15, 2017

On this post I’m going to show you how to manage multiple environments in micro services development using Ruby on Rails easily.

At the most basic Ruby on Rails development we only develop using one application. Therefore it’s easy, we can just run on a single port, by which 3000 is the most common.

Then we start using more than 1 application. At first we can remember the main application should run on port 3000, the second application should run on port 3001, the third application should run on port 3002

You got the idea, at the beginning it's easy to remember. Then as the number of applications start to grow, you need to run several applications simultaneously on your development machine.

Then one day you start to get confused, what port this application should run on? Then you start to write notes to remember which port this application should run on.

Sure we can setup docker and other things, but IMHO it's too much of unnecessary engineering.

We can do it better. Let's use something to set environment variable directly when you enter a directory.

Installation

Let's install direnvfrom https://direnv.net . Your favorite operating system may have that in the package management system.

Example for Mac:

brew install direnv

After that add command to your shell script initializer so it’s called automatically when you open a new shell. This is the example for bash

eval "$(direnv hook bash)"to ~/.bashrc

Using

After you install and set your shell to use the direnv, let's configure direnv for a Rails application.

cd project1

Add .envrcfile in the folder with the content like this:

export $PORT=3000

When you go to the folder, direnv will complain because it’s not been allowed:

.envrc is not allowed

It’s a good defense mechanism, just in case there’s an application downloaded from public places like github and you don’t want unknown environment variables loaded automatically. You can enable by using command:

direnv allow .

You can now start running rails without remembering the port for that directory:

rails s -p $PORT

It’s very handy for running a lot of Ruby on Rails applications, or for running different applications with a lot of different environment variables. For example you can setup different AWS key for different applications, or for running multiple background workers.

Bonus:

You can add function in your shell script to make it easier without typing. Example for

~/.bashrc

rails_s () { 
rails s -p $PORT
}

Now every time can just go to pplication directory and run rails_s

--

--

Karuna Murti
FiNC Tech Blog

Senior polyglot programmer and sysadmin with management experience. Ruby, Rust, Java, Python, JS, C ++