Running MySQL with docker compose

  • 2021-06-28 14:28:00
  • OfStack

directory structure


.
 C  .env
 C  docker-compose.yml
 C 
 - mysql
  - config
  C  my.cnf
  C 
  - data

data in the mysql directory is the data directory where the mysql tables and binary log files are located.The env file contains a number of variables that can be used in the docker-compose.yml Passed in file ${variable_name} To reference.

Of course, you can also place the directory of mysql somewhere else. The picture here is convenient, and it is directly placed in the directory of the same level as the yml file.

.env file


MYSQL_ROOT_PASSWORD=root
MYSQL_ROOT_HOST=%
MYSQL_DIR=./mysql

MySQL Profile my.cnf


[mysqld]
character-set-server=utf8mb4
default-time-zone='+8:00'
innodb_rollback_on_timeout='ON'
max_connections=500
innodb_lock_wait_timeout=500

This file can be omitted if the default configuration is used.

docker-compose.yml


version: '3'

services:

 mysql-db:
 container_name: mysql-docker #  Specify the name of the container 
 image: mysql:8.0   #  Specify mirror and version 
 ports:
 - "3306:3306"
 environment:
 MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
 MYSQL_ROOT_HOST: ${MYSQL_ROOT_HOST}
 volumes:
 - "${MYSQL_DIR}/data:/var/lib/mysql"  #  Mount Data Directory 
 - "${MYSQL_DIR}/config:/etc/mysql/conf.d" #  Mount Profile Directory 

Environment variable

MYSQL_ROOT_PASSWORD: There is no explanation for this, the password of the root user. MYSQL_USER, MYSQL_PASSWORD: These two variables are optional, creating a new user at MYSQL_Superuser privileges on the database specified by the DATABASE variable. MYSQL_DATABASE: Specify a database to be created at container startup. MYSQL_ALLOW_EMPTY_PASSWORD: Set to yes to allow root users to have blank passwords. (Not recommended) MYSQL_RANDOM_ROOT_PASSWORD: Setting yes will generate a random password for root users at container startup, which will be displayed in the standard output stream (GENERATED ROOT PASSWORD:...). MYSQL_ONETIME_PASSWORD: Literally means a one-time password, which is set for root users and must be changed after the first login (only versions above 5.6 are supported).

Run Container

Execute in the docker-compose.yml directory:

> docker-compose up

If you want to run in the background, use docker-compose up -d .

Stop container:

> docker-compose down

If it is running in the foreground, stop using: Ctrl + C.Both methods delete the container after stopping, and the next boot must use the up command.

Stop without deleting the container:

> docker-compose stop

After stopping with stop, start using the start command again.

summary


Related articles: