0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

docker-compose run web rails db:migrateでエラーが出る

Last updated at Posted at 2023-03-10

エラー内容 

[+] 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) を解決

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?