Docker技术常用命令
1. Docker基本操作
systemctl start docker #启动docker服务
systemctl stop docker #关闭docker服务
systemctl status docker #查看docker是否启动,是否是运行状态
systemctl enable docker #设置docker开机自启
systemctl disable docker #禁用docker开机自启
systemctl restart docker #重启docker服务
docker info #查看docker信息
如果网络问题,可配置加速器来加速,下面命令直接生成加速文件 daemon.json
cat <<EOF > /etc/docker/daemon.json
{
"registry-mirrors": [
"https://docker.mirrors.ustc.edu.cn",
"http://hub-mirror.c.163.com"
],
"max-concurrent-downloads": 10,
"log-driver": "json-file",
"log-level": "warn",
"log-opts": {
"max-size": "10m",
"max-file": "3"
},
"data-root": "/var/lib/docker"
}
EOF
设置好以后重启docker服务.
2. Docker 镜像操作
docker pull hello-world #下载镜像文件,hello-world为一个镜像文件
docker pull centos:7
docker images #浏览镜像文件
docker inspect hello-world #查看镜像详情,inspect 后可跟镜像名或镜像ID
docker history hello-world #查看镜像文件历史
docker image rm hello-world #删除镜像文件
docker load < hello-world.tar.gz #镜像导入(要在hello-world.tar.gz 文件所在目录下执行)
docker save hello-world | gzip > hello-world.tar.gz #镜像导出
docker run hello-world #运行镜像文件
docker build -t jdk:8 . #为jdk:8构建镜像
3. Docker容器操作
下载镜像
以Centos:7镜像为例
docker pull centos:7 #下载centos:7镜像
官方镜像仓库地址:官方镜像仓库
docker images #查看centos:7镜像文件
docker run -it centos:7 bash #启动centos:7镜像
例: docker run -it xxxx bash
其中: xxx 表示镜像名或 image id 的前几位
-it 表示两个参数(-i 表示交互式操作, -t 表示终端)
bash 表示进入操作终端,基于交互式进行相关操作
容器操作
docker ps #查看docker中运行的容器
docker ps -a #查看docker中所有运行的容器 -a表示all
docker inspect xxx #查看容器 xxx表示容器id
docker start xxx #启动容器 xxx表示容器id
docker stop xxx #关闭容器 xxx表示容器id
docker restart xxx #重新启动容器 xxx表示容器id
docker container logs xxx #查看容器日志信息,通过此指令去看一下错误日志 xxx表示容器id
docker exec -it xxx bash #进入指定容器 xxx表示容器id
exit #进入了启动的容器后,退出容器到宿主机用exit
docker rm -f xxx bash #删除指定容器 xxx表示容器id -f 表示强制
docker container prune #清理所有终止状态容器
4. Docker数据管理操作
容器中管理数据主要有两种方式:
1. 挂载主机目录 (**Bind mounts**)-最常用 (**docker run -v** 宿主机目录:容器目录)
2. 数据卷(**Volumes**)
数据卷: 数据卷是一个可供一个或多个容器使用的特殊目录,可以在容器之间共享和重用,默认会一直存在,即使容器被删除。
docker volume create container-vol #创建数据卷 container-vol为数据卷名称
docker volume ls #查看所有数据卷信息
docker volume inspect container-vol #查看指定的数据卷信息
#启动挂载数据卷的容器,其中-v container-vol:/root 把数据卷 container-vol 挂载到容器的 /root 目录
docker run -it --mount source=container-vol,target=/root centos:7 bash
docker run -it -v container-vol:/root centos:7 bash #简写方式
docker volume rm container-vol #删除数据卷(如果数据卷被容器使用则无法删除)
docker volume prune #清理无主的数据卷
5. Docker容器互联操作
Docker 中存在多个容器时,容器与容器之间经常需要进行通讯,例如nacos访问mysql
Docker 中容器与容器之间进行通讯的解决方案一般有两种:
- 两个容器通过宿主机进行通讯(容器中的端口会映射到宿主机上)
- 两个容器之间直接通过虚拟网络进行连接,但是需要我们在docker中创建网络。
docker network create -d bridge t-net #创建名字为t-net的网络
#其中: -d driver,网络类型,默认 bridge
docker network create t-net #创建名字为t-net的网络
docker network ls #列出所属有网络
docker inspect xxx #查看网络信息 xxx 为创建的网络id
实现容器互联:
#打开终端,基于centos:7这个镜像启动容器,并加入到t-net这个网络
docker run -it --name app1 --network t-net centos:7
#打开新终端执行,基于centos:7这个镜像再启动容器,同时也加入到t-net网络
docker run -it --name app2 --network t-net centos:7
#两个终端分别执行
ping app1
ping app2