使用docker安装mysql和redis

时间:2022-01-12 14:05:08

本文介绍在linux下使用docker安装mysql和redis。

原文地址:代码汇个人博客 http://www.codehui.net/info/59.html

测试环境:centos7.6,docker 18.09.1

首先要确保docker环境已经安装成功

[root@localhost ~]# docker --version
Docker version 18.09.2, build 6247962

Docker 安装 Mysql

  • 安装镜像

直接跳过docker search mysql这一步,我们直接安装官方mysql5.5的镜像

[root@localhost ~]# docker pull mysql:5.5

安装完成查看本地镜像,标签名为5.5

[root@localhost ~]# docker images mysql
REPOSITORY TAG IMAGE ID CREATED SIZE
mysql 5.5 50ba61f07d0c 7 days ago 205MB
  • 运行容器
[root@localhost ~]# docker run -p 3306:3306 -d --name mymysql -v /docker/mysql/data:/usr/share/mysql -e MYSQL_ROOT_PASSWORD=123456 mysql:5.5
979542f0c201ed229a548a260cd3bf0d8fbafb99ecb3e75e74cdc302358575f6

-p 3306:3306:将容器的 3306 端口映射到主机的 3306 端口。

-v /docker/mysql/data:/usr/share/mysql:将主机当前目录下的data目录挂载到容器的 /var/lib/mysql 。

-e MYSQL_ROOT_PASSWORD=123456:初始化 root 用户的密码。

  • 查看容器运行情况
[root@localhost ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
979542f0c201 mysql:5.5 "docker-entrypoint.sh" 2 minutes ago Up 2 minutes 0.0.0.0:3306->3306/tcp mymysql
  • 使用mysql
[root@localhost ~]# docker exec -it mymysql bash
root@979542f0c201:/# mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.5.62 MySQL Community Server (GPL) Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved. 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>

Docker 安装 Redis

  • 安装镜像

这里安装redis3.2的官方镜像版本

[root@localhost ~]# docker pull  redis:3.2

安装完成查看本地镜像,标签名为3.2

[root@localhost ~]# docker images redis
REPOSITORY TAG IMAGE ID CREATED SIZE
redis 3.2 87856cc39862 4 months ago 76MB
  • 运行容器
[root@localhost ~]# docker run -p 6379:6379 -d --name myredis -v /docker/redis/data:/data redis:3.2 redis-server --appendonly yes
84631392a9fab37c08976673c75a701687bfe6a3443209db92a19bab8e107b6b

-p 6379:6379 将容器的6379端口映射到主机的6379端口

-v /docker/redis/data:/data: 将主机中当前目录下的data挂载到容器的/data

redis-server --appendonly yes: 在容器执行redis-server启动命令,并打开redis持久化配置

  • 查看容器运行情况
[root@localhost ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
84631392a9fa redis:3.2 "docker-entrypoint.s猞" 16 seconds ago Up 13 seconds 0.0.0.0:6379->6379/tcp myredis
979542f0c201 mysql:5.5 "docker-entrypoint.s猞" 14 minutes ago Up 14 minutes 0.0.0.0:3306->3306/tcp mymysql
  • 使用redis
[root@localhost ~]# docker exec -it myredis redis-cli
127.0.0.1:6379> ping
PONG