- Create your project dir
railsapp
and copy the Dockerfile inside. - Comment all but first 3 lines in
Dockerfile
. - Run
docker build -t railsapp:latest .
- Once done, run
docker run --rm -it -v $(pwd):/project railsapp:latest /bin/bash
- Inside docker, run the following commands
rails new railsapp --api --database=postgresql --skip-bundle mv railsapp/{*,.*} /project/ exit
- Then in the host, own everything back from root using
sudo chown -R $USER:$USER .
- Add the following in
config/database.yml
filedefault: &default # other stuff # adapter: ... # encoding: ... # pool: ... host: db username: postgres password: password
- Uncomment previously commented lines in
Dockerfile
- Copy docker-compose.yml to your project folder
- Then run the following docker commands:
docker compose build docker compose up
- Without closing the docker compose up running task, run in another terminal
docker compose run web rails db:create
- Your app should now be running at
http://localhost:3000
It is a good practice to keep the configuration in a separate file inside the codebase. Fortunately, the variables specified in docker-compose.yml
file, without no extra setup, will be subsituted with the variables specified inside the .env
file (if they are not present in the environment variables already).
-
Add a new line
.env
at the end of.gitignore
file if it is not present already. This.env
file which we will create in the next step contains all the secrets and hence is added to.gitignore
before creation! -
Add a new
.env
file with the following contents:RAILS_APPNAME=railsapp RAILS_DEMO_POSTGRES_USERNAME=railsapp RAILS_DEMO_POSTGRES_PASSWORD=password RAILS_DEMO_POSTGRES_HOST=db
-
postgres docker image allows creating specific roles with the specified password using the entrypoint script. Add under
db
indocker-compose.yml
,services: db: environment: - POSTGRES_USER=${RAILS_DEMO_POSTGRES_USERNAME} - POSTGRES_PASSWORD=${RAILS_DEMO_POSTGRES_PASSWORD}
-
All the environment variables inside
.env
file are required for our rails app and so, underweb
indocker-compose.yml
add,services: web: env_file: - .env
-
Replace the hardcoded variables previously added in the
database.yml
filedefault: &default # other stuff # adapter: ... # encoding: ... # pool: ... host: <%= ENV["RAILS_DEMO_POSTGRES_HOST"] %> username: <%= ENV["RAILS_DEMO_POSTGRES_USERNAME"] %> password: <%= ENV["RAILS_DEMO_POSTGRES_PASSWORD"] %>