Running Ruby On Rails With Postgres In A Docker Container
Ruby On Rails With PostgreSQL and Docker
- You are running MacOS, a Linux distro, or Windows with WSL (Windows Subsystems For Linux)
- Know how to use the Terminal in before mentioned Operating Systems
- You have Visual Studio Code, and have it set up to open from a terminal command with "code ."
- You are somewhat familiar with Ruby and Rails
Necessary Installs
Docker
Install Docker according to the operating system you will be using.https://docs.docker.com/engine/install/
Docker-Compose
Install docs can be found here. https://docker-docs.netlify.app/compose/install/
Project Setup
Create Project Directory
In whatever directory you keep your projects, create a directroy for your project You can copy what's below, or use your own name.
$ mkdir rails_postgres_docker_demo
I'm using rails_postgres_docker_demo for this tutorial. Then cd into the directory you just made.
$ cd rails_postgres_docker_demo
Create Necessary Initial Files
$ touch Dockerfile docker-compose.yml Gemfile
Open Visual Studio Code by tying "code ."
$ code .
Once Visual Studio Code has opened hit ⌘+p and type part of the file name you want to open and it will appear in the file results
In your file named Dockerfile paste the following:
Create docker-compose.yml
Into your Gemfile paste the following
source 'https://rubygems.org'gem 'rails', '~> 7.0.2', '>= 7.0.2.2'
Run your Dockerfile and Start up your server
In you terminal window, inside the directory of your project run the following to initiate your docker containers. This may take a while.
$ docker-compose run --no-deps web rails new . --force --database=postgresql
Note, that with the call to rails, you can call other rails options other than just the database type. You can call the --api, or any number of other rails configuration options.
Now that the Docker containers have been built, you can build the application by running:
$ docker-compose build
Afterward we need to update our rails config/database.yml file to look like the following
default: &default adapter: postgresql encoding: unicode pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> host: <%= ENV.fetch('DB_HOST', 'localhost') %> username: <%= ENV['DB_USERNAME'] %> password: <%= ENV['DB_PASSWORD'] %>
development: <<: *default database: app_developmenttest: <<: *default database: app_test
production: <<: *default database: app_production username: app password: <%= ENV["APP_DATABASE_PASSWORD"] %>
Migrating the Database
Now we can open docker application, and use it to launch a terminal to the running docker project by clicking the icon circled in red below. You can also launch Visual Studio Code by clicking on it's open icon.
Now that the terminal is open for the web-1 container, we can run our rake commands, and interact with rails running in the docker container.
$ rake db:create
$ rake db:migrate
Comments
Post a Comment