企业运维 | MySQL关系型数据库在Docker与Kubernetes容器环境中快速搭建部署主从实践

乎语百科 317 0
目录
  • 1.Docker 快速部署 MySQL 数据库服务器

    • 命令方式

    • 配置清单

  • 2.Kubernetes 快速部署 MySQL 数据库服务器

    • 单实例模式

    • 主从同步模式


首发地址: https://mp.weixin.qq.com/s/7mmIsd83QPT65QnQd5CtFQ

1.Docker 快速部署 MySQL 数据库服务器

MySQL 是一种广泛使用的开源关系数据库管理系统 (RDBMS),其久经考验的性能、可靠性和易用性,MySQL 已成为基于 Web 的应用程序的领先数据库选择。

MySQL 帮助文档:https://docs.oracle.com/en-us/iaas/mysql-database/doc/getting-started.html镜像仓库地址:https://hub.docker.com/_/mysql镜像问题:https://github.com/docker-library/mysql/issues

温馨提示:此处实践环境是使用Docker,若你没有安装Docker环境或者不了解的Docker容器的朋友,可以参考博主学习【Docker的系列笔记】汇总:https://blog.weiyigeek.top/2018/1-1-1.html#Docker容器学习之路汇总

命令方式

步骤 01.快速部署脚本命令。

# 准备数据持久化目录
mkdir -vp /app/data

# 准备mysql8.x仓库镜像
docker pull mysql:8.0.30

# 准备root密码不采用环境变量直接显示密码
echo "weiyigeek.top" > /app/my-secret-pw

# 一条命令创建运行mysql数据库容器
docker run -d --name mysql8.0 --restart=always \
-v "/app/data":/var/lib/mysql \
-v "/app/my-secret-pw":/app/my-secret-pw \
-e MYSQL_ROOT_PASSWORD_FILE=/app/my-secret-pw \
-e MYSQL_DATABASE=app \
-e MYSQL_USER=weiyigeek \
-e MYSQL_PASSWORD=password \
-p 3306:3306 \
mysql:8.0.30 \
--default-authentication-plugin=mysql_native_password
# 144e883af1a99901913a986d540382c8aefe3e5bd96730ad76a019b2567159bb

# 可以为 mysqld 使用特定的 UID/GID , 例如此处的 1000 用户。
--user 1000:1000 

# 可以为 mysqld 指定命令行参数。
--character-set-server=utf8mb4
--collation-server=utf8mb4_unicode_ci

步骤 02.查看验证在Docker中的部署情况。

# 容器
$ docker ps
CONTAINER ID   IMAGE          COMMAND                  CREATED              STATUS              PORTS                               NAMES
05c5a0e23e39   mysql:8.0.30   "docker-entrypoint.s…"   About a minute ago   Up About a minute   0.0.0.0:3306->3306/tcp, 33060/tcp   mysql8.0

# 日志
$ docker logs mysql8.0
2022-09-27 14:19:03+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.30-1.el8 started.
2022-09-27 14:19:03+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
2022-09-27 14:19:03+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.30-1.el8 started.
2022-09-27 14:19:03+00:00 [Note] [Entrypoint]: Initializing database files

# 连接测试
$ docker exec -it mysql8.0 sh -c 'mysql -u root -p"weiyigeek.top"'
mysql: [Warning] Using a password on the command line interface can be insecure.
mysql> select @@version;
+-----------+
| @@version |
+-----------+
| 8.0.30    |
+-----------+
1 row in set (0.00 sec)

步骤 03.部署 Adminer 进行管理连接 MySQL 数据库, Adminer 是一个类似于 phpMyAdmin 的 MySQL 管理客户端。 Adminer 可用于连接 MySQL, PostgreSQL, SQLite, MSSQL, Oracle, Firebird, SimpleDB, Elasticsearch and MongoDB 等数据库。

docker pull adminer:latest

# Standalone
docker run -d --restart unless-stopped --name db_adminer -p 8080:8080 adminer:latest

