docker run mysql 如果不指定 -e(-env) 环境变量参数, 则容器无法启动, 用 docker logs 容器名 可看到报错日志, 如:

root@102pve-u2441f:/DockerPodmanSaveLoadImages# docker logs Mysql3307
2024-11-24 16:08:48+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.4.3-1.el9 started.
2024-11-24 16:08:48+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
2024-11-24 16:08:48+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.4.3-1.el9 started.
2024-11-24 16:08:48+00:00 [ERROR] [Entrypoint]: Database is uninitialized and password option is not specified
   You need to specify one of the following as an environment variable:
   - MYSQL_ROOT_PASSWORD
   - MYSQL_ALLOW_EMPTY_PASSWORD
   - MYSQL_RANDOM_ROOT_PASSWORD

可看到 三个可选变量

- MYSQL_ROOT_PASSWORD  设置root的密码
- MYSQL_ALLOW_EMPTY_PASSWORD    允许无密码
- MYSQL_RANDOM_ROOT_PASSWORD    随机密码

复制用模板
MYSQL_ROOT_PASSWORD

MYSQL_ROOT_PASSWORD
-e MYSQL_ROOT_PASSWORD=NoSpace
--env MYSQL_ROOT_PASSWORD='password'

MYSQL_ALLOW_EMPTY_PASSWORD=root

MYSQL_ALLOW_EMPTY_PASSWORD=root
MYSQL_ALLOW_EMPTY_PASSWORD='root'
-e MYSQL_ALLOW_EMPTY_PASSWORD=root
--env MYSQL_ALLOW_EMPTY_PASSWORD='root'

例子

sudo docker run -dp 3307:3306 --name Mysql3307  -e MYSQL_ROOT_PASSWORD='root的密码'  mysql:latest
### root无密码
sudo docker run -dp 57:3306  --name Mysql57  --env MYSQL_ALLOW_EMPTY_PASSWORD='root'  mysql:5.7

官网列出的一些环境变量 https://hub.docker.com/_/mysql?tab=description

Environment Variables (docker run -e 的环境变量)

When you start the mysql image, you can adjust the configuration of the MySQL instance by passing one or more environment variables on the docker run command line. Do note that none of the variables below will have any effect if you start the container with a data directory that already contains a database: any pre-existing database will always be left untouched on container startup.

See also https://dev.mysql.com/doc/refman/5.7/en/environment-variables.html for documentation of environment variables which MySQL itself respects (especially variables like MYSQL_HOST, which is known to cause issues when used with this image).

  • MYSQL_ROOT_PASSWORD
    This variable is mandatory and specifies the password that will be set for the MySQL root superuser account. In the above example, it was set to my-secret-pw.

  • MYSQL_DATABASE
    This variable is optional and allows you to specify the name of a database to be created on image startup. If a user/password was supplied (see below) then that user will be granted superuser access (corresponding to GRANT ALL) to this database.

  • MYSQL_USER, MYSQL_PASSWORD
    These variables are optional, used in conjunction to create a new user and to set that user’s password. This user will be granted superuser permissions (see above) for the database specified by the MYSQL_DATABASE variable. Both variables are required for a user to be created.

Do note that there is no need to use this mechanism to create the root superuser, that user gets created by default with the password specified by the MYSQL_ROOT_PASSWORD variable.

  • MYSQL_ALLOW_EMPTY_PASSWORD
    This is an optional variable. Set to a non-empty value, like yes, to allow the container to be started with a blank password for the root user. NOTE: Setting this variable to yes is not recommended unless you really know what you are doing, since this will leave your MySQL instance completely unprotected, allowing anyone to gain complete superuser access.

  • MYSQL_RANDOM_ROOT_PASSWORD
    This is an optional variable. Set to a non-empty value, like yes, to generate a random initial password for the root user (using pwgen). The generated root password will be printed to stdout (GENERATED ROOT PASSWORD: …).

  • MYSQL_ONETIME_PASSWORD
    Sets root (not the user specified in MYSQL_USER!) user as expired once init is complete, forcing a password change on first login. Any non-empty value will activate this setting. NOTE: This feature is supported on MySQL 5.6+ only. Using this option on MySQL 5.5 will throw an appropriate error during initialization.

  • MYSQL_INITDB_SKIP_TZINFO
    By default, the entrypoint script automatically loads the timezone data needed for the CONVERT_TZ() function. If it is not needed, any non-empty value disables timezone loading.

Docker Secrets
As an alternative to passing sensitive information via environment variables, _FILE may be appended to the previously listed environment variables, causing the initialization script to load the values for those variables from files present in the container. In particular, this can be used to load passwords from Docker secrets stored in /run/secrets/<secret_name> files. For example:

