2

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!

2
  • How is your Rails server run? On Docker or from your machine directly? Commented Apr 10, 2020 at 8:35
  • @PierreB. I run it from my machine directly (I use MacOS Catalina by the way) Commented Apr 10, 2020 at 8:37

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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!
Great, happy to help! I'll edit with this alternative solution (DATABASE_URL is also a supported way of doing this)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.