Pull the mirror

Docker pull mysql: 8.0.20Copy the code

Run the container

docker run --name mysql -e MYSQL_ROOT_PASSWORD=123456 -d3306 - p32771: mysql: 8.0.20Copy the code

Parameter Description:

  • –name Specifies the container name
  • -e Sets environment variables. This parameter specifies the initial password of the mysql root user
  • -d Stands for Damon, running in the background
  • – P32771:3306 maps port 3306 of mysql in the container to port 32771 of the host

Navicat client connection

Execute docker ps to see if the container is started






Mysql is the name of the container
docker exec -it mysql bash
# on mysql
mysql -p
Alter user root's host to support non-native access
use mysql
update user set host=The '%' where user='root';
Change the password of user root and verify plugin
alter user 'root'@The '%' identified with mysql_native_password by 'root';
Copy the code

Communicate connection successful!

Using a Data Volume

If the container is started in the preceding way, data generated after the restart will be lost without backup. Using data volumes can easily solve this problem.

Delete old containers
docker rm -f mysql
Start a new container
docker run \
--name mysql \
-v /usr/local/mysql/conf:/etc/mysql/conf.d \
-v /usr/local/mysql/data:/var/lib/mysql \
-e MYSQL_ROOT_PASSWORD=123456 \
-d -P mysql
Copy the code
  • -v Mounts a local directory to a container as a data volume
  • The mysql server reads it when it starts/etc/mysql/my.cnfIn the configuration, which passes! includedirCustom configuration directories are introduced/etc/mysql/conf.d, will host the machine/usr/local/mysql/confOnce mounted to this directory, you can create and modify custom mysql configuration files on the host (to.cnfAt the end).
  • In the container/etc/mysql/my.cnfThe configuration file also specifies the mysql data directorydatadir=/var/lib/mysql, will host the machine/usr/local/mysql/dataMount to this directory and the container will restart without losing the generated data.