1.下载
项目环境
cd /data/docker/ubuntu/
mkdir mysql
Dockerfile内容为:
FROM sshd:dockerfile
MAINTAINER from www.csdn.com/wanchaopeng by wanchaopeng ([email protected])
#安装软件
ENV DEBIAN_FRONTEND noninteractive
RUN apt-get update && \
apt-get -yq install mysql-server-5.6 pwgen && \
rm -rf /var/lib/apt/lists/*
# 删除预安装的数据库文件
RUN rm -rf /var/lib/mysql/*
# 添加文件夹下的 MYSQL 配置文件
ADD my.cnf /etc/mysql/conf.d/my.cnf
ADD mysqld_charset.cnf /etc/mysql/conf.d/mysqld_charset.cnf
# 添加 MYSQL 的脚本
ADD import_sql.sh /import_sql.sh
ADD run.sh /run.sh
RUN chmod 755 /*.sh
# 设置环境变量,用户名以及秘密
ENV MYSQL_USER admin
ENV MYSQL_PASS **Random**
# 设置主从复制模式下的环境变量
ENV REPLICATION_MASTER **False**
ENV REPLICATION_SLAVE **False**
ENV REPLICATION_USER replica
ENV REPLICATION_PASS replica
# 设置可以允许挂载的卷,可以用来备份数据库和配置文件
VOLUME ["/etc/mysql", "/var/lib/mysql"]
# 设置可以映射的端口,如果是从我们的 sshd 镜像继承的话,默认还会开启 22 端口
EXPOSE 3306
CMD ["/run.sh"]
2. 创建镜像
docker build -t mysql:ubuntu .
3. 使用镜像
使用默认方式启动后台容器,不添加环境变量,并使用-P 参数自动映射22和3306端口
docker run -d -P mysql:ubuntu
检查
[root@ybsrv1 /data/docker/ubuntu/mysql]# docker ps
c2626bae59fc mysql:ubuntu "/run.sh" 2 hours ago Up 2 hours 0.0.0.0:32817->22/tcp, 0.0.0.0:32816->3306/tcp reverent_fermat
通过ssh登陆docker容器
ssh 127.0.0.1 -p 32817
使用mysql直接登陆
查看admin账号的密码
[root@ybsrv1 /data/docker/ubuntu/mysql]# docker logs c262
=> An empty or uninitialized MySQL volume is detected in /var/lib/mysql
=> Installing MySQL ...
=> Done!
=> Creating admin user ...
=> Waiting for confirmation of MySQL service startup, trying 0/13 ...
=> Creating MySQL user admin with random password
=> Done!
========================================================================
You can now connect to this MySQL Server using:
mysql -uadmin -pHNotI6if75YX -h -P
Please remember to change the above password as soon as possible!
MySQL user 'root' has no password but only allows local connections
========================================================================
190507 03:30:51 mysqld_safe Can't log to error log and syslog at the same time. Remove all --log-error configuration options for --syslog to take effect.
190507 03:30:51 mysqld_safe Logging to '/var/log/mysql/error.log'.
190507 03:30:51 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
密码是:HNotI6if75YX
4. 指定admin账号用户名和密码
docker run -d -P -e MYSQL_PASS="mmxcard" mysql:ubuntu
5. 挂载目录到容器
docker run -d -P -v /opt/mysqldb:/var/lib/mysql mysql:ubuntu
本地的/opt/mysqldb存放/var/lib/mysql
6. 启动主动模式
主从可以为数据库提供更好的可靠性
创建一个mysql的主容器
docker run -d -e REPLICATION_MASTER=true -P --name mysql mysql:ubuntu
创建一个mysql从容器
docker run -d -e REPLICATION_SLAVE=true -P --link mysql:mysql mysql:ubuntu
主容器必须是mysql
7. 使用docker-compose 启动docker容器
vim docker-compose.yaml
#
version: '2'
services:
mysql:
image: mysql:5.7
container_name: mysql
ports:
- 8706:3306
restart: always
environment:
MYSQL_ROOT_PASSWORD: sa
volumes:
- /etc/localtime:/etc/localtime:ro
- /u01/mysql/datadir:/var/lib/mysql
- /u01/mysql/conf/my.cnf:/etc/mysql/my.cnf
完成!!!