$ docker run --name some-mysql -e MYSQL_ROOT_PASSWORD_FILE=/run/secrets/mysql-root -d mysql:tag
Currently, this is only supported for MYSQL_ROOT_PASSWORD, MYSQL_ROOT_HOST, MYSQL_DATABASE, MYSQL_USER, and MYSQL_PASSWORD.




Deploying MySQL on Linux with Docker : 在Linux上用docker部署MySQL : https://dev.mysql.com/doc/refman/8.0/en/linux-installation-docker.html

MySQL官方文档对dockers关于mysql的环境变量的说明

Docker Environment Variables
When you create a MySQL Server container, you can configure the MySQL instance by using the --env option (short form -e) and specifying one or more environment variables. No server initialization is performed if the mounted data directory is not empty, in which case setting any of these variables has no effect (see Persisting Data and Configuration Changes), and no existing contents of the directory, including server settings, are modified during container startup.

Environment variables which can be used to configure a MySQL instance are listed here:

The boolean variables including MYSQL_RANDOM_ROOT_PASSWORD, MYSQL_ONETIME_PASSWORD, MYSQL_ALLOW_EMPTY_PASSWORD, and MYSQL_LOG_CONSOLE are made true by setting them with any strings of nonzero lengths. Therefore, setting them to, for example, “0”, “false”, or “no” does not make them false, but actually makes them true. This is a known issue.

MYSQL_RANDOM_ROOT_PASSWORD: When this variable is true (which is its default state, unless MYSQL_ROOT_PASSWORD is set or MYSQL_ALLOW_EMPTY_PASSWORD is set to true), a random password for the server’s root user is generated when the Docker container is started. The password is printed to stdout of the container and can be found by looking at the container’s log (see Starting a MySQL Server Instance).

MYSQL_ONETIME_PASSWORD: When the variable is true (which is its default state, unless MYSQL_ROOT_PASSWORD is set or MYSQL_ALLOW_EMPTY_PASSWORD is set to true), the root user’s password is set as expired and must be changed before MySQL can be used normally.

MYSQL_DATABASE: This variable allows you to specify the name of a database to be created on image startup. If a user name and a password are supplied with MYSQL_USER and MYSQL_PASSWORD, the user is created and granted superuser access to this database (corresponding to GRANT ALL). The specified database is created by a CREATE DATABASE IF NOT EXIST statement, so that the variable has no effect if the database already exists.

MYSQL_USER, MYSQL_PASSWORD: These variables are used in conjunction to create a user and set that user’s password, and the user is granted superuser permissions for the database specified by the MYSQL_DATABASE variable. Both MYSQL_USER and MYSQL_PASSWORD are required for a user to be created—if any of the two variables is not set, the other is ignored. If both variables are set but MYSQL_DATABASE is not, the user is created without any privileges.

Note
There is no need to use this mechanism to create the root superuser, which is created by default with the password set by either one of the mechanisms discussed in the descriptions for MYSQL_ROOT_PASSWORD and MYSQL_RANDOM_ROOT_PASSWORD, unless MYSQL_ALLOW_EMPTY_PASSWORD is true.

MYSQL_ROOT_HOST: By default, MySQL creates the ‘root’@‘localhost’ account. This account can only be connected to from inside the container as described in Connecting to MySQL Server from within the Container. To allow root connections from other hosts, set this environment variable. For example, the value 172.17.0.1, which is the default Docker gateway IP, allows connections from the host machine that runs the container. The option accepts only one entry, but wildcards are allowed (for example, MYSQL_ROOT_HOST=172...* or MYSQL_ROOT_HOST=%).

MYSQL_LOG_CONSOLE: When the variable is true (which is its default state for MySQL 8.0 server containers), the MySQL Server’s error log is redirected to stderr, so that the error log goes into the Docker container’s log and is viewable using the docker logs mysqld-container command.

Note
The variable has no effect if a server configuration file from the host has been mounted (see Persisting Data and Configuration Changes on bind-mounting a configuration file).

MYSQL_ROOT_PASSWORD: This variable specifies a password that is set for the MySQL root account.

Warning
Setting the MySQL root user password on the command line is insecure. As an alternative to specifying the password explicitly, you can set the variable with a container file path for a password file, and then mount a file from your host that contains the password at the container file path. This is still not very secure, as the location of the password file is still exposed. It is preferable to use the default settings of MYSQL_RANDOM_ROOT_PASSWORD and MYSQL_ONETIME_PASSWORD both being true.

