Build production ready Mysql docker container with customized db, user and character-set

If you simply execute docker run -d -e MYSQL_ROOT_PASSWORD=pass1 mysql, you will get a mysql instance. But, it should not be used in production environment, reasons are:

  • It uses the root user. This is very dangerous.
  • It does not set character-set. This may cause text encoding problems.

Create a better mysql container

Here is an example command:

docker run --name dk_mysql -d -p 13306:3306 \
--env MYSQL_DATABASE=db1 \
--env MYSQL_USER=user1 \
--env MYSQL_PASSWORD=pass1 \
--env MYSQL_RANDOM_ROOT_PASSWORD=yes \
mysql mysqld --character-set-server utf8mb4

Test the created mysql container

Access inside the container:

docker exec -it dk_mysql mysql -D db1 -u user1 -ppass1

Access outside the container:

mysql -h 127.0.0.1 -P 13306 -D db1 -u user1 -ppass1

Check if character-set is correct

We set --character-set-server utf8mb4 earlier, now let's check the effect:

docker exec -it dk_mysql mysql -D db1 -u user1 -ppass1 \
-e "SHOW VARIABLES LIKE 'character_set_server'"

The output will be like:

+----------------------+---------+
| Variable_name        | Value   |
+----------------------+---------+
| character_set_server | utf8mb4 |
+----------------------+---------+
Posted on 2022-04-12