Docker: a Rails application run in Docker
Setup Rails 7 app
rails new rails_7_with_docker --database=postgresql
cd rails_7_with_docker
rails db:create
rails server
Make docker file: Dockerfile
FROM ruby:3.0-bullseye as base
RUN apt-get update -qq && apt-get install -y build-essential apt-utils libpq-dev nodejs
WORKDIR /docker/app
RUN gem install bundler
COPY Gemfile* ./
RUN bundle install
ADD . /docker/app
ARG DEFAULT_PORT 3000
EXPOSE ${DEFAULT_PORT}
CMD [ "bundle","exec", "puma", "config.ru"] # CMD ["rails","server"] # you can also write like this.
Build image:
docker build . -t rails_docker:1 # t flag use to give image name and version number.
Run a container:
docker run -p 3000:3000 rails_docker:1
Crete a network:
docker network create rails_postgres # crete a network
Run postgres in the network:
docker run --network rails_postgres --name postgres -d -e POSTGRES_PASSWORD=postgres postgres:latest
Change database.yml:
development:
adapter: postgresql
encoding: unicode
host: postgres
username: postgres
password: postgres
pool: 5
database: test_db
Build again:
docker build . -t rails_docker:2
Rails application Run in detash mood:
docker run -d --network rails_postgres --name rails_7 -p 3000:3000 rails_docker:2
Create Database:
docker exec rails_7 rails db:create # create a database inside your docker project
Also you can use docker-composer:
version: '3.7'
services:
db:
image: 'postgres:latest'
volumes:
- postgres:/var/lib/postgresql/data
environment:
POSTGRES_PASSWORD: postgres
# env_file:
# - ./env/postgres.env # you can also define env variables like this.
rails:
build: ./
ports:
- '3000:3000'
volumes:
- .:/docker/app # add our local code to dockerfile
depends_on:
- db # add all dependant container
volumes:
postgres: # named volume
docker composer up
docker-compose up
Welcome to Docker in Rails