LoginSignup
0
0

More than 1 year has passed since last update.

Docker公式イメージのmysqlの文字コードを変更する方法

Posted at

はじめに

Dockerを使ってrailsでSNSアプリを作成していたところ、日本語をmysqlデータベースに保存しようとするとエラーがでてしまいました。原因を模索していると、mysqlの文字コードがデフォルトでlatin1になっていたためでした。

latin1は日本語未対応みたいですね。
参考:Latin-1のアスキーコード表

mysqlの文字コードを日本語対応のutf8mb4に変更する

DockerHubからmysql公式イメージのDescriptionによると、
引用元:DockerHub mysqlについてのDescription

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

本来mysqlの文字コードを設定する場合、mysqlを設定するcnfファイルを編集する必要があるが、cnfファイルの編集をせず、上記のようにコマンドを実行することでmysqlの文字コードをカスタマイズできるようですね。

mysqlの文字コード設定方法

docker-compose.ymlファイルを以下のように編集しました。

Docker-compose.yml
version: '3'
services:
  db:
    image: mysql:5.7
    command: mysqld --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci
    environment:
      MYSQL_DATABASE: with_exo_development
      MYSQL_ROOT_PASSWORD: dbpass
      MYSQL_USER: dbuser
      MYSQL_PASSWORD: dbpass
    ports:
      - "3306:3306"

  web:
    build:
      context: .
      dockerfile: Dockerfile
    command: /bin/sh -c "rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'"
    tty: true
    stdin_open: true
    depends_on:
      - db
    ports:
      - "3000:3000"
    volumes:
      - .:/app

dbのcommand部分を追記しました。

最後に

今回、文字コードをutf8ではなくutf8mb4にした理由は、絵文字もデータベースに保存できるようにするためです。

参考記事:Docker公式イメージのMySQLで文字コードを指定する

0
0
0

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
0
0