docker安装单实例MySQL数据库

1、安装docker容器
2、拉取镜像
3、创建MySQL容器

备注:
离线下来镜像并导入到其他容器

# docker save --output /tmp/mysql8043.tar mysql:8.0.43

# docker load -i mysql8043.tar 
827b99c091a5: Loading layer [==================================================>]  116.9MB/116.9MB
39fa2ded14c9: Loading layer [==================================================>]  11.26kB/11.26kB
8eb81af04524: Loading layer [==================================================>]  1.773MB/1.773MB
16b66714c085: Loading layer [==================================================>]  16.93MB/16.93MB
6af4c4c0c273: Loading layer [==================================================>]  6.656kB/6.656kB
b0fa1694a870: Loading layer [==================================================>]  3.072kB/3.072kB
7e009265e212: Loading layer [==================================================>]  147.4MB/147.4MB
202717a8d589: Loading layer [==================================================>]  3.072kB/3.072kB
f931a8173bc7: Loading layer [==================================================>]  515.2MB/515.2MB
2e5e34431da7: Loading layer [==================================================>]  17.41kB/17.41kB
77a5757b25aa: Loading layer [==================================================>]  1.536kB/1.536kB
Loaded image: mysql:8.0.43
# docker images
REPOSITORY   TAG       IMAGE ID       CREATED        SIZE
mysql        8.0.43    8f51417dfdbf   3 months ago   780MB


下载并安装docker

https://download.docker.com/linux/static/stable/x86_64/

