docker-compose 部署mysql

420 阅读1分钟

编写docker-compose.yml

version: '2.3'

services:
    db:
      image: mysql:8.0.20
      ports:
        - "3306:3306"
      volumes:
        - "./mysql/conf:/etc/mysql"
        - "./mysql/logs:/logs"
        - "./mysql/data:/var/lib/mysql"
        - "/etc/localtime:/etc/localtime"
      environment:
        - MYSQL_ROOT_PASSWORD=123456
      logging:
        driver: json-file
        options:
          max-size: "200k"
          max-file: "10"
      healthcheck:
        test: [ "CMD", "curl", "-f", "http://localhost:3306" ] 
        interval: 1m30s
        timeout: 10s
        retries: 3
        start_period: 40s
      restart: always
 

编写mysql.cnf

编写mysql.cnf,存放于./mysql/conf下

# Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
# 
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA

#
# The MySQL  Server configuration file.
#
# For explanations see
# http://dev.mysql.com/doc/mysql/en/server-system-variables.html

[mysqld]
bind-address = 0.0.0.0
pid-file        = /var/run/mysqld/mysqld.pid
socket          = /var/run/mysqld/mysqld.sock
datadir         = /var/lib/mysql
secure-file-priv= NULL
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0

# Custom config should go here
!includedir /etc/mysql/conf.d/


启动

# 后台启动
docker-compose up -d
# 查看启动日志
docker-compose logs -f

image.png

进入容器内进行初始化配置

# 进入容器
docker exec -it mysql-container bash
# 测试mysql,无需密码直接进入
mysql -uroot -p 
# MySQL初始化,设置安全策略和密码
mysql_secure_installation

开启远程访问

mysql.cnf配置

进入容器:`docker exec -it mysql-container bash`
编辑配置文件:`vi /etc/mysql/mysql.conf.d/mysqld.cnf`
找到 `bind-address = 127.0.0.1` 这一行,并将其改为 `bind-address = 0.0.0.0`,然后保存并退出。
重启 MySQL 服务:`service mysql restart`

授权远程访问

 UPDATE mysql.user SET Host='%' WHERE User='root';
 FLUSH PRIVILEGES;

测试连接

   # 退出容器,在宿主机上测试
   mysql -h 127.0.0.1 -P 3306 -u root -p