在目录/home/mysql下新建文件my.cnf
vim my.cnf
复制以下内容
[mysql]
default-character-set=utf8
socket = /var/lib/mysql/mysql.sock
[mysqld]
pid-file = /var/lib/mysql/mysql.pid
socket = /var/lib/mysql/mysql.sock
datadir = /var/lib/mysql
secure-file-priv= NULL
log-bin-trust-function-creators=1
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
# Custom config should go here
!includedir /etc/mysql/conf.d/
# 错误日志,指定到 /var/log/mysql 目录
log_error=/var/log/mysql/mysql_err.log
在 /home/mysql 目录下,创建 .env 文件
vim .env
复制内容如下:
MYSQL_ROOT_PASSWORD=123456
MYSQL_DATABASE=testdb
在 /home/mysql 目录下,创建 docker-compose.yml 文件,内容如下:
vim docker-compose.yml
version: "3.7"
networks:
service-network:
name: service-network
services:
service_mysql:
image: mysql:8.1
restart: always
container_name: mysql_8.1
ports:
- 3307:3306
environment:
- MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD}
- MYSQL_DATABASE=${MYSQL_DATABASE}
networks:
- service-network
volumes:
- /home/mysql/my.cnf:/etc/mysql/my.cnf:rw
- /home/mysql/data:/var/lib/mysql/:rw
- /home/mysql/logs:/var/log/mysql/:rw
容器内的程序要在挂载的 log 目录下创建 log 文件,需要确保 root 以外的用户也有 log 目录的写权限,/home/mysql 目录下输入:
sudo chmod 777 logs
在 /home/mysql 目录下输入:
docker-compose up -d
通过命令行或者第三方客户端测试连接即可