1
0
Fork 0
mirror of https://github.com/docker/awesome-compose.git synced 2025-04-19 15:28:06 +02:00
This commit is contained in:
Julien Boyer 2024-05-20 20:38:20 +02:00 committed by GitHub
commit 1bcb3b093a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 214 additions and 49 deletions

View file

@ -5,23 +5,34 @@ a Rails/PostgreSQL app. Before starting, [install Compose](https://docs.docker.c
## Define the project
### Dockerfile
Start by setting up the files needed to build the app. The app will run inside a
Docker container containing its dependencies. Defining dependencies is done using
a file called `Dockerfile`. To begin with, the Dockerfile consists of:
```dockerfile
# syntax=docker/dockerfile:1
FROM ruby:2.5
RUN apt-get update -qq && apt-get install -y nodejs postgresql-client
WORKDIR /myapp
COPY Gemfile /myapp/Gemfile
COPY Gemfile.lock /myapp/Gemfile.lock
FROM ruby:3.2.2
# Install postgres client
RUN apt-get update && apt-get install -y postgresql-client
WORKDIR /app
COPY Gemfile /app/Gemfile
COPY Gemfile.lock /app/Gemfile.lock
RUN bundle install
COPY . /app
# Only necessary for production
# RUN rails assets:precompile
# Add a script to be executed every time the container starts.
COPY entrypoint.sh /usr/bin/
RUN chmod +x /usr/bin/entrypoint.sh
ENTRYPOINT ["entrypoint.sh"]
EXPOSE 3000
# Configure the main process to run when running the image
@ -33,11 +44,13 @@ with Ruby, Bundler and all your dependencies inside it. For more information on
how to write Dockerfiles, see the [Docker user guide](https://docs.docker.com/get-started/)
and the [Dockerfile reference](https://docs.docker.com/engine/reference/builder/).
# Set up Rails
Next, open an editor and create a bootstrap `Gemfile` which just loads Rails. This will be overwritten in a moment by `rails new`.
```ruby
source 'https://rubygems.org'
gem 'rails', '~>5'
gem 'rails', '~>7'
```
Create an empty `Gemfile.lock` file to build our `Dockerfile`.
@ -56,12 +69,14 @@ This script will be executed every time the container gets started.
set -e
# Remove a potentially pre-existing server.pid for Rails.
rm -f /myapp/tmp/pids/server.pid
rm -f /app/tmp/pids/server.pid
# Then exec the container's main process (what's set as CMD in the Dockerfile).
exec "$@"
```
### Compose file
Finally, `docker-compose.yml` is where the magic happens. This file describes
the services that comprise your app (a database and a web app), how to get each
one's Docker image (the database just runs on a pre-made PostgreSQL image, and
@ -69,29 +84,83 @@ the web app is built from the current directory), and the configuration needed
to link them together and expose the web app's port.
```yaml
volumes:
db-data:
gems:
services:
db:
image: postgres
image: postgres:15
volumes:
- ./tmp/db:/var/lib/postgresql/data
environment:
POSTGRES_PASSWORD: password
- db-data:/var/lib/postgresql/data
env_file: .env
web:
build: .
command: bash -c "rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'"
volumes:
- .:/myapp
- .:/app:z
- gems:/usr/local/bundle
ports:
- "3000:3000"
depends_on:
# - maildev # for email in dev, optional
- db
env_file: .env
# lets you use the debugger
# stdin_open: true
# tty: true
# Shows you emails sent by Rails at localhost:1080
# maildev:
# image: maildev/maildev:2.1.0
# ports:
# - "1080:1080"
test:
build: .
volumes:
- .:/app
- gems:/usr/local/bundle
depends_on:
- db
# - chrome-server # For system tests, optional
environment:
RAILS_ENV: test
env_file: .env
# lets you use the debugger
# stdin_open: true
# tty: true
# For system tests, optional
# chrome-server:
# image: selenium/standalone-chrome:114.0
```
> **Tip**
>
> You can use either a `.yml` or `.yaml` extension for this file.
### Build the project
### Dot env file
You can see in the docker-compose.yml file:
```yaml
env_file: .env
```
We need to create that .env file, with the following content:
```bash
POSTGRES_PASSWORD=uniquesecretpassword
POSTGRES_USER=postgres
```
Feel free to make them unique.
Note for later: if you commit your code to git, make sure to add this .env file that has your
db password to .gitignore. You can use this file to store other secrets.
## Build the project
With those files in place, you can now generate the Rails skeleton app
using [docker compose run](https://docs.docker.com/engine/reference/commandline/compose_run/):
@ -143,67 +212,55 @@ $ sudo chown -R $USER:$USER .
If you are running Docker on Mac or Windows, you should already have ownership
of all files, including those generated by `rails new`.
Now that youve got a new Gemfile, you need to build the image again. (This, and
changes to the `Gemfile` or the Dockerfile, should be the only times youll need
to rebuild.)
This process added a lof of gems to your gemfile. One of them can be removed,
as we will sidestep it:
```console
$ docker compose build
Remove:
```ruby
gem "webdrivers"
```
### Connect the database
## Connect the database
The app is now bootable, but you're not quite there yet. By default, Rails
expects a database to be running on `localhost` - so you need to point it at the
`db` container instead. You also need to change the database and username to
align with the defaults set by the `postgres` image.
Replace the contents of `config/database.yml` with the following:
Adapt the contents of `config/database.yml`.
The lines you need to add are marked with a comment.
```yaml
default: &default
adapter: postgresql
encoding: unicode
# add what's below this
host: db
username: postgres
password: password
pool: 5
username: <%= ENV['POSTGRES_USER'] %>
password: <%= ENV['POSTGRES_PASSWORD'] %>
# and above this
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
development:
<<: *default
database: myapp_development
database: app_development
test:
<<: *default
database: myapp_test
database: app_test
```
You can now boot the app with [docker compose up](https://docs.docker.com/engine/reference/commandline/compose_up/).
If all is well, you should see some PostgreSQL output:
You can now boot the app with [docker compose up web](https://docs.docker.com/engine/reference/commandline/compose_up/).
```console
$ docker compose up
rails_db_1 is up-to-date
Creating rails_web_1 ... done
Attaching to rails_db_1, rails_web_1
db_1 | PostgreSQL init process complete; ready for start up.
db_1 |
db_1 | 2018-03-21 20:18:37.437 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432
db_1 | 2018-03-21 20:18:37.437 UTC [1] LOG: listening on IPv6 address "::", port 5432
db_1 | 2018-03-21 20:18:37.443 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
db_1 | 2018-03-21 20:18:37.726 UTC [55] LOG: database system was shut down at 2018-03-21 20:18:37 UTC
db_1 | 2018-03-21 20:18:37.772 UTC [1] LOG: database system is ready to accept connections
$ docker compose up web
```
Finally, you need to create the database. In another terminal, run:
```console
$ docker compose run web rake db:create
Starting rails_db_1 ... done
Created database 'myapp_development'
Created database 'myapp_test'
$ docker compose run web rails db:prepare
```
### View the Rails welcome page!
@ -215,7 +272,7 @@ browser to see the Rails Welcome.
![Rails example](images/rails-welcome.png)
### Stop the application
## Stop the application
To stop the application, run [docker compose down](https://docs.docker.com/engine/reference/commandline/compose_down/) in
your project directory. You can use the same terminal window in which you
@ -234,11 +291,11 @@ Removing network rails_default
```
### Restart the application
## Restart the application
To restart the application run `docker compose up` in the project directory.
To restart the application run `docker compose up web` in the project directory.
### Rebuild the application
## Rebuild the application
If you make changes to the Gemfile or the Compose file to try out some different
configurations, you need to rebuild. Some changes require only
@ -263,6 +320,114 @@ Inside the container, your app is running on the same port as before `3000`, but
the Rails Welcome is now available on `http://localhost:3001` on your local
host.
## Configure mail
The app includes a maildev server so you can view emails sent by your app.
Uncomment the maildev service in docker-compose.yml if your app needs to
send email.
Then add this to config/development.rb
```ruby
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
:address => 'maildev',
:port => 1025,
:openssl_verify_mode => 'none'
}
```
Now [set up a mailer](https://guides.rubyonrails.org/action_mailer_basics.html) and view all emails sent by
your app at http://localhost:1080
## How to use rails in Docker Compose
At this point, your dev environement is set up. You can create your models and scaffold by piping rails to the correct container. Simply prefix "docker compose run web" to your command. For example, let's generate a scaffold.
```console
docker compose run web rails generate scaffold Post title:string body:text
```
You can edit files locally and see the result in your browser. Just edit the routes files to point to Post#index and your new blogging platform is ready. As soon as you've migrated the database, that is:
```console
docker compose run web rails db:migrate
```
If you want to see the routes:
```console
docker compose run web rails routes
```
NB: you can pipe it to other commands.
```console
docker compose run web rails routes | grep articles
```
And the rails console is waiting for you at
```console
docker compose run web rails console
```
Install some gems you added to your Gemfile:
```console
docker-compose run web bundle install
```
Drop in a terminal inside the rails container:
```console
docker-compose run web bash
```
## Run some tests
The test environment has some setup steps as well. Mostly related to system tests. In fact, your regular tests are already ready to run.
Once you migrate your test database of course:
```bash
docker compose run test rails db:migrate
docker compose run test rails test
```
Note how we're not using the "web" container, but from the "test" container.
Your system tests however, the ones that fire up an actual browser and simulate clicks and keyboard entries,
these tests won't work yet, as we need to point Rails to the Chrome browser included in the app in the
"chrome-server" service.
If you don't need system tests, ignore the next part.
### Set up the browser for system tests
First, uncomment the chrome-server service in the docker-compose.yml
#### Point Capybara to the browser
Rails expects the browser to be local. We need to point it to the chrome-server.
Adapth the driver definition in test/application_system_test_case.rb
```ruby
driven_by :selenium, using: :headless_chrome, screen_size: [1400, 1400], options: {
browser: :remote,
url: "http://chrome-server:4444/wd/hub"
}
```
#### Point the browser to your app
In test/test_helper.rb, add:
```ruby
Capybara.server_host = "0.0.0.0"
Capybara.app_host = "http://#{ENV.fetch("HOSTNAME")}:#{Capybara.server_port}"
```
It should be at the base of the file, outside of the TestCase class definition.
Now you can run your system tests:
```bash
docker compose run test rails test:system
```
## More Compose documentation
* [Docker Compose overview](https://docs.docker.com/compose/)

Binary file not shown.

Before

Width:  |  Height:  |  Size: 334 KiB

After

Width:  |  Height:  |  Size: 62 KiB

Before After
Before After