エラー内容
[+] Running 1/0
⠿ Container sample_app_local-db-1 Running 0.0s
Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
Couldn't create 'sample_app_development' database. Please check your configuration.
rails aborted!
ActiveRecord::ConnectionNotEstablished: Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
/myapp/bin/rails:5:in `<top (required)>'
/myapp/bin/spring:15:in `<top (required)>'
Caused by:
Mysql2::Error::ConnectionError: Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
/myapp/bin/rails:5:in `<top (required)>'
/myapp/bin/spring:15:in `<top (required)>'
Tasks: TOP => db:create
(See full trace by running task with --trace)
該当のソースコード
docker-compose.yml
version: "3"
services:
web:
container_name: sample_app_local
build: .
command: bash -c "rm -f tmp/pids/server.pid && yarn install && bundle exec rails s -p 3000 -b '0.0.0.0'"
volumes:
- .:/myapp
ports:
- "3000:3000"
depends_on:
- db
db:
image: mysql:5.7
volumes:
- mysql-data:/var/lib/mysql
environment:
MYSQL_ROOT_PASSWORD: password
MYSQL_USER: root
ports:
- 3306:3306
volumes:
mysql-data:
config/database.yml
#該当箇所を抜粋
default: &default
adapter: mysql2
encoding: utf8
charset: utf8
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
username: root
password: password
socket: /tmp/mysql.sock
原因・解決
database.yml に host の設定が抜けていたから
config/database.yml
default: &default
adapter: mysql2
encoding: utf8
charset: utf8
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
username: root
password: password
socket: /tmp/mysql.sock
host: db #追記
参考サイト
dockerでのエラー Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2) を解決