Setup rails project using Docker
Install Docker
https://docs.docker.com/engine/installation/mac/
Create rails app
mkdir assignment rvm install "ruby-3.1.0" rvm use 3.1.0 cd assignment gem install rails -v 7.0.4 rails new . -d postgresql
Add docker files
touch Dockerfile touch docker-compose.yml
Dockerfile
# Gets the docker image of ruby 3.1.0 and lets us build on top of that FROM ruby:3.1.0 # Install rails dependencies RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs libsqlite3-dev # create a folder in the docker container and go into that folder ENV INSTALL_PATH /assignment RUN mkdir -p $INSTALL_PATH WORKDIR $INSTALL_PATH # Copy the Gemfile and Gemfile.lock from app root directory into the /myapp/ folder in the docker container COPY Gemfile $INSTALL_PATH/Gemfile COPY Gemfile.lock $INSTALL_PATH/Gemfile.lock # Run bundle install to install gems inside the gemfile RUN gem install bundler RUN bundle install # Copy rails app to Docker COPY . $INSTALL_PATH
docker-compose.yml
api
, db
you can using any name, image
(s) you can find at https://hub.docker.com/search
api
is your app name
version: '3.1' services: db: image: 'postgres:14.0' volumes: - 'db:/var/lib/postgresql/data' env_file: - '.env' environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: password api: platform: linux/x86_64 # Fix nokogiri error on Mac M1 depends_on: - 'db' build: . ports: - '3000:3000' volumes: - '.:/assignment' env_file: - '.env' command: bundle exec rails s -p 3000 -b '0.0.0.0' volumes: db:
Update config/database.yml
default: &default adapter: postgresql encoding: unicode # For details on connection pooling, see Rails configuration guide # https://guides.rubyonrails.org/configuring.html#database-pooling host: db username: <%= Rails.application.credentials.database[:username] %> password: <%= Rails.application.credentials.database[:password] %> pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
Set credentials
database: username: postgres password: password
Start docker
docker-compose build docker-compose up
Create database
api
is your app name (docker-compose.yml)
docker-compose run api bundle exec rails db:create
Enjoy
http://localhost:3000
Possible errors
# Error: cannot load such file -- nokogiri gem uninstall nokogiri bundle config set force_ruby_platform true bundle install