上一章节我们了解了Docker的基本概念,以及相关原理。这一章节进行实操。
《Docker这么火爆。章节一:带你详尽了解Docker容器的介绍及使用》
一、Docker安装
声明:Docker支持Centos 6及以后的版本。
1. 查询是否有安装docker
我的是腾讯云的服务器,什么都没有安装,所以没有查询出docker的安装记录
① 如果有安装过docker的小伙伴,可以执行下面命令进行删除:
② 如果安装过,那么再将镜像/容器删除,命令如下:
因为腾讯云的默认为centos7版本
因此在这里只介绍centos7的安装流程
2. 安装docker
有两种方式安装docker:
① 通过yum直接安装docker。但是,这种方式安装可能并不是最新版的docker版本(存在更新不及时的问题)
② 通过yum从阿里云镜像中进行安装,可以下载安装最新版本,运行三条安装命令(在这里就没有把安装输出信息打印出来了,怕篇幅太长,说我水文章~)
其中最后一条命令sudo yum install docker-ce安装过程中,需要有两次确认的过程,直接输入字母:y,然后回车即可。
3. 启动docker
4. 查看docker版本
5. 设置随系统启动
6. docker初体验
输入:docker run hello-world (进入docker世界)
下面会输出一行:Hello from Docker!
二、Docker基本操作
1. 容器操作
docker [run | start | stop | restart | kill | rm | pause | unpause]
-
run/create [镜像名]:创建一个新的容器,并运行一个命令
-
start/stop/restart [容器名]:启动/停止/重启一个容器
-
kill [容器名]:直接杀掉容器进程,不给进程响应时间
-
rm [容器名]:删除已经停止的容器
-
pause/unpause [容器名]:暂停/恢复容器中的进程
docker [ps | inspect | exec | logs | export | import]
-
ps:查看容器列表(默认查看正在运行的容器,-a查看所有容器)
-
inspect [容器名]:查看容器配置元数据
-
exec -it [容器名] /bin/bash:进入容器环境中交互操作
-
logs --since="2020-11-25" -f --tail=10 [容器名]:查看容器日志
-
cp path1 [容器名]:path容器与主机之间的数据拷贝
-
export -o test.tar [容器名]/docker export [容器名]>test.tar:文件系统作为一个tar归档文件
-
import test.tar [镜像名:版本号]:导入归类文档,成为一个镜像
三、镜像操作
docker [images | rmi | tag | build | history | save | load]
-
images:列出本地镜像列表
-
rmi [镜像名:版本]:删除镜像
-
tag [镜像名:版本] [仓库]/[镜像名:版本]:标记本地镜像,将其归入某一仓库
-
build -t [镜像名:版本] [path]:Dockerfile 创建镜像
-
history [镜像名:版本]:查看指定镜像的创建历史
-
save -o xxx.tar [镜像名:版本] /save [镜像名:版本] > xxx.tar:将镜像保存成tar归档文件
-
load --input xxx.tar / docker load < xxx.tar:从归档文件中加载镜像
四、镜像与容器原理及用法探究
1. history命令查看镜像层
例如:docker history hello-world
显示镜像hello-world分三层,其中2个空层
2. 查看镜像文件
镜像存放在imagedb里
一般在image/overlay2/imagedb/content/sha256 下面
打开一个镜像文件查看其内容:
其中,history数组内,标识了镜像的历史记录(与history命令内容对应);
rootfs的diff_ids中,对应了依赖使用中镜像层文件(history命令中size大于0的层)。
五、查看镜像层文件
层文件在layerdb里
镜像层文件内结构
六、镜像与容器总结
一个镜像就是一层层的layer层文件,盖楼而成,上层文件叠于下层文件上,若上层文件有与下层文件重复的,则覆盖掉下层文件重复的部分,如下图:
① 初始挂载时读写层为空。
② 当需要修改镜像内的某个文件时,只对处于最上方的读写层进行了变动,不复写下层已有文件系统的内容,已有文件在只读层中的原始版本仍然存在,但会被读写层中的新版本文件所隐藏,当 docker commit 这个修改过的容器文件系统为一个新的镜像时,保存的内容仅为最上层读写文件系统中被更新过的文件。
③ 联合挂载是用于将多个镜像层的文件系统挂载到一个挂载点来实现一个统一文件系统视图的途径,是下层存储驱动(aufs、overlay等) 实现分层合并的方式。
七、容器创建详解
1. 交互式创建容器并进入:
docker run -it --name centos centos /bin/bash(前台进程)
exit退出也关闭容器;Ctrl+P+Q退出不关闭容器
2. 后台启动容器
d:后台运行, ti/it:交互shell进程
3. 进入已运行的容器
查看容器的元数据:docker inspect nginx
4. 绑定容器端口到主机
5. 挂载主机文件目录到容器内
6. 复制主机文件到容器内
编后语
本文介绍了Docker的安装部署,基本操作;其中包括了容器操作、镜像操作;镜像及容器的原理及用法。通过对Docker的介绍,让小伙伴们能够了解对Docker的基本从操作和常用命令。
下一章节将介绍:《Docker仓库使用》
更多精彩敬请关注公众号
Java极客思维
微信扫一扫,关注公众号
通知:今日公众号将开启送书福利活动,还没有关注公众号的小伙伴尽快关注公众号啦~