mv docker-29.1.2.tgz /opt
cd /opt
tar -zxvf docker-29.1.2.tgz
cp docker/* /usr/bin/
cd /etc/systemd/system/
touch docker.service
vi docker.service  修改镜像源
# cat /etc/docker/daemon.json
{
  "registry-mirrors": [
    "https://docker.hpcloud.cloud",
    "https://docker.m.daocloud.io",
    "https://docker.unsee.tech",
    "https://docker.1panel.live",
    "http://mirrors.ustc.edu.cn",
    "https://docker.chenby.cn",
    "http://mirror.azure.cn",
    "https://dockerpull.org",
    "https://dockerhub.icu",
    "https://hub.rat.dev"
  ]
}

chmod 777 /etc/systemd/system/docker.service
systemctl daemon-reload
systemctl start docker
systemctl status docker
systemctl enable docker.service

docker -v

拉取MySQL镜像

docker pull mysql
ocker pull mysql:8.0.43

创建目录
mkdir -p /data/dockerData/mysql/data
mkdir -p /data/dockerData/mysql/conf
mkdir -p /data/dockerData/mysql/logs
useradd -r -u 10000 mysql
chown -R mysql:mysql /mydata/dockerData/mysql

创建my.cnf
/data/dockerData/mysql/conf/my.cnf
chmod 644 /data/dockerData/mysql/conf/my.cnf

[mysqld]
port = 3306
bind-address = 0.0.0.0
datadir = /data/dockerData/mysql/data
character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci
# InnoDB 优化
innodb_buffer_pool_size = 1G
innodb_log_file_size = 256M
innodb_flush_log_at_trx_commit = 1
innodb_file_per_table = ON
# 连接与超时
max_connections = 200
wait_timeout = 600
interactive_timeout = 600
# 日志与安全
log_error = /data/dockerData/mysql/logs/mysql.log
slow_query_log = 1
slow_query_log_file = /data/dockerData/mysql/logs/slow_queries.log
log-bin = mysql-bin


创建MySQL容器

映射my.cnf文件
映射data目录

docker run --restart always \
--name mysql \
-p 33306:3306 \
--privileged=true \
-v /data/dockerData/mysql/logs:/var/log/mysql \
-v /data/dockerData/mysql/data:/var/lib/mysql \
-v /data/dockerData/mysql/conf/my.cnf:/etc/my.cnf \
-e MYSQL_ROOT_PASSWORD="root" \
-d mysql:8.0.43

方式二:也可以正确映射配置文件和数据目录


# 创建配置目录
mkdir -p /data/dockerData/mysql/conf.d

# 将你的 my.cnf 放到 conf.d 目录下
cp /data/dockerData/mysql/conf/my.cnf /data/dockerData/mysql/conf.d/

# 运行容器(映射整个配置目录)
docker run --restart always \
--name mysql \
-p 33306:3306 \
--privileged=true \
-v /data/dockerData/mysql/logs:/var/log/mysql \
-v /data/dockerData/mysql/data:/var/lib/mysql \
-v /data/dockerData/mysql/conf.d/:/etc/mysql/conf.d/ \
-e MYSQL_ROOT_PASSWORD="root" \
-d mysql:8.0.43

验证本地配置文件是否生效

[root@dockerser conf]# docker exec mysql mysql -uroot -proot -e "SHOW VARIABLES LIKE 'max_connections';"
mysql: [Warning] Using a password on the command line interface can be insecure.
Variable_name   Value
max_connections 300
[root@dockerser conf]# 
[root@dockerser conf]# docker exec mysql mysql -uroot -proot -e "SHOW VARIABLES LIKE 'port';"
mysql: [Warning] Using a password on the command line interface can be insecure.
Variable_name   Value
port    3306

修改用户的密码验证方式

ALTER USER root@'localhost' IDENTIFIED WITH mysql_native_password BY 'root';
ALTER USER root@'%' IDENTIFIED WITH mysql_native_password BY 'root';
FLUSH PRIVILEGES;

注释:
脱离cnf文件进行数据库参数配置
很多的配置选项可以通过标签flags传递到mysqld进程。这样用户就可以脱离cnf配置文件,对容器进行弹性的定制。比如,用户需要改变默认的编码方式,将所有的表格的编码方式修改为utf8mb4,则可以使用以下指令:
docker run --name mysql -e MYSQL_ROOT_PASSWORD=root -d mysql:8.0.42 --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci

如果需要查看可用选项的完整列表,则可以执行
docker run -it --rm mysql --verbose --help

[root@dockerser ~]# docker run -it --rm mysql --verbose --help
mysqld  Ver 9.5.0 for Linux on x86_64 (MySQL Community Server - GPL)
BuildID[sha1]=3201143e6c91b14935feebf586594725c98bcfcc
Copyright (c) 2000, 2025, 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.

Starts the MySQL database server.

Usage: mysqld [OPTIONS]

Default options are read from the following files in the given order:
/etc/my.cnf /etc/mysql/my.cnf /usr/etc/my.cnf ~/.my.cnf 
The following groups are read: mysql_cluster mysqld server mysqld-9.5
The following options may be given as the first argument:
--print-defaults        Print the program argument list and exit.
--no-defaults           Don't read default options from any option file,
                        except for login file.
--defaults-file=#       Only read default options from the given file #.
--defaults-extra-file=# Read this file after the global files are read.
--defaults-group-suffix=#
                        Also read groups with concat(group, suffix)
--login-path=#          Read this path from the login file.
--no-login-paths        Don't read login paths from the login path file.

  --activate-all-roles-on-login 
                      Automatically set all granted roles as active after the
                      user has authenticated successfully.
  --activate-mandatory-roles 
                      Automatically set all mandatory roles as active after the
                      user has authenticated successfully.
                      (Defaults to on; use --skip-activate-mandatory-roles to disable.)
  --admin-address=name 
                      IP address to bind to for service connection. Address can
                      be an IPv4 address, IPv6 address, or host name. Wildcard
                      values *, ::, 0.0.0.0 are not allowed. Address value can
                      have following optional network namespace separated by
                      the delimiter / from the address value. E.g., the
                      following value 192.168.1.1/red specifies IP addresses to
                      listen for incoming TCP connections that have to be
                                            placed into the namespace 'red'. Using of network
                      namespace requires its support from underlying Operating
                      System. Attempt to specify a network namespace for a
                      platform that doesn't support it results in error during
                      socket creation.
  --admin-port=#      Port number to use for service connection, built-in
                      default (33062)
  --admin-ssl-ca=name CA file in PEM format (check OpenSSL docs) for
                      --admin-port
  --admin-ssl-capath=name 
                      CA directory (check OpenSSL docs) for --admin-port
  --admin-ssl-cert=name 
                      X509 cert in PEM format for --admin-port
  --admin-ssl-cipher=name 
                      SSL cipher to use for --admin-port
  --admin-ssl-crl=name 
                      CRL file in PEM format (check OpenSSL docs) for
                      --admin-port
  --admin-ssl-crlpath=name 
                      CRL directory (check OpenSSL docs) for --admin-port
  --admin-ssl-key=name 
                      X509 key in PEM format for --admin-port
  --admin-tls-ciphersuites=name 
                      TLS v1.3 ciphersuite to use for --admin-port
  --admin-tls-version=name 
                      TLS version for --admin-port, permitted values are
                      TLSv1.2, TLSv1.3
  --allow-suspicious-udfs 
                      Allows use of UDFs consisting of only one symbol xxx()
                      without corresponding xxx_init() or xxx_deinit(). That
                      also means that one can load any function from any
                      library, for example exit() from libc.so
  -a, --ansi          Use ANSI SQL syntax instead of MySQL syntax. This mode
                      will also set transaction isolation level 'serializable'.
  --archive[=name]    Enable or disable ARCHIVE plugin. Possible values are ON,
                      OFF, FORCE (don't start if the plugin fails to load).
   --authentication-policy=name 
                      Defines policies around how user account can be
                      configured with Multi Factor authentication methods
                      during CREATE/ALTER USER statement. This variable accepts
                      at-most 3 comma separated list of authentication factor
                      descriptions. Allowed factor descriptions are: (empty) -
                      factor is optional, any authentication method is allowed.
                      * - factor is mandatory, any authentication method is
                      allowed. <plugin> - <plugin> is mandatory authentication
                      method. *:<plugin> - factor is mandatory, <plugin> is
                      default authentication method. The first factor cannot be
                      optional and if neither mandatory nor default method is
                      specified, caching_sha2_password is assumed as default.
  --auto-generate-certs 
                      Auto generate SSL certificates at server startup if none
                      of the other SSL system variables are specified and
                      certificate/key files are not present in data directory.
                      (Defaults to on; use --skip-auto-generate-certs to disable.)
  --auto-increment-increment[=#] 
                      Auto-increment columns are incremented by this
  --auto-increment-offset[=#] 
                      Offset added to Auto-increment columns. Used when
                      auto-increment-increment != 1
  --autocommit        Set default value for autocommit (0 or 1)
                      (Defaults to on; use --skip-autocommit to disable.)
  --automatic-sp-privileges 
                      Creating and dropping stored procedures alters ACLs
                      (Defaults to on; use --skip-automatic-sp-privileges to disable.)
  --back-log=#        The number of outstanding connection requests MySQL can
                      have. This comes into play when the main MySQL thread
                      gets very many connection requests in a very short time
  -b, --basedir=name  Path to installation directory. All paths are usually
                      resolved relative to this
  --big-tables        Allow big result sets by saving all temporary sets on
                      file (Solves most 'table full' errors)
  --binlog-do-db=name Include only updates to the specified database when
                      writing the binary log.
  --binlog-encryption Enable/disable binary and relay logs encryption.
  --binlog-error-action=name 
                      When statements cannot be written to the binary log due
                      to a fatal error, this option determines whether the
                      server ignores the error and closes the binary log, or
                      aborts.
  --binlog-expire-logs-auto-purge 
                      Controls whether the server shall automatically purge
                      binary log files or not. If this variable is set to FALSE
                      then the server will not purge binary log files
                      automatically.
                      (Defaults to on; use --skip-binlog-expire-logs-auto-purge to disable.)
  --binlog-expire-logs-seconds=# 
                      If non-zero, binary logs will be purged after
                      binlog_expire_logs_seconds seconds; Purges happen at
                      startup and at binary log rotation.
  --binlog-format=name 
                      The format used when writing the binary log. ROW writes
                      each changed row in a binary format. STATEMENT writes SQL
                      statements. MIXED writes SQL statements for most
                      statements, and row format for statements that cannot be
                      replayed in a deterministic manner using SQL. If
                      NDBCLUSTER is enabled and binlog-format is MIXED, the
                      format switches to row-based and back implicitly for each
                      query accessing an NDBCLUSTER table. This option is
                      deprecated and will be removed in a future version.
  --binlog-group-commit-sync-delay=# 
                      The number of microseconds the server waits for the
                      binary log group commit sync queue to fill before
                      continuing. Default: 0. Min: 0. Max: 1000000.


更多推荐