MYSQL_ALLOW_EMPTY_PASSWORD. Set it to true to allow the container to be started with a blank password for the root user.

Warning
Setting this variable to true is insecure, because it is going to leave your MySQL instance completely unprotected, allowing anyone to gain complete superuser access. It is preferable to use the default settings of MYSQL_RANDOM_ROOT_PASSWORD and MYSQL_ONETIME_PASSWORD both being true.




MySQL自身的环境变量

VariableDescription
AUTHENTICATION_KERBEROS_CLIENT_LOGKerberos authentication logging level.
AUTHENTICATION_LDAP_CLIENT_LOGClient-side LDAP authentication logging level.
AUTHENTICATION_PAM_LOGPAM authentication plugin debug logging settings.
CCThe name of your C compiler (for running CMake).
CXXThe name of your C++ compiler (for running CMake).
CCThe name of your C compiler (for running CMake).
DBI_USERThe default user name for Perl DBI.
DBI_TRACETrace options for Perl DBI.
HOMEThe default path for the mysql history file is $HOME/.mysql_history.
LD_RUN_PATHUsed to specify the location of libmysqlclient.so.
LIBMYSQL_ENABLE_CLEARTEXT_PLUGINEnable mysql_clear_password authentication plugin; see Section 6.4.1.4, “Client-Side Cleartext Pluggable Authentication”.
LIBMYSQL_PLUGIN_DIRDirectory in which to look for client plugins.
LIBMYSQL_PLUGINSClient plugins to preload.
MYSQL_DEBUGDebug trace options when debugging.
MYSQL_GROUP_SUFFIXOption group suffix value (like specifying --defaults-group-suffix).
MYSQL_HISTFILEThe path to the mysql history file. If this variable is set, its value overrides the default for $HOME/.mysql_history.
MYSQL_HISTIGNOREPatterns specifying statements that mysql should not log to $HOME/.mysql_history, or syslog if --syslog is given.
MYSQL_HOMEThe path to the directory in which the server-specific my.cnf file resides.
MYSQL_HOSTThe default host name used by the mysql command-line client.
MYSQL_OPENSSL_UDF_DH_BITS_THRESHOLDMaximum key length for create_dh_parameters(). See Section 6.6.3, “MySQL Enterprise Encryption Usage and Examples”.
MYSQL_OPENSSL_UDF_DSA_BITS_THRESHOLDMaximum DSA key length for create_asymmetric_priv_key(). See Section 6.6.3, “MySQL Enterprise Encryption Usage and Examples”.
MYSQL_OPENSSL_UDF_RSA_BITS_THRESHOLDMaximum RSA key length for create_asymmetric_priv_key(). See Section 6.6.3, “MySQL Enterprise Encryption Usage and Examples”.
MYSQL_PS1The command prompt to use in the mysql command-line client.
MYSQL_PWDThe default password when connecting to mysqld. Using this is insecure. See note following table.
MYSQL_TCP_PORTThe default TCP/IP port number.
MYSQL_TEST_LOGIN_FILEThe name of the .mylogin.cnf login path file.
MYSQL_TEST_TRACE_CRASHWhether the test protocol trace plugin crashes clients. See note following table.
MYSQL_TEST_TRACE_DEBUGWhether the test protocol trace plugin produces output. See note following table.
MYSQL_UNIX_PORTThe default Unix socket file name; used for connections to localhost.
MYSQLX_TCP_PORTThe X Plugin default TCP/IP port number.
MYSQLX_UNIX_PORTThe X Plugin default Unix socket file name; used for connections to localhost.
NOTIFY_SOCKETSocket used by mysqld to communicate with systemd.
PATHUsed by the shell to find MySQL programs.
PKG_CONFIG_PATHLocation of mysqlclient.pc pkg-config file. See note following table.
TMPDIRThe directory in which temporary files are created.
TZThis should be set to your local time zone. See Section B.3.3.7, “Time Zone Problems”.
UMASKThe user-file creation mode when creating files. See note following table.
UMASK_DIRThe user-directory creation mode when creating directories. See note following table.
USERThe default user name on Windows when connecting to mysqld.







MYSQL_RANDOM_ROOT_PASSWORD

MYSQL_RANDOM_ROOT_PASSWORD 是一个环境变量,通常在 Docker 或其他容器化环境中使用,用于在容器启动时自动生成 MySQL 数据库的 root 用户密码。这个特性增强了数据库的安全性,因为它避免了使用默认的或易于猜测的密码,从而减少了数据库被未授权访问的风险。

