Home Software Development Dockerize Your Rails App Today – Josh Software

Dockerize Your Rails App Today – Josh Software

by Zaki Ghassan
0 comments


Tired of Development Setup Headaches? Reclaim Your Coding Time with Docker!

As software developers, we pour our energy into crafting new features daily. But what about the hidden time sink before you even write a line of code: setting up your machine to run existing legacy applications or sharing your new rails application with other people to give it a look? It’s a universal pain point, especially when dealing with Rails applications that rely on very old versions of gems, libraries, and packages. An operating system upgrade can quickly turn into a nightmare of outdated dependencies, forcing you to spend days, or even longer, just to get your development environment ready. This “machine setup tax” can steal valuable time that you could be using more productively.

Imagine if getting your development environment up and running took just one or two commands, instead of endless Googling for forgotten dependencies. And it’s not just a dream; it’s the concrete solution that Docker makes possible. This powerful tool completely transforms how developers prepare their machines, saving countless hours and eliminating the frustration of dependency hell.

Ready to streamline your workflow and focus on what truly matters: building amazing software?

Today, in this blog, we’ll explore one of the most widely used solutions in major IT firms worldwide, i.e. Docker.

Getting Started: Dockerizing Your Rails App

Docker is a powerful tool designed to simplify software development and deployment by containerizing applications. Docker does this for you and resolves all your problems, it helps to create a container of all the dependencies and setups included, for successfully run an application in multiple machines.

Imagine writing a Rails application on your machine and ensuring it works seamlessly on another developer’s laptop, a staging server, or a production environment. With Docker, this consistency is achieved because the application runs in isolated environments called Docker Containers.

 A container is a lightweight, standalone, and executable package that includes everything needed to run a piece of software, such as the code, runtime, libraries, and dependencies.

Now, lets learn about some of the commands used in a Dockerfile to be coded.

1. Docker Basics:

Commands Description
FROM This is used to set the base image for the docker application.
It can be the base image for the programming language we use or the OS we need for the application to run.
Ex: FROM ruby:7.0.8 or FROM ubuntu:24.0
ENV It is used to set the Environment variables inside the docker file that can be passed as an args in any command or RUN statement to perform certain tasks. Ex: ENV PROJ_ENV=development
 RUN bundle exec rails db:migrate RAILS_ENV=${PROJ_ENV}
COPY It is used to copy the file from the local build context into the root directory of our image
RUN It executes any commands to create a new layer on top of the current image. It run during the container is getting started.
CMD The CMD instruction sets the command to be executed when running a container from an image.CMD doesn’t execute anything at build time, but specifies the intended command for the image
EXPOSE This used to set the port at which docker listens at the runtime.
WORKDIR This instruction is used to set the working directory for other instructions to run.

2. Initial Requirements:

  1. Install Docker Engine –  Ensure Docker Engine is installed in the local machine and to ensure that you can follow the given link Docker Engine Install
  2. Create a new rails project – ‘rails new personal_project’
  3. Add a Dockerfile – In project directory (/personal_project), create a new file named Dockerfile(with no extensions ).Follow Docker naming convention to ensure proper functionality.
  4. Configure the database.yml with correct db_username and db_password values, which allows the application to connect with the database.Use Environment variables to dynamically use the credentials at every place to avoid any kind of connection setup errors.

Bare-minimum requirement to dockerize a rails application:

a. Add a Dockerfile file inside our project

FROM ruby:3.2.2
#ENV is used to set any environment variables in our docker build
ENV INSTALL_PATH /app

RUN mkdir -p $INSTALL_PATH

#WORKDIR defines the working directory for the application else at 
#every place we need to explicitly need to define the path with /app/..
WORKDIR /app

#RUN is used to execute command during the build process is going on.
RUN apt-get update -qq && apt-get install -y \
build-essential \
libpq-dev \
nodejs \
yarn \
postgresql-client \
tzdata

RUN apt-get install -y redis

RUN gem install rails bundler

#copy is used to copy the file from the local build context into the root directory of our image
COPY Gemfile Gemfile.lock ./

RUN bundle install

COPY . .
#RUN is used to execute some process or task during container getting started
RUN bundle exec rails assets:precompile

#This sets the listening port for the application to run
EXPOSE 3000

#CMD is used to run some commands that needs to be executed after the containers has started.
CMD ["bundle", "exec", "sidekiq"]

CMD ["bash", "-c", "bin/rails db:migrate && rails server -b 0.0.0.0"]

You’re probably wondering, what are all these things like “build-essential”, “libpq-dev”, “node js”, “postgres-client”, “tzdata”....??

All these are essential depedencies required to smoothly run your application. Lets, learn about these in brief.

b. The Must-Have Dependencies You Need to Know …..

Build-essential -Itis used for the ruby code to compile, without this we will get compilation error during gem installation.

Libpq-dev – This is used when we are using postgreSQL as a database for our Rails application, The pg gem, which is the standard PostgreSQL adapter for Ruby,requires libpq-dev to compile and link against the PostgreSQL client library.

Nodejs & Yarn – Node.js is a JavaScript runtime environment. Rails is primarily is a ruby framework but, now a days web-applications uses Javascript for frontend-development. Even if we don’t have any forntend, we need node.js environment to compile the rails asset pipeline. And, Yarn is used as a node package manager.

Postgresql-client – This provides the postresSQL command-line client tool(like psql). These tools help in interacting with the database directly through the command-line.

Tzdata – This package contains time-zone. It is very crucial for such application where change of time and zone is important

Redis – This is the redis client server package which provides the redis server for us to support the background job processes by sidekiq.

c. Next step is to add a docker-compose.yml file inside our project :

services:
  app:
    build: .
    container_name: Personal Project_App_Dev
    environment:
      RAILS_ENV: development
      DATABASE_URL: postgresql://postgres:postgres@postgresdb:5432/Personal_Project_App_development
      REDIS_URL: redis://redisdb:6379/0
    volumes:
      - .:/app
      - ./bundle_cache:/bundle
    ports:
      - 3000:3000
    depends_on:
      - postgresdb
      - redisdb

  postgresdb:
    image: postgres:16
    container_name: postgresdb
    restart: on-failure:5
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: postgres
      POSTGRES_DB: Personal_Project_App_development
    ports:
      - 5432:5432
    volumes:
      - ./postgresdb_data:/var/lib/postgres/data
    
  redisdb:
    image: redis:6.2-alpine
    container_name: redisdb
    command: redis-server
    volumes:
      - ./redis_data:/data

  sidekiq:
    build: .
    volumes:
    - .:/app
    environment:
      REDIS_URL: redis://redisdb:6379/0
    depends_on:
      - redisdb
    command: bundle exec sidekiq

Few Final Steps:

  1. Step 1 :
    This will build the image without starting the container at a time.
    docker compose build
After running the above command it will look something like this happening in the terminal

2.Step 2 :
This command will start the container and runs the application to desired port given.
docker compose up

Image 1: when the services are getting started while running compose up

Image 2: when all services have started and our server is finally Up.

Woohoo! We totally Dockerized our Rails App! 😊

During the implementations I faced some errors which i believe i should share with you all, so that you stay aware while containerising your rails application….!!!

Troubleshooting Errors : Tips and Tricks

a. unable to get image ‘personal project app-app’: permission denied while trying to connect to the docker daemon socket at

Check the permissions of the listed files using command –> ‘ls -all’ or ‘ls -la’
Used the below command to change the Read, Write and execute permission of docker.sock file for my root user.

– sudo chmod 600 docker.sock

– sudo chmod 660 docker.sock

– sudo chmod 744 docker.sock

– sudo chmod 644 docker.sock

This changed the permission for directory to resolve this error.

b. psql: error: connection to server on socket “/var/run/postgresql/.s.PGSQL.5432” failed: FATAL: role “postgres” does not exist

This errors occured when the credential for username in your database.yml file in rails application mismatches with the one given in the docker-compose.yml database service.

  1. Try to keep the database user name same as the username given in the database.yml file to avoid this issue.

c. ActiveRecord::ConnectionNotEstablished (connection to server at “127.0.0.1”, port 5432 failed: Connection refused
– connection to server at “127.0.0.1”, port 5432 failed: connection refused is the server running on that host and accepting tcp/ip connections?

These two errors can occur when Docker standard naming rule for DATABASE_URL is not followed.

DATABASE_URL: postgresql://postgres:postgres@postgresdb:5432/Personal_Project_App_development

Format Should be : postgresql://POSTGRES_USER:POSTGRES_PASSWORD@SERVICE_NAME:PORT_NUMBER/DB_NAME

d. ActiveRecord::NoDatabaseError (We could not find your database: Lending_Money_App_dev_development. Which can be found in the database configuration file located at config/database.yml.

This kind of NoDatabaseError can occur when the POSTGRES_DB in docker-compose.yml doesn’t matches with any existing database in database.yml

development:
<<: *default
database: Personal_Project_App_development

postgresql://postgres:postgres@postgresdb:5432/Personal_Project_App_development

e. ActiveRecord::PendingMigrationError (
Migrations are pending. To resolve this issue, run: 
bin/rails db:migrate RAILS_ENV=development ):

This error will occur when you database is now correctly setup and database is up, now we need to do one more addition in the Dockerfile to up the migration files and to create schema for the same.

CMD ["bundle", "exec", "sidekiq"]
CMD ["bash", "-c", "bin/rails db:migrate && rails server -b 0.0.0.0"]

f)  ActiveRecord::ConnectionNotEstablished: connection to server at “::1”, port 5432 failed: Connection refused
Is the server running on that host and accepting TCP/IP connections?
connection to server at “127.0.0.1”, port 5432 failed: Connection refused
Is the server running on that host and accepting TCP/IP connections?

Error: 

Cause: mismatch of the IP address set in docker-compose.yml and our configuration set in sidekiq.rb initializers.
Changes required:

Here redisdb is the service IP that we set in the docker-compose.yml

🚀 Why Dockerize Your Rails App? A Quick Summary

Docker eliminates the classic “It works on my machine!” issue by providing consistent, reproducible environments across development, staging, and production. Compared to traditional VMs, Docker is faster, more portable, and resource-efficient.

🔧 Key Benefits:
  • Consistency: Run your app the same way everywhere.
  • Portability: Move containers easily across machines and clouds.
  • Scalability: Scale services smoothly with tools like Docker Compose.
  • Speed: Containers start fast, boosting your workflow efficiency.

Dockerizing your Rails app simplifies setup, reduces environment-related bugs, and makes scaling straightforward. It lets your team focus on building features—not fixing setup issues.

Start dockerizing today and boost your app’s portability, reliability, and development speed! 🚢

Useful Links and References:


You may also like

Welcome to Technova Pulse – Your Gateway to Technology & Innovation

At Technova Pulse, we dive into the fast-moving world of technology and innovation.

Subscribe

Subscribe my Newsletter for new blog posts, tips & new photos. Let's stay updated!

© 2010-2025 Mahasun.site. All rights reserved.