docker搭建mysql

使用docker来搭建mysql

1. 使用docker run 的方式创建

  1. 创建配置文件目录

    1
    2
    mkdir -p /opt/docker-data/mysql/datadir
    mkdir -p /opt/docker-data/mysql/init
  2. 容器初始化脚本(可选,起来后执行的脚本)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    vim /opt/docker-data/mysql/init/01_create_init.sql

    --用来创建多个用户和数据库

    CREATE DATABASE IF NOT EXISTS gitea DEFAULT CHARSET utf8 COLLATE utf8_general_ci;

    drop user 'gitea'@'%';

    create user 'gitea'@'%' identified by '12345678';

    grant all privileges on gitea.* to 'gitea'@'%' with grant option;

    flush privileges;
  3. 拉取镜像

    1
    [root@zmr-service opt]# docker pull mysql/mysql-server:8.0.32
  4. 创建需要的nginx容器

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    # 暴露自己需要的端口
    docker run -d --name mysql \
    --restart=always \
    -v /opt/docker-data/mysql/datadir:/var/lib/mysql \
    -v /opt/docker-data/mysql/init:/docker-entrypoint-initdb.d\
    -e MYSQL_ROOT_PASSWORD=12345678 \
    -e MYSQL_DATABASE=nextclud \
    -e MYSQL_USER=nextcloud \
    -e MYSQL_PASSWORD=12345678 \
    -e LC_ALL="en_US.UTF-8" \
    -e TZ="Asia/Shanghai" \
    -p 3306:3306\
    mysql/mysql-server:latest

2. 使用docker-compose的方式创建

.env

1
COMPOSE_PROJECT_NAME=app

docker-compose.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
version: '3'

services:
db:
image: mysql/mysql-server:8.0.32
restart: always
container_name: "mysql8"
# ports:
# - 3306:3306
environment:
MYSQL_ROOT_PASSWORD: 12345678
MYSQL_DATABASE: gitea
MYSQL_USER: gitea
MYSQL_PASSWORD: 12345678
LC_ALL: "en_US.UTF-8"
TZ: "Asia/Shanghai"
volumes:
- "/opt/docker-data/mysql/datadir:/var/lib/mysql"
- "/opt/docker-data/mysql/init:/docker-entrypoint-initdb.dl"
command: --default-authentication-plugin=mysql_native_password
networks:
- net

networks: # 这里创建了一个 app_net的网络,后面如果有容器需要mysql,可直接继承这个网络
net:
driver: bridge