当你在 Docker 容器或 Kubernetes Pod 中部署 MySQL 服务时,可以通过设置这个环境变量来让 MySQL 容器在启动时自动生成一个随机的 root 密码。这个密码随后可以通过容器的日志或特定的命令来获取,以便数据库管理员或应用程序可以使用它来连接到数据库。

使用 MYSQL_RANDOM_ROOT_PASSWORD 的好处包括:

  1. 提高安全性:自动生成的密码通常是复杂且难以预测的,这大大增加了数据库的安全性。
  2. 简化管理:管理员不需要手动为每个数据库实例设置和记住密码,这简化了数据库的管理。
  3. 自动化部署:在自动化部署流程中,使用这种机制可以很容易地为每个新部署的数据库实例生成唯一的密码,而无需人工干预。

然而,使用这种机制时也需要注意以下几点:

  • 密码获取:需要确保有合适的方法来获取和使用这个自动生成的密码,例如通过容器的日志、环境变量或特定的管理接口。
  • 密码存储:生成的密码应该安全地存储和管理,以便在需要时可以访问,同时也防止泄露给未授权的用户。
  • 密码更新:在获取到随机生成的密码后,出于安全考虑,可能需要定期更新这个密码。

总之,MYSQL_RANDOM_ROOT_PASSWORD 是一个有用的特性,可以帮助提高数据库部署的安全性和便利性,但在使用时也需要注意密码的管理和安全性。

关于MYSQL_RANDOM_ROOT_PASSWORD的具体用法,实际上在标准的 MySQL 文档或官方资料中并没有直接提及这个环境变量。通常,在 Docker 容器化环境中部署 MySQL 时,会使用 MYSQL_ROOT_PASSWORD 环境变量来设置 root 用户的密码。这个环境变量如果被设置为非空值,MySQL 容器在启动时就会使用这个值作为 root 用户的密码。

然而,如果你提到的 MYSQL_RANDOM_ROOT_PASSWORD 是在某个特定的上下文或工具中使用的,那么它的用法可能会有所不同。但基于一般的理解,这里可以提供一个假设性的用法,以及如何在 Docker 容器中使用 MYSQL_ROOT_PASSWORD 来设置 root 用户密码的示例。

假设性的 MYSQL_RANDOM_ROOT_PASSWORD 用法

如果 MYSQL_RANDOM_ROOT_PASSWORD 被设计为自动生成 root 密码的环境变量,它可能在容器启动时被某个脚本或容器化工具读取,然后生成一个随机密码,并设置给 MySQL 的 root 用户。但请注意,这只是一个假设性的描述,实际用法可能因具体实现而异。

使用 MYSQL_ROOT_PASSWORD 设置 MySQL root 密码

在 Docker 容器中部署 MySQL 时,可以通过以下步骤使用 MYSQL_ROOT_PASSWORD 环境变量来设置 root 用户密码:

  1. 编写 Docker Compose 文件(如果使用 Docker Compose 进行部署):

    version: '3'
    services:
      mysql:
        image: mysql:latest
        environment:
          MYSQL_ROOT_PASSWORD: your_secure_password
        ports:
          - "3306:3306"
        volumes:
          - mysql_data:/var/lib/mysql
    
    volumes:
      mysql_data:
    

    在上面的示例中,MYSQL_ROOT_PASSWORD 被设置为 your_secure_password。你应该将其替换为一个复杂且难以猜测的密码。

  2. 运行 Docker 容器(如果不使用 Docker Compose):

    docker run --name mysql-container -e MYSQL_ROOT_PASSWORD=your_secure_password -d mysql:latest
    

    在这个命令中,-e MYSQL_ROOT_PASSWORD=your_secure_password 部分设置了环境变量,并指定了 root 用户的密码。

  3. 连接到 MySQL 容器

    容器启动后,你可以使用以下命令连接到 MySQL 容器:

    docker exec -it mysql-container mysql -u root -p
    

    系统会提示你输入密码,输入你在 MYSQL_ROOT_PASSWORD 环境变量中设置的密码即可。

注意事项

  • 密码安全:确保设置的密码足够复杂且难以猜测,以提高数据库的安全性。
  • 环境变量管理:在生产环境中,避免在命令行或配置文件中明文存储密码。考虑使用环境变量管理工具或秘密管理系统来安全地存储和管理密码。
  • 定期更新密码:为了进一步提高安全性,建议定期更新 root 用户的密码。

如果你确实在某个特定的上下文或工具中遇到了 MYSQL_RANDOM_ROOT_PASSWORD,建议查阅该上下文或工具的官方文档以获取准确的用法和指导。































Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