# FastCGI
docker run -d --name db_admine_fastcgi --link some_database:db -p 9000:9000 adminer:fastcgi

随后使用浏览器访问宿主机的8080端口进行连接:

温馨提示:MySQL的默认配置可以在 /etc/mysql/my.cnf,或可以自定义配置文件/etc/mysql/conf.d/my.cnf

tee my.cnf <<'EOF'
[mysqld]
# 执行用户
user=mysql

# 开放监听服务端口
port=3306
bind-address=*
socket=/var/run/mysqld/mysqld.sock

# 数据目录
datadir=/var/lib/mysql

# 进程 pid 文件
pid-file=/var/run/mysqld/mysqld.pid

# 插件默认路径
plugin-dir=/usr/lib64/mysql/plugin/

# 安全文件路径
secure-file-priv=/var/lib/mysql-files

# 启用日志与路径设置
general-log=on
general-log-file=/var/lib/mysql/mysql8x.log

# 服务器字符集设置
character-set-server=utf8mb4
collation-server=utf8mb4_unicode_ci

# 数据库容灾binlog启用配置
log-bin=binlog
log-bin-index=binlog.index

# 认证密码策略, 默认 aching_sha2_password , 针对于old链接认证方式为 mysql_native_password
default-authentication-plugin=mysql_native_password

# 跳过某些操作
skip-host-cache
skip-name-resolve

[client]
socket=/var/run/mysqld/mysqld.sock
EOF

温馨提示:如果您想查看 mysqld 可用选项的完整列表,只需运行

$ docker run -it --rm mysql:8.0.30 --verbose --help

