1. Prepare Host Directories
First, create the necessary directories on your host machine to store MySQL data, logs, and configuration files. This ensures data persistence evenif the container is removed.
mkdir -p /opt/mysql/data
mkdir -p /opt/mysql/logs
mkdir -p /opt/mysql/conf
2. Create a Custom Configuration File
Create a configuration file within the conf directory to customize MySQL settings. For example, create a file named my-custom.cnf.
[mysqld]
character-set-server=utf8mb4
collation-server=utf8mb4_unicode_ci
max_connections=200
bind-address=0.0.0.0
3. Run the MySQL Container
Now, you can start the MySQL container. The command below pulls the official MySQL image (if not already present) and runs a new container instance with the specified configurations.
docker run --name mysql-instance \
--restart=always \
-e MYSQL_ROOT_PASSWORD=secure_password_123 \
-e TZ=Asia/Shanghai \
-p 3306:3306 \
-v /opt/mysql/data:/var/lib/mysql \
-v /opt/mysql/logs:/var/log/mysql \
-v /opt/mysql/conf/my-custom.cnf:/etc/mysql/conf.d/custom.cnf \
-d mysql:8.0
This single command performs several actions:
--name mysql-instance: Assigns a memorable name to the container for easy management.--restart=always: Ensures the container automatically restarts upon system reboot or failure.-e MYSQL_ROOT_PASSWORD=...: Sets the root user's password using an environment variable.-e TZ=Asia/Shanghai: Sets the correct timezone for the container.-p 3306:3306: Maps port 3306 of the container to port 3306 on the host, allowing external access.-v /opt/mysql/data:/var/lib/mysql: Mounts the host's data directory to the container's data directory, persisting database files.-v /opt/mysql/logs:/var/log/mysql: Mounts the host's log directory to the container's log directory for easy log access.-v /opt/mysql/conf/my-custom.cnf:/etc/mysql/conf.d/custom.cnf: Mounts the custom configuration file, allowing you to override default MySQL settings.-d mysql:8.0: Runs the container in detached mode and specifies the MySQL 8.0 image.