简体   繁体   中英

Can't connect to remote mysql server from rails

When I run:

bundle exec rails c

I get

Mysql2::Error: Access denied for user 'root'@'$HOST' (using password: YES)

despite the fact that this works just fine:

mysql -h $HOST -P $PORT -u root -p

This is my config/database.yml

development:
  &defaults
  adapter: mysql2
  encoding: utf8mb4
  collation: utf8mb4_unicode_ci
  pool: 5
  host: $HOST
  port: $PORT
  database: $DATABASE
  username: root
  password: $PASSWORD
  reconnect: true

What am I doing wrong?

You can't use bash variables within config/database.yml like that. Rails will treat $HOST as the string "$HOST" , which is what you see happening here

Mysql2::Error: Access denied for user 'root'@'$HOST' (using password: YES)

Instead, you can use ENV

development:
  &defaults
  adapter: mysql2
  encoding: utf8mb4
  collation: utf8mb4_unicode_ci
  pool: 5
  host: ENV['HOST']
  port: ENV['PORT']
  database: ENV['DATABASE']
  username: root
  password: ENV['PASSWORD']
  reconnect: true

Related: http://railsapps.github.io/rails-environment-variables.html

Is the Rails app on localhost?

I think your command line thing translates to

mysql -h $HOST -P $PORT -u root@your-computer -p

MySQL permissions are based on the host you connect from, so if you are running Rails on a remote host, but doing the command line test on localhost, you are making a different request each time. For example, root@localhost should have DROP privileges, but root@$REMOTE_HOST should not. I would expect that your permissions allow only root@your-computer to connect, but not root@$HOST .

If this is the case, alter the privileges to add access to root@$HOST using GRANT

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM