Help us understand the problem. What is going on with this article?

dockerのmysqlでUTF8が文字化けしたらやること

More than 1 year has passed since last update.

はじめに

dockerでローカル開発環境を作る時、大概お世話になるのがmysqlイメージですよね〜
/docker-entrypoint-initdb.dに初期化のsqlを入れたフォルダをマウントするとdocker起動時に実行してくれるのでほんと便利ですね!
だけど、えー・・文字化けしてるやん!ってことで悩んでるかたはこちらを試してみてください。

やること

dockerを起動する時のコマンドにcharacter-setcollation-serverを指定しときましょう

docker-compose.yml
version: '3'
services:
  mysql:
    image: mysql
    command: mysqld --character-set-server=utf8 --collation-server=utf8_unicode_ci
    volumes:
      - ./docker/mysql:/docker-entrypoint-initdb.d
    ...

起動時に実行されるsqlでは、先頭でCHARACTER_SET_CLIENTCHARACTER_SET_CONNECTIONをしときましょう。

./docker/mysql/create.sql
SET CHARSET UTF8;
CREATE DATABASE IF NOT EXISTS sample_database DEFAULT CHARACTER SET utf8;

USE sample_database;
CREATE TABLE IF NOT EXISTS sample_table(
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(255),
  updated_at TIMESTAMP
);

./docker/mysql/insert.sql
USE sample_database;

SET CHARACTER_SET_CLIENT = utf8;
SET CHARACTER_SET_CONNECTION = utf8;

INSERT INTO sample_table 
  (name) 
VALUES 
  ('テスト1'),
  ('テスト2');

これで大丈夫なはず!?

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away