DEV Community

Aimeri Baddouh
Aimeri Baddouh

Posted on

Quickly generating a Dockerized Rails development environment

The motivator for this small quality of life "hack" came from the frustration of managing all possible variables of creating a new Rails project. Every time I wanted to test a new tutorial or course, I had to worry about the already existing versions of Rails, Ruby, and npm packages.The obvious solution for my problem is to containerize my test applications.
This is just a quick script to help bootstrap this process by spinning up a temporary docker container, generating a new Rails application, and writing the Dockerfile and docker-compose.yaml files to the newly created application folder.
Append this function to the end of your ~/.zshrc or ~/.bashrc

generate_rails_project() {
    docker run -it --rm -v "$PWD":/"$1" -w /"$1" ruby:latest /bin/bash -c "curl\ 
-sL https://deb.nodesource.com/setup_12.x | bash && apt-get install -y nodejs &&\ 
npm i -g yarn && gem install rails && rails new $1 $2"
    echo "FROM ruby:latest
\n
\n
RUN mkdir /"$1"
WORKDIR /"$1"
\n
RUN apt-get update
RUN curl -sL https://deb.nodesource.com/setup_12.x | bash -
RUN apt-get install -y nodejs
RUN npm i -g yarn
RUN gem install bundler
\n
\n
COPY Gemfile /"$1"/Gemfile
COPY Gemfile.lock /"$1"/Gemfile.lock
RUN bundle install
COPY . /"$1"
" > "$1"/Dockerfile
    echo "version: '3.6'
services:
    $1:
        build:
            context: .
        volumes:
            - .:/"$1"
        ports:
            - '3000:3000'
        command: bash -c \"rm -f tmp/pids/server.pid && bundle exec rails s -p 3000\
-b '0.0.0.0'\"" > "$1"/docker-compose.yaml
}

You might want to alias this function to something that is quicker to use. I'll go with nrp for new rails project:

# I'm adding this at the very end of my ~/.zshrc, after the new function
alias nrp=generate_rails_project

to make changes available immediately, run:

source ~/.zshrc

or if you're not running the ZSH shell:

source ~/.bashrc

To use this new alias:

nrp my_project
cd my_project
docker-compose up --build

in a new tab you can start your IDE and issue commands to the docker container like so:

code .
docker-compose run my_project rails generate controller Welcome index

You can also start a new Rails API application as such:

nrp my_project --api

Things to note:

  • This script will use the latest version of Ruby and Rails available
  • You need docker and docker compose installed for this setup to work
  • This setup should work as is on most linux distros and on OSX, but for Windows 10 you will probably need to configure this in the WSL or git bash
  • This script should not be used for generating production applications. The intent of this script is to quickly bootstrap new projects for test environments.

Top comments (0)