I'm trying use Docker compose and Dockerfile to connect my Ruby on Rails app to Mariadb database and importing a database (.sql file) to this database.
I'm using gem 'mysql2', '>= 0.3.18', '< 0.5'
In config/database.yml I tried:
default: &default
adapter: mysql2
encoding: utf8
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
username: root
password: somepassword
host: mysql2://root:somepassword@127.0.0.1:3306/mydatabase
development:
<<: *default
I also tried replacing the above with the following:
default: &default
url: <%= ENV['DATABASE_URL'] %>
development:
<<: *default
In Dockerfile I added:
# after COPY . .
RUN bundle exec rake RAILS_ENV=production DATABASE_URL=mysql2://root:somepassword@127.0.0.1:3306/mydatabase SECRET_TOKEN=sometoken assets:precompile
CMD bundle exec unicorn -c config/
In docker-compose.yml :
services:
mysql:
image: mariadb:10.3
container_name: mysql
volumes:
- ./database.sql:/docker-entrypoint-initdb.d/database.sql
- ~/.docker-volumes/database/mysql:/var/lib/mysql
environment:
MYSQL_ROOT_PASSWORD: somepassword
MYSQL_DATABASE: mydatabase
ports:
- '3306:3306'
rails_app:
build: .
restart: always
container_name: rails_app
environment:
DATABASE_URL: mysql2://root:somepassword@mysql/mydatabase
links:
- mysql:sql_srv
- redis
- elasticsearch
volumes:
- .:/rails_app
ports:
- '3000:3000'
env_file:
- .rails_app.env
In .rails_app.env :
SECRET_KEY_BASE=sometoken
WORKER_PROCESSES=1
LISTEN_ON=127.0.0.1:3000
DATABASE_URL=mysql2://root:somepasssword@127.0.0.1:3306/mydatabase
The error I got for my last attempt was:
Mysql2::Error: Can't connect to MySQL server on '127.0.0.1' (111 "Connection refused")
...
ERROR: Service 'rails_app' failed to build: The command '/bin/sh -c bundle exec rake RAILS_ENV=production DATABASE_URL=mysql2://root:somepassword@127.0.0.1:3306/mydatabase SECRET_TOKEN=sometoken assets:precompile' returned a non-zero code: 1
How can I fix this issue and succeed to connect rails app with mariadb through Docker compose?
Any help please?
Try change database.yml
to
default: &default
adapter: mysql2
encoding: utf8
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
username: root
password: somepassword
host: sql_srv
database: mydatabase
port: 3306
Also remove DATABASE_URL
from bundle exec rake
in Dockerfile
You trying to connect database on 127.0.0.1
but really your DB locate on another docker container in same network, in
links:
- mysql:sql_srv
- redis
- elasticsearch
you pass to rails_app
service link to database service and set alias to sql_srv
From rails app you can connect to database use that link wich will be resolved in docker network to mysql
service.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.