使用docker-compose同时启动MySQL和Redis

环境查看

image

安装docker和docker-compose

apt -y install docker.io docker-compose

设置docker-compose配置文件

root@iZ2zebcd9hncu1371fetliZ:/data/docker-compose# pwd
/data/docker-compose
root@iZ2zebcd9hncu1371fetliZ:/data/docker-compose# cat docker-compose.yml
version: '2.0'
services:
  mysql:
    hostname: mysql
    image: container-registry.oracle.com/mysql/community-server:8.0.32
    ports:
      - 13306:3306
    volumes:
      - ./mysql/conf:/etc/mysql/conf.d
      - ./mysql/data:/var/lib/mysql
      - ./mysql/log:/var/log/mysql
      - /etc/localtime:/etc/localtime:ro
      - /etc/timezone:/etc/timezone:ro
    environment:
      MYSQL_ROOT_PASSWORD: password
      #MYSQL_DATABASE:
      #MYSQL_USER: root
      #MYSQL_PASSWORD: ioYbcZ1u

  redis:
    hostname: redis
    image: redis
    environment:
      REDIS_PASSWORD: Apple2022#*
    ports:
      - 16379:6379
    volumes:
      - /etc/localtime:/etc/localtime:ro
      - /etc/timezone:/etc/timezone:ro
    command: ["redis-server", "--appendonly", "yes", "--requirepass","password"]

注意MySQL和Redis设置密码的方式

启动

docker-compose up -d

查看是否启动

image

连接MySQL容器设置管理员密码

默认无法通过远程连接所以需要先连接容器设置密码

docker exec -it docker-compose_mysql_1 /bin/bash
#进入容器之后操作
mysql -uroot -p'password'
CREATE USER 'root'@'%' IDENTIFIED BY 'password';
grant all on *.* to 'root'@'%';
flush privileges

2024-11-15补充开始
写一个简单一点的脚本同时启动MySQL8和Redis7

version: '3.8'

services:
  mysql:
    image: mysql:8.0
    container_name: mysql_container
    environment:
      MYSQL_ROOT_PASSWORD: ROOT_PASSWORD # 替换为你的MySQL root密码
      MYSQL_DATABASE: mydatabase               # 可选:创建一个初始数据库
      MYSQL_USER: username                       # 可选:创建一个初始用户
      MYSQL_PASSWORD: USERNAME_PASSWORD          # 替换为你的MySQL用户密码
    ports:
      - "3306:3306"
    volumes:
      - ./mysql_data:/var/lib/mysql
      - ./mysql-init-scripts:/docker-entrypoint-initdb.d  # 可选:用于初始化数据库的脚本

  redis:
    image: redis:7.0
    container_name: redis_container
    command: ["redis-server", "--requirepass", "REDIS_PASSWORD"]  # 替换为你的Redis密码
    ports:
      - "6379:6379"
    volumes:
      - ./redis_data:/data

volumes:
  mysql_data:
  redis_data:

在当前目录创建持久化存储目录mysql_data,redis_data
启动即可使用

# docker-compose up -d

2024-11-15补充结束

posted @ 2023-06-20 13:59  minseo  阅读(187)  评论(0编辑  收藏  举报