musertest
musertest

Reputation: 11

Rails on docker: Mysql2::Error::ConnectionError: Unknown MySQL server host 'db'

Rails and Docker

TL;DR: I try to orchestrate my rails app using mysql with docker-compose. I have one container running a mysql server and another one using passenger to serve my application. When building I get an unknown Host error.


Hello,

I want to deploy my Ruby on Rails app with docker-compose. Since I wanted to use Passenger as the application server I thought it would also be a good idea to use their baseimage. The application is using mysql as its database. The application works fine in development. When trying to build the image using docker-compose build I get the following error:

** Invoke db:migrate (first_time)
** Invoke db:load_config (first_time)
** Invoke environment (first_time)
** Execute environment
** Execute db:load_config
** Execute db:migrate
rake aborted!
Mysql2::Error::ConnectionError: Unknown MySQL server host 'db' (11)
/var/www/school/code/vendor/bundle/ruby/2.6.0/gems/mysql2-0.5.3/lib/mysql2/client.rb:90:in `
...

I don't quite understand why it's throwing this error since I thought when I use depends_on it will wait for the other container to be started.

I am still learning. Both rails and docker. Here are my compose and database.yml files. If there is anything more to add please let me know. Thanks in advance!

# docker-compose.yml

# Using version 2 because of portainer where its supposed to run later on
version: "2.4"

services:
  db:
    image: mysql:5.7
    volumes:
      - db_data:/var/lib/mysql
    environment:
      MYSQL_ROOT_PASSWORD: password
      MYSQL_DATABASE: school
    ports:
      - "3306:3306"

  app:
    build: 
      context: .
      dockerfile: ./docker/passenger.Dockerfile
    volumes:
      - .:/var/www/school
    ports:
      - "80:80"
    depends_on:
      - db

volumes:
  db_data: {}

And here also my database.yml

# database.yml

default: &default
  adapter: mysql2
  encoding: utf8
  reconnect: false
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  timeout: 5000

production:
  <<: *default
  username: root
  password: "password"
  database: school
  port: 3306
  host: db

Upvotes: 1

Views: 3099

Answers (1)

cdadityang
cdadityang

Reputation: 543

Try Changing your app section in docker-compose.yml to this:

app:
  build: 
    context: .
    dockerfile: ./docker/passenger.Dockerfile
  volumes:
    - .:/var/www/school
  ports:
    - "80:80"
  links:
    - db

Learn more: Docs


Also, you've done a very good job explaining the question precisely/properly. Kudos!

Upvotes: 2

Related Questions