Dockerizing a Rails 6 App: A Comprehensive Guide
Introduction
Dockerization has become a crucial aspect of modern web development, ensuring seamless deployment and scalability. In this guide, we’ll walk you through the steps of dockerizing a Rails 6 application using Docker Compose.
Prerequisites
Before we begin, make sure you’re familiar with Docker and have it installed. If not, visit my blog post on Containerization and Docker for detailed information and installation instructions.
Dockerizing Your Rails 6 App
Follow these steps to dockerize your Rails 6 application using Docker Compose:
Step 1: Navigate to the Project Directory
cd your_project_directory
Step 2: Create an Entry Point Script
Create a file named docker-entrypoint.sh
and add the following content:
#!/bin/bash
set -e
bundle check || bundle install --binstubs="$BUNDLE_BIN"
echo "command executing $@"
exec "$@"
Step 3: Create a Dockerfile
Create a Dockerfile
with the following content:
FROM ruby:2.6.3
RUN apt-get update -qq && apt-get install -y build-essential
RUN apt-get install -y libpq-dev
RUN apt-get install -y libxml2-dev libxslt1-dev
RUN apt-get install -y nodejs
RUN mkdir /app
WORKDIR /app
ADD . /app
EXPOSE 3000
COPY ./docker-entrypoint.sh /
RUN chmod +x /docker-entrypoint.sh
ENTRYPOINT ["/docker-entrypoint.sh"]
ENV BUNDLE_PATH=/bundle \
BUNDLE_BIN=/bundle/bin \
GEM_HOME=/bundle
ENV PATH="${BUNDLE_BIN}:${PATH}"
RUN gem install bundler
Step 4: Create a docker-compose.yml File
Create a docker-compose.yml
file with the following content:
version: '3'
services:
postgres:
image: postgres:9.6
ports:
- '5432:5432'
volumes:
- postgres:/var/lib/postgresql/data
web:
build: .
command: puma
volumes:
- bundle:/bundle
- .:/app
ports:
- '3000:3000'
links:
- postgres
volumes:
bundle:
postgres:
Step 5: Update database.yml
Update your database.yml
to reflect the following changes:
development:
<<: *default
host: postgres # service name in docker-compose.yml
username: postgres # has to be this way
password:
database: my_app_development
Step 6: Rebuild the Docker Image
Whenever you modify the Dockerfile
, rebuild the image using:
docker-compose build
Step 7: Initialize the Database
For the first-time setup, create and seed the database:
docker-compose run web rails db:create && rails db:migrate && rails db:seed
Alternatively, you can run each command separately:
docker-compose run web rails db:create
docker-compose run web rails db:migrate
docker-compose run web rails db:seed
Now, you can access your application via localhost:3000
in your web browser.
Conclusion
By following these steps, you have successfully dockerized your existing Rails 5/6 projects using Docker Compose. Dockerization facilitates efficient deployment and management, enhancing your development workflow.