Docker Compose安装MySQL8

拉取 MySQL 镜像

Copy
root@ubuntu:~# docker pull mysql:8.0.31

验证

Copy
root@ubuntu:~# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
mysql 8.0.31 3842e9cdffd2 8 days ago 538MB

创建 MySQL 相关挂载目录

Copy
root@ubuntu:~# mkdir -p mysql/data mysql/conf mysql/log mysql/mysql-files

创建 MySQL 配置文件

Copy
root@ubuntu:~# vim mysql/conf/my.cnf

Copy
[mysqld]
skip-host-cache
skip-name-resolve
datadir=/var/lib/mysql
socket=/var/run/mysqld/mysqld.sock
secure-file-priv=/var/lib/mysql-files

character-set-server=utf8
default_authentication_plugin=mysql_native_password
expire_logs_days=7
sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION
max_connections=1000

pid-file=/var/run/mysqld/mysqld.pid
[client]
socket=/var/run/mysqld/mysqld.sock

[mysql]
default-character-set=utf8

#!includedir /etc/mysql/conf.d/

编辑 MySQL 启动的 yml 文件

Copy
mysql:
image: mysql:8.0.31
container_name: mysql
restart: always
deploy:
resources:
limits:
memory: 1024m
user: root
command:
--default-authentication-plugin=mysql_native_password
--character-set-server=utf8mb4
--collation-server=utf8mb4_general_ci
--explicit_defaults_for_timestamp=true
environment:
MYSQL_ROOT_PASSWORD: root
ports:
- 3306:3306
volumes:
- /opt/mysql/data:/var/lib/mysql:rw
- /opt/mysql/conf/my.cnf:/etc/mysql/my.cnf:rw
- /opt/mysql/log:/var/log/mysql:rw
- /opt/mysql/mysql-files:/var/lib/mysql-files:rw

启动

Copy
root@ubuntu:~# docker-compose up -d

验证

Copy
root@ubuntu:~# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
49e9b0115a54 mysql:8.0.31 "docker-entrypoint.s…" 10 seconds ago Up 9 seconds 33060/tcp, 0.0.0.0:3006->3306/tcp, :::3006->3306/tcp mysql

进入容器内

Copy
root@ubuntu:~# docker exec -it mysql bash

登录 mysql

Copy
bash-4.4# mysql -uroot -p
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 10
Server version: 8.0.31 MySQL Community Server - GPL

Copyright (c) 2000, 2022, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.