LoginSignup
137
94

More than 5 years have passed since last update.

Docker公式イメージのMySQLで文字コードを指定する

Last updated at Posted at 2016-04-23

Docker公式のMySQLイメージを使用

Docker Composeを使ってDocker公式のMySQLイメージを利用したら文字コードでハマった。
下記構成でDocker Compose利用時、アプリサーバとMySQLサーバの文字コードが相違した。

docker-compose.yml
version: '2'
services:
  db:
    image: mysql:5.5
    volumes:
      - data:/var/lib/mysql
    environment:
      MYSQL_ROOT_PASSWORD: 'password'
    ports:
      - 3306
  cache:
    image: memcached:1.4
    ports:
      - 11211
  rails:
    build: .
    command: bundle exec rails s -p 3000 -b '0.0.0.0'
    volumes:
      - .:/opt/rails
    ports:
      - "3000:3000"
    environment:
      RAILS_ENV: local
      DATABASE_URL: mysql2://root:password@db:3306
      CACHE_SERVER: cache:11211
    links:
      - db
      - cache
volumes:
  data:
    driver: local

発生した文字コード相違問題

こんな感じで相違していた。
* Rails: utf8
* MySQL: latin1

エラーメッセージが発生してRailsが起動しない!
charset: utf8, collation: utf8_general_ci (if you set the charset manually, make sure you have a matching collation)

my.cnf編集させなくてもイケるんじゃね

色々とググッてみたらmy.cnfを編集しなくてはいけないという記載をよく見た。
そんな面倒なことあるか!?
とりあえずDocker公式のMySQLレポジトリへ飛んだ。
Docker公式MySQLレポジトリ

そしたらこんな記載が・・・!

Configuration without a cnf file
Many configuration options can be passed as flags to mysqld. This will give you the flexibility to customize the container without needing a cnf file. For example, if you want to change the default encoding and collation for all tables to use UTF-8 (utf8mb4) just run the following:

そんで下記のようなコマンド例もちゃんと書いてある!

$ docker run --name some-mysql -e MYSQL_ROOT_PASSWORD=my-secret-pw -d mysql:tag --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci

解決方法

docker-compose.ymlを下記のように編集した。

docker-compose.yml
version: '2'
services:
  db:
    image: mysql:5.5
    command: mysqld --character-set-server=utf8 --collation-server=utf8_unicode_ci
    volumes:
      - data:/var/lib/mysql
    environment:
      MYSQL_ROOT_PASSWORD: 'password'
    ports:
      - 3306
  cache:
    image: memcached:1.4
    ports:
      - 11211
  rails:
    build: .
    command: bundle exec rails s -p 3000 -b '0.0.0.0'
    volumes:
      - .:/opt/rails
    ports:
      - "3000:3000"
    environment:
      RAILS_ENV: local
      DATABASE_URL: mysql2://root:password@db:3306
      CACHE_SERVER: cache:11211
    links:
      - db
      - cache
volumes:
  data:
    driver: local

具体的にはdbにcommandを追加して、コマンドラインで文字コードの設定を渡すようにした。

137
94
2

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
137
94