1

I am trying to use MySQL on Docker (instead of Homebrew) for a Rails project. This is because I need different versions of MySQL for each project, and it's a pain to switch versions with brew. However, I'm having trouble pointing Rails to the MySQL server on Docker.

I started the Docker container like this (5.6 is the version I need):

docker run -p 3306:3306 --name project-db -e MYSQL_ROOT_PASSWORD=mysql_pw -d mysql:5.6

The container seems to be up and running fine, because

  • docker ps tells me it is running
  • I can connect to it via mysql -u root -p -h 127.0.0.1

But I can't get Rails to create its DB in Docker; executing rails db:setup creates the DB in the locally installed MySQL instead.

I tried uninstalling MySQL locally with brew uninstall mysql, thinking perhaps it was somehow overriding the Docker one. But then, trying to set up the DB results in this error:

Mysql2::Error: Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

I'm not very familiar with Docker so I'm probably misunderstanding something. I googled around, but most of the information I could find was for Dockerizing the entire Rails project including MySQL, which is not what I'm trying to do.

Thanks for any advice in advance!

reesaspieces
  • 1,600
  • 4
  • 18
  • 47

1 Answers1

1

Your MySQL instance is exposed on localhost via port 3306. You must configure Rails to use it, something like:

development:
  adapter: mysql2
  encoding: utf8
  database: my_db_name
  username: root
  password: my_password
  host: 127.0.0.1
  port: 3306

Or by using environment variable:

export DATABASE_URL=mysql2://root:@127.0.0.1

See this post and rails doc for details

Currently you are trying to access MySQL via a socket at /tmp/mysql.sock but there is nothing available here as your MySQL instance runs into its container.

Pierre B.
  • 11,612
  • 1
  • 37
  • 58
  • 1
    I wasn't allowed to edit `database.yml` because it's a team project, but your answer gave me an idea - in my environment variables, I tried setting up `DATABASE_URL=mysql2://root:@127.0.0.1/` and it worked. Thank you so much! – reesaspieces Apr 10 '20 at 09:34
  • 1
    Great, happy to help! I'll edit with this alternative solution (`DATABASE_URL` is also a supported way of doing this) – Pierre B. Apr 10 '20 at 09:46