macos: 用docker安装mysql

一,创建mysql用到的目录

% pwd
/Users/apple/Documents/docker_setting/mysql 
% mkdir data
% mkdir conf.d

二,创建compose配置文件:

生成compose文件

% touch docker-compose.yml

内容:

services:
  mysql:
    image: mysql:8.0
    container_name: my-mysql
    restart: always
    ports:
      - "3306:3306"
    environment:
      # 设置 root 用户的初始密码(请修改为你的强密码)
      MYSQL_ROOT_PASSWORD: rootpassword
      # 可选:创建一个初始的默认数据库
      MYSQL_DATABASE: my_base
    volumes:
      # 将数据挂载到 Mac 本地,防止容器删除后数据丢失
      - ./data:/var/lib/mysql
      # 将自定义配置文件挂载进容器
      - ./conf.d:/etc/mysql/conf.d
    command: --default-authentication-plugin=mysql_native_password

三,启动服务:

% docker-compose up -d

如下:

 % docker-compose up -d
[+] up 16/16
 ✔ Image mysql:8.0       Pulled                                                                                     349.7s
 ✔ Network mysql_default Created                                                                                      0.0s
 ✔ Container my-mysql    Started                                                                                      0.8s
apple@bogon mysql % docker image ls     
                                                                                                     i Info →   U  In Use
IMAGE                ID             DISK USAGE   CONTENT SIZE   EXTRA
hello-world:latest   5e2309035332       25.9kB         9.49kB    U   
mysql:8.0            7dcddc01f13b        1.1GB          249MB    U   
nginx:latest         cb29e33d254e        253MB         69.2MB    U   
apple@bogon mysql % docker ps      
CONTAINER ID   IMAGE          COMMAND                   CREATED          STATUS          PORTS                                         NAMES
3c31fc84f1cc   mysql:8.0      "docker-entrypoint.s…"   14 minutes ago   Up 14 minutes   0.0.0.0:3306->3306/tcp, [::]:3306->3306/tcp   my-mysql
3674444fe600   nginx:latest   "/docker-entrypoint.…"   2 hours ago      Up 24 minutes   0.0.0.0:8080->80/tcp, [::]:8080->80/tcp       my-nginx

四,验证结果:

执行如下命令:

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

如下:

 % docker exec -it my-mysql mysql -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 9
Server version: 8.0.46 MySQL Community Server - GPL

Copyright (c) 2000, 2026, 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.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> 
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| my_base            |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
5 rows in set (0.01 sec)

 

posted @ 2026-09-18 23:39  刘宏缔的架构森林  阅读(7)  评论(0)    收藏  举报