The main goal of this gist is to demonstrate how to set up a PostgreSQL container and enable a Ruby on Rails application to connect to the database via PostgreSQL running in Docker.
- Create
docker-compose.ymlfile:
services:
postgres:
image: postgres:14-alpine
restart: always
ports:
- 5432:5432
volumes:
- ~/apps/postgres:/var/lib/postgresql/data
environment:
- POSTGRES_USER=<MacOS system user name goes here>
- POSTGRES_PASSWORD=password
- POSTGRES_DB=postgres
- POSTGRES_HOST_AUTH_METHOD=trust
-
Make sure that Docker Desktop or OrbStack is installed.
-
Open the terminal, go to
docker-compose.ymllocation and run the commanddocker-compose up -din order to spawn Postgresql container in deattached mode. -
Modify
database.ymlin your Ruby on Rails project:
default: &default
adapter: postgresql
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
timeout: 5000
development:
<<: *default
database: db_development
host: <%= ENV.fetch("DATABASE_HOST", "localhost") %>
port: <%= ENV.fetch("DATABASE_PORT", 5432) %>
test:
<<: *default
database: db_test
host: <%= ENV.fetch("DATABASE_HOST", "localhost") %>
port: <%= ENV.fetch("DATABASE_PORT", 5432) %>
production:
<<: *default
database: db_production
- Run your project.
Domain socket works when processes run on the same host OS. Since the database process is on docker which is technically another host, server needs database's TCP Socket address to communicate. That's why you need to add:
host: <%= ENV.fetch("DATABASE_HOST", "localhost") %>
port: <%= ENV.fetch("DATABASE_PORT", 5432) %>