# my.cnf 可用配置
Variables (--variable-name=value)
and boolean options {FALSE|TRUE}                             Value (after reading options)
------------------------------------------------------------ -------------
abort-slave-event-count                                      0
activate-all-roles-on-login                                  FALSE
admin-address                                                (No default value)
admin-port                                                   33062
admin-ssl                                                    TRUE
admin-ssl-ca                                                 (No default value)
admin-ssl-capath                                             (No default value)
admin-ssl-cert                                               (No default value)
admin-ssl-cipher                                             (No default value)
admin-ssl-crl                                                (No default value)
admin-ssl-crlpath                                            (No default value)
admin-ssl-key                                                (No default value)
admin-tls-ciphersuites                                       (No default value)
admin-tls-version                                            TLSv1.2,TLSv1.3
allow-suspicious-udfs                                        FALSE
archive                                                      ON
authentication-policy                                        *,,
auto-generate-certs                                          TRUE
auto-increment-increment                                     1
auto-increment-offset                                        1
autocommit                                                   TRUE
automatic-sp-privileges                                      TRUE
avoid-temporal-upgrade                                       FALSE
back-log                                                     151
basedir                                                      /usr/
big-tables                                                   FALSE
bind-address                                                 *
binlog-cache-size                                            32768
binlog-checksum                                              CRC32
binlog-direct-non-transactional-updates                      FALSE
binlog-encryption                                            FALSE
binlog-error-action                                          ABORT_SERVER
binlog-expire-logs-auto-purge                                TRUE
binlog-expire-logs-seconds                                   2592000
binlog-format                                                ROW
binlog-group-commit-sync-delay                               0
binlog-group-commit-sync-no-delay-count                      0
binlog-gtid-simple-recovery                                  TRUE
binlog-max-flush-queue-time                                  0
binlog-order-commits                                         TRUE
binlog-rotate-encryption-master-key-at-startup               FALSE
binlog-row-event-max-size                                    8192
binlog-row-image                                             FULL
binlog-row-metadata                                          MINIMAL
binlog-row-value-options
binlog-rows-query-log-events                                 FALSE
binlog-stmt-cache-size                                       32768
binlog-transaction-compression                               FALSE
binlog-transaction-compression-level-zstd                    3
binlog-transaction-dependency-history-size                   25000
binlog-transaction-dependency-tracking                       COMMIT_ORDER
blackhole                                                    ON
block-encryption-mode                                        aes-128-ecb
bulk-insert-buffer-size                                      8388608
caching-sha2-password-auto-generate-rsa-keys                 TRUE
caching-sha2-password-digest-rounds                          5000
caching-sha2-password-private-key-path                       private_key.pem
caching-sha2-password-public-key-path                        public_key.pem
character-set-client-handshake                               TRUE
character-set-filesystem                                     binary
character-set-server                                         utf8mb4
character-sets-dir                                           /usr/share/mysql-8.0/charsets/
check-proxy-users                                            FALSE
chroot                                                       (No default value)
collation-server                                             utf8mb4_0900_ai_ci
completion-type                                              NO_CHAIN
concurrent-insert                                            AUTO
connect-timeout                                              10
connection-memory-chunk-size                                 8912
connection-memory-limit                                      18446744073709551615
console                                                      FALSE
create-admin-listener-thread                                 FALSE
cte-max-recursion-depth                                      1000
daemonize                                                    FALSE
datadir                                                      /var/lib/mysql/
default-authentication-plugin                                caching_sha2_password
default-password-lifetime                                    0
default-storage-engine                                       InnoDB
default-table-encryption                                     FALSE
default-time-zone                                            (No default value)
default-tmp-storage-engine                                   InnoDB
default-week-format                                          0
delay-key-write                                              ON
delayed-insert-limit                                         100
delayed-insert-timeout                                       300
delayed-queue-size                                           1000
disabled-storage-engines
disconnect-on-expired-password                               TRUE
disconnect-slave-event-count                                 0
div-precision-increment                                      4
end-markers-in-json                                          FALSE
enforce-gtid-consistency                                     FALSE
eq-range-index-dive-limit                                    200
event-scheduler                                              ON
expire-logs-days                                             0
explicit-defaults-for-timestamp                              TRUE
external-locking                                             FALSE
federated                                                    OFF
flush                                                        FALSE
flush-time                                                   0
ft-boolean-syntax                                            + -><()~*:""&|
ft-max-word-len                                              84
ft-min-word-len                                              4
ft-query-expansion-limit                                     20
ft-stopword-file                                             (No default value)
gdb                                                          FALSE
general-log                                                  FALSE
general-log-file                                             /var/lib/mysql/a29706ab34c6.log
generated-random-password-length                             20
global-connection-memory-limit                               18446744073709551615
global-connection-memory-tracking                            FALSE
group-concat-max-len                                         1024
group-replication-consistency                                EVENTUAL
gtid-executed-compression-period                             0
gtid-mode                                                    OFF
help                                                         TRUE
histogram-generation-max-mem-size                            20000000
host-cache-size                                              279
information-schema-stats-expiry                              86400
init-connect
init-file                                                    (No default value)
init-replica
init-slave
initialize                                                   FALSE
initialize-insecure                                          FALSE
innodb-adaptive-flushing                                     TRUE
innodb-adaptive-flushing-lwm                                 10
innodb-adaptive-hash-index                                   TRUE
innodb-adaptive-hash-index-parts                             8
innodb-adaptive-max-sleep-delay                              150000
innodb-api-bk-commit-interval                                5
innodb-api-disable-rowlock                                   FALSE
innodb-api-enable-binlog                                     FALSE
innodb-api-enable-mdl                                        FALSE
innodb-api-trx-level                                         0
innodb-autoextend-increment                                  64
innodb-autoinc-lock-mode                                     2
innodb-buffer-pool-chunk-size                                134217728
innodb-buffer-pool-dump-at-shutdown                          TRUE
innodb-buffer-pool-dump-now                                  FALSE
innodb-buffer-pool-dump-pct                                  25
innodb-buffer-pool-filename                                  ib_buffer_pool
innodb-buffer-pool-in-core-file                              TRUE
innodb-buffer-pool-instances                                 0
innodb-buffer-pool-load-abort                                FALSE
innodb-buffer-pool-load-at-startup                           TRUE
innodb-buffer-pool-load-now                                  FALSE
innodb-buffer-pool-size                                      134217728
innodb-change-buffer-max-size                                25
innodb-change-buffering                                      all
innodb-checksum-algorithm                                    crc32
innodb-cmp-per-index-enabled                                 FALSE
innodb-commit-concurrency                                    0
innodb-compression-failure-threshold-pct                     5
innodb-compression-level                                     6
innodb-compression-pad-pct-max                               50
innodb-concurrency-tickets                                   5000
innodb-data-file-path                                        ibdata1:12M:autoextend
innodb-data-home-dir                                         (No default value)
innodb-ddl-buffer-size                                       1048576
innodb-ddl-threads                                           4
innodb-deadlock-detect                                       TRUE
innodb-dedicated-server                                      FALSE
innodb-default-row-format                                    dynamic
innodb-directories                                           (No default value)
innodb-disable-sort-file-cache                               FALSE
innodb-doublewrite                                           ON
innodb-doublewrite-batch-size                                0
innodb-doublewrite-dir                                       (No default value)
innodb-doublewrite-files                                     0
innodb-doublewrite-pages                                     0
innodb-extend-and-initialize                                 TRUE
innodb-fast-shutdown                                         1
innodb-file-per-table                                        TRUE
innodb-fill-factor                                           100
innodb-flush-log-at-timeout                                  1
innodb-flush-log-at-trx-commit                               1
innodb-flush-method                                          fsync
innodb-flush-neighbors                                       0
innodb-flush-sync                                            TRUE
innodb-flushing-avg-loops                                    30
innodb-force-load-corrupted                                  FALSE
innodb-force-recovery                                        0
innodb-fsync-threshold                                       0
innodb-ft-aux-table                                          (No default value)
innodb-ft-cache-size                                         8000000
innodb-ft-enable-diag-print                                  FALSE
innodb-ft-enable-stopword                                    TRUE
innodb-ft-max-token-size                                     84
innodb-ft-min-token-size                                     3
innodb-ft-num-word-optimize                                  2000
innodb-ft-result-cache-limit                                 2000000000
innodb-ft-server-stopword-table                              (No default value)
innodb-ft-sort-pll-degree                                    2
innodb-ft-total-cache-size                                   640000000
innodb-ft-user-stopword-table                                (No default value)
innodb-idle-flush-pct                                        100
innodb-io-capacity                                           200
innodb-io-capacity-max                                       4294967295
innodb-lock-wait-timeout                                     50
innodb-log-buffer-size                                       16777216
innodb-log-checksums                                         TRUE
innodb-log-compressed-pages                                  TRUE
innodb-log-file-size                                         50331648
innodb-log-files-in-group                                    2
innodb-log-group-home-dir                                    (No default value)
innodb-log-spin-cpu-abs-lwm                                  80
innodb-log-spin-cpu-pct-hwm                                  50
innodb-log-wait-for-flush-spin-hwm                           400
innodb-log-write-ahead-size                                  8192
innodb-log-writer-threads                                    TRUE
innodb-lru-scan-depth                                        1024
innodb-max-dirty-pages-pct                                   90
innodb-max-dirty-pages-pct-lwm                               10
innodb-max-purge-lag                                         0
innodb-max-purge-lag-delay                                   0
innodb-max-undo-log-size                                     1073741824
innodb-monitor-disable                                       (No default value)
innodb-monitor-enable                                        (No default value)
innodb-monitor-reset                                         (No default value)
innodb-monitor-reset-all                                     (No default value)
innodb-old-blocks-pct                                        37
innodb-old-blocks-time                                       1000
innodb-online-alter-log-max-size                             134217728
innodb-open-files                                            0
innodb-optimize-fulltext-only                                FALSE
innodb-page-cleaners                                   &n

标签: # MySQL # Docker # Kubernetes

留言评论

  • 这篇文章还没有收到评论,赶紧来抢沙发吧~