Search⌘ K
AI Features

Restarting Our Rails Server with Database

Explore how to integrate a Postgres database into your Rails app using Docker Compose. Learn to organize environment configurations, create development and test databases with Rails commands, and restart the Rails server to apply changes. This lesson helps you verify the database connection and practice running migrations and scaffolds in a Dockerized Rails environment.

Separating our environment-specific configurations

First, we will need some directories to store our environment-specific config:

$ mkdir -p .env/development

Configurations of web

Then we require a file, .env/development/web (without a file extension), which contains our web-service-specific environment variables:

DATABASE_HOST=database

Configurations of database

And another file, .env/development/database, containing variables for our database service:

POSTGRES_USER=postgres
POSTGRES_PASSWORD=some-long-secure-password
POSTGRES_DB=myapp_development

Updating the Compose file

Now we need to tell Compose to use these files instead of explicitly setting the variables directly. We do this using the env_file directive:

YAML
version: '3'
services:
web:
build: .
ports:
- "3000:3000"
volumes:
- .:/usr/src/app
env_file:
- .env/development/database
- .env/development/web
redis:
image: redis
database:
image: postgres
env_file:
- .env/development/database

We could have named the environment files anything we liked, but we chose a simple naming scheme that made sense. Similarly, you are free to use whatever file structure and naming conventions you like for the ...