Skip to content

Instantly share code, notes, and snippets.

@staskolukasz
Last active November 10, 2024 22:40
Show Gist options
  • Select an option

  • Save staskolukasz/5a294d1bd044ee5a725140c460b34266 to your computer and use it in GitHub Desktop.

Select an option

Save staskolukasz/5a294d1bd044ee5a725140c460b34266 to your computer and use it in GitHub Desktop.
MacOS + Postgres + Docker + Ruby on Rails

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.

  1. Create docker-compose.yml file:
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
  1. Make sure that Docker Desktop or OrbStack is installed.

  2. Open the terminal, go to docker-compose.yml location and run the command docker-compose up -d in order to spawn Postgresql container in deattached mode.

  3. Modify database.yml in 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
  1. 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) %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment