Data Volume 练习 MySQL

Note

本次练习,演示使用的是Linux环境,Windows环境也可以做这里面的90%以上的内容

使用MySQL官方镜像,tag版本5.7

Dockerfile可以在这里查看 https://github.com/docker-library/mysql/tree/master/5.7

准备镜像

  1. $ docker pull mysql:5.7
  2. $ docker image ls
  3. REPOSITORY TAG IMAGE ID CREATED SIZE
  4. mysql 5.7 2c9028880e58 5 weeks ago 447MB

创建容器

关于MySQL的镜像使用,可以参考dockerhub https://hub.docker.com/_/mysql?tab=description&page=1&ordering=last_updated

关于Dockerfile Volume的定义,可以参考 https://github.com/docker-library/mysql/tree/master/5.7

  1. $ docker container run --name some-mysql -e MYSQL_ROOT_PASSWORD=my-secret-pw -d -v mysql-data:/var/lib/mysql mysql:5.7
  2. 02206eb369be08f660bf86b9d5be480e24bb6684c8a938627ebfbcfc0fd9e48e
  3. $ docker volume ls
  4. DRIVER VOLUME NAME
  5. local mysql-data
  6. $ docker volume inspect mysql-data
  7. [
  8. {
  9. "CreatedAt": "2021-06-21T23:55:23+02:00",
  10. "Driver": "local",
  11. "Labels": null,
  12. "Mountpoint": "/var/lib/docker/volumes/mysql-data/_data",
  13. "Name": "mysql-data",
  14. "Options": null,
  15. "Scope": "local"
  16. }
  17. ]
  18. $

数据库写入数据

进入MySQL的shell,密码是 my-secret-pw

  1. $ docker container exec -it 022 sh
  2. # mysql -u root -p
  3. Enter password:
  4. Welcome to the MySQL monitor. Commands end with ; or \g.
  5. Your MySQL connection id is 2
  6. Server version: 5.7.34 MySQL Community Server (GPL)
  7. Copyright (c) 2000, 2021, Oracle and/or its affiliates.
  8. Oracle is a registered trademark of Oracle Corporation and/or its
  9. affiliates. Other names may be trademarks of their respective
  10. owners.
  11. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
  12. mysql> show databases;
  13. +--------------------+
  14. | Database |
  15. +--------------------+
  16. | information_schema |
  17. | mysql |
  18. | performance_schema |
  19. | sys |
  20. +--------------------+
  21. 4 rows in set (0.00 sec)
  22. mysql> create database demo;
  23. Query OK, 1 row affected (0.00 sec)
  24. mysql> show databases;
  25. +--------------------+
  26. | Database |
  27. +--------------------+
  28. | information_schema |
  29. | demo |
  30. | mysql |
  31. | performance_schema |
  32. | sys |
  33. +--------------------+
  34. 5 rows in set (0.00 sec)
  35. mysql> exit
  36. Bye
  37. # exit

创建了一个叫 demo的数据库

查看data volume

  1. $ docker volume inspect mysql-data
  2. [
  3. {
  4. "CreatedAt": "2021-06-22T00:01:34+02:00",
  5. "Driver": "local",
  6. "Labels": null,
  7. "Mountpoint": "/var/lib/docker/volumes/mysql-data/_data",
  8. "Name": "mysql-data",
  9. "Options": null,
  10. "Scope": "local"
  11. }
  12. ]
  13. $ ls /var/lib/docker/volumes/mysql-data/_data
  14. auto.cnf client-cert.pem ib_buffer_pool ibdata1 performance_schema server-cert.pem
  15. ca-key.pem client-key.pem ib_logfile0 ibtmp1 private_key.pem server-key.pem
  16. ca.pem demo ib_logfile1 mysql public_key.pem sys
  17. $

其它数据库

如果熟悉的话,也可以试试MongoDB https://hub.docker.com/_/mongo