Docker的安装与使用

常用命令小结

attach      Attach to a runing container                     # 当前shell下attach连接指定运行镜像
build       Build an image from d Dockerfile                 # 通过Dockerfile 定制镜像
commit      Create a new image from a container changes      # 提交当前容器为新的镜像
cp          Copy files/folders from the container filesystem to the host path
            # 从当前容器中拷贝指定文件或者目录到宿主机中
create      Create a new container                           # 创建一个新的容器,同run,但是不启动容器
diff        Inspect changes on a container's filesystem      # 查看docker容器变化
events      Get real time events from server                 # 从docker服务获取容器实时事件
exec        Run a command in an existing container           # 在已存在的容器上运行命令
export      Stream the contents of a container as tar archive
            # 导出容器的内容流作为一个tar归档文件[对应import]
history     Show the history of an image                     # 展示一个镜像形成历史
images      List images                                      # 镜像列表
import      Create a new filesystem image from the contents of a tarball
            # 从tar包中的内容创建一个新的文件系统系统[对应export]
info        Display system-wide  information on a container  # 显示系统相关信息
inspect     Ruturn low-level information on a container      # 查看容器详细信息
kill        Kill a runing container                          # kill指定docker容器
load        Load an image from a tar archive                 # 从一个tar包中加载一个镜像[对应save]
login       Register or login to the docker registry server  # 注册或登录一个docker源服务器
logout      Log out from a Docker registry server            # 从当前的Docker registry 退出
logs        Fetch the logs of a container                    # 输出指定容器的日志信息
port        Lookup the punlic-facing port ehich is NAT-ed PRIVATE_PORT
            # 查看映射端口对应的容器内部源端口
pause       Pause all processes within a container           # 暂停容器
ps          list containers                                  # 列出容器列表
pull        Pull an image or a registory from the docker registry server
            # 从docker镜像源服务器拉取指定镜像或者库镜像
push        Push an image or registory to the docker registry server
            # 推送指定镜像或者库镜像至docker源服务器
restart     # 重启一个在运行的容器
rm          # 移除一个或者多个容器
rmi         # 移除一个或多个镜像[镜像有容器运行时,不能删除,除非加-f强制删除]
run         # 创建一个新的容器并运行一个命令
save        # 保存一个镜像为一个tar包[对应load]
search      # 在docker hub中搜索镜像
start       # 启动容器
stop        # 停止容器
tag         # 给源中镜像打标签
top         # 查看容器中运行的进程
unpause     # 取消暂停容器
version     # 查看docker版本号
wait        # 截取容器停止时的退出状态值

Docker in deepin

深度系统安装Docker

卸载之前的docker

  • sudo apt-get remove docker.io docker-engine

安装curl

​ deepin系统没有curl,需要手动安装。因为我们要安装docker-ce和密钥管理相关的工具,需要使用curl,所以使用下面的命令安装。

  • 测试你的环境是否有curl

  • 没有就安装:sudo apt-get install curl

  • 测试是否可以正常链接:curl -X GET http://www.baidu.com

下载安装相关的部件

  • sudo apt-get install apt-transport-https ca-certificates curl software-properties-common

    Python相关的组件,目前的python-software-properties已经包含在software-properties-common。

    安装docker

安装docker-ce之准备环节

安装秘钥

curl -fsSL https://download.docker.com/linux/debian/gpg | sudo apt-key add - 

测试是否成功

sudo apt-key fingerprint 0EBFCD88
  • 注意这里命令是零不是o。

安装docker-ce

安装docker官方仓库并更新本地软件仓库

sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/debian jessie stable"

输入此命令后报错了:

aptsources.distro.NoDistroTemplateException: Error: could not find a distribution template for Deepin/stable

错误解决:

sudo deepin-editor /etc/lsb-release

​ 修改:

# DISTRIB_ID=Deepin
# DISTRIB_RELEASE="15.11"
# DISTRIB_DESCRIPTION="Deepin 15.11 "
# DISTRIB_CODENAME=stable

DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=16.04
DISTRIB_DESCRIPTION="Ubuntu 16.04.6 LTS"
DISTRIB_CODENAME=trusty

重新安装:

sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/debian jessie stable"
sudo apt-get update

下载docker-ce并安装

sudo apt-get install docker-ce

​ 安装速度很快!安装完成后,输入ifconfig之后可以发现docker已经启动起来了。

​ 输入docker version 查看版本信息。

配置阿里云镜像加速

配置daemon.json文件

配置命令

  • sudo vim /etc/docker/daemon.json
    
  • 添加如下内容:

{
    "registry-mirrors": ["https://cr.console.aliyuncs.com"]
}

然后重启docker服务

sudo service docker restart

可添加的其他源:

Docker中国区官方镜像
https://registry.docker-cn.com

网易
http://hub-mirror.c.163.com

ustc
https://docker.mirrors.ustc.edu.cn

中国科技大学
https://docker.mirrors.ustc.edu.cn

阿里云容器 服务
https://cr.console.aliyun.com/

遇到的问题

重启docker,遇到如下问题:

sun@sun-PC:~/Desktop$ systemctl restart docker
Job for docker.service failed because the control process exited with error code.
See "systemctl status docker.service" and "journalctl -xe" for details.

查询遇到的问题:

sun@sun-PC:/etc/docker$ dockerd
unable to configure the Docker daemon with file /etc/docker/daemon.json: the following directives don't match any configuration option: registry-mrrors

可以发现这里的json文件有问题,所以我修改了上面的json文件,结果如上面的文件,之后重启就成功了。相同的问题可能是其他的情况,如:

重启docker

systemctl restart docker

​ 重启成功了!

测试镜像hello-world

sudo docker run hello-world

测试时,遇到一系列报错,我换了源,反复重启了docker,问题依然没有解决,最后使用命令开启docker服务。

sudo service docker start

常用命令

帮助命令

docker version                   # docker的版本信息
docker info                      # docker的系统信息,包含了镜像和容器的信息
docker '命令' --help              # docker的帮助命令
# 也可以进入官网查看命令的使用详情
# reference地址:https://docs.docker.com/reference/

镜像命令

docker images 查看所有本地的主机上的镜像

sun@sun-PC:~/Desktop$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
hello-world         latest              bf756fb1ae65        5 months ago        13.3kB
# 解释
REPOSITORY       镜像的仓库源(名)
TAG              镜像的标签
IMAGE ID         镜像的ID
CREATED          镜像的创建时间
SIZE             镜像的大小
---------------------------------------------------------------------------
# 可选项
Options:
  -a, --all             展示所有的镜像
      --digests         Show digests
  -f, --filter filter   根据条件过滤镜像
      --format string   Pretty-print images using a Go template
      --no-trunc        Don't truncate output
  -q, --quiet           只显示镜像的ID
---------------------------------------------------------------------------
sun@sun-PC:~/Desktop$ docker images -a
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
hello-world         latest              bf756fb1ae65        5 months ago        13.3kB
sun@sun-PC:~/Desktop$ docker images -aq
bf756fb1ae65

docker search 搜索命令

sunxiaoqing@sunxiaoqing-PC:~/Desktop$ docker search mysql
NAME                              DESCRIPTION                                     STARS               OFFICIAL            AUTOMATED
mysql                             MySQL is a widely used, open-source relation…   9682                [OK]                
mariadb                           MariaDB is a community-developed fork of MyS…   3523                [OK] 
-----------------------------------------------------------------------------
# 可选项
# 搜索星在4000以上的
Options:
  -f, --filter filter   按条件过滤
      --format string   Pretty-print search using a Go template
      --limit int       Max number of search results (default 25)
      --no-trunc        Don't truncate output
------------------------------------------------------------------------------
sunxiaoqing@sunxiaoqing-PC:~/Desktop$ docker search mysql --filter=stars=4000
NAME                DESCRIPTION                                     STARS               OFFICIAL            AUTOMATED
mysql               MySQL is a widely used, open-source relation…   9682                [OK]  
# 这里的stars与STARS效果一样
------------------------------------------------------------------------------

docker pull 镜像下载

# 直接下载,默认下载最新的版本,后面可以跟版本号指定版本
sun@sun-PC:~/Desktop$ docker pull mysql
Using default tag: latest                 # 如果不写tag,默认就是latest版本
latest: Pulling from library/mysql
8559a31e96f4: Pull complete               # 下载的时候这一段是一直在变的--->分层下载:
d51ce1c2e575: Pull complete               # docker images的核心 联合文件系统
c2344adc4858: Pull complete 
fcf3ceff18fc: Pull complete 
16da0c38dc5b: Pull complete 
b905d1797e97: Pull complete 
4b50d1c6b05c: Pull complete 
c75914a65ca2: Pull complete 
1ae8042bdd09: Pull complete 
453ac13c00a3: Pull complete 
9e680cd72f08: Pull complete 
a6b5dc864b6c: Pull complete 
Digest: sha256:8b7b328a7ff6de46ef96bcf83af048cb00a1c86282bfca0cb119c84568b4caf6 # 签名
Status: Downloaded newer image for mysql:latest
docker.io/library/mysql:latest            # 真实的地址(这一句可能没有)

# 下面两者等价
docker pull mysql
docker pull docker.io/library/mysql:latest
-------------------------------------------------------------------------------------
# 指定版本下载
sun@sun-PC:~/Desktop$ docker pull mysql:5.7
5.7: Pulling from library/mysql
8559a31e96f4: Already exists              # 下载latest版本时,这些片已经下载了
d51ce1c2e575: Already exists 
c2344adc4858: Already exists 
fcf3ceff18fc: Already exists 
16da0c38dc5b: Already exists 
b905d1797e97: Already exists 
4b50d1c6b05c: Already exists 
d85174a87144: Pull complete 
a4ad33703fa8: Pull complete 
f7a5433ce20d: Pull complete 
3dcd2a278b4a: Pull complete 
Digest: sha256:32f9d9a069f7a735e28fd44ea944d53c61f990ba71460c5c183e610854ca4854
Status: Downloaded newer image for mysql:5.7
--------------------------------------------------------------------------------------
sun@sun-PC:~/Desktop$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
mysql               5.7                 9cfcce23593a        2 weeks ago         448MB
mysql               latest              be0dbf01a0f3        2 weeks ago         541MB
hello-world         latest              bf756fb1ae65        5 months ago        13.3kB
--------------------------------------------------------------------------------------

docker rmi 删除镜像

sun@sun-PC:~/Desktop$ docker rmi -f 镜像ID                      # 删除一个镜像
sun@sun-PC:~/Desktop$ docker rmi -f 镜像ID 镜像ID 镜像ID 镜像ID   # 删除多个镜像
sun@sun-PC:~/Desktop$ docker rmi -f $(docker images -aq)        # 删除全部镜像

一般我们指定ID进行删除

sun@sun-PC:~/Desktop$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
mysql               5.7                 9cfcce23593a        2 weeks ago         448MB
mysql               latest              be0dbf01a0f3        2 weeks ago         541MB
hello-world         latest              bf756fb1ae65        5 months ago        13.3kB
sun@sun-PC:~/Desktop$ docker rmi be0dbf01a0f3
Untagged: mysql:latest
Untagged: mysql@sha256:8b7b328a7ff6de46ef96bcf83af048cb00a1c86282bfca0cb119c84568b4caf6
Deleted: sha256:be0dbf01a0f3f46fc8c88b67696e74e7005c3e16d9071032fa0cd89773771576
Deleted: sha256:086d66e8d1cb0d52e9337eabb11fb9b95960e2e1628d90100c62ea5e8bf72306
Deleted: sha256:f37c61ee1973b18c285d0d5fcf02da4bcdb1f3920981499d2a20b2858500a110
Deleted: sha256:e40b8bca7dc63fc8d188a412328e56caf179022f5e5d5b323aae57d233fb1069
Deleted: sha256:339f6b96b27eb035cbedc510adad2560132925a835f0afddbcc1d311c961c14b
Deleted: sha256:d38b06cdb26a5c98857ddbc6ef531d3f57b00e325c0c314600b712efc7ff6ab0
# 这里删除时,没有删除mysql:5.7的依赖,只删除mysql:latest版本的独立依赖
----------------------------------------------------------------------------------------
sunxiaoqing@sunxiaoqing-PC:~/Desktop$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
mysql               5.7                 9cfcce23593a        2 weeks ago         448MB
hello-world         latest              bf756fb1ae65        5 months ago        13.3kB
sunxiaoqing@sunxiaoqing-PC:~/Desktop$ docker rmi -f $(docker images -aq) # 删除全部镜像
Untagged: mysql:5.7
Untagged: mysql@sha256:32f9d9a069f7a735e28fd44ea944d53c61f990ba71460c5c183e610854ca4854
Deleted: sha256:9cfcce23593a93135ca6dbf3ed544d1db9324d4c40b5c0d56958165bfaa2d46a
Deleted: sha256:98de3e212919056def8c639045293658f6e6022794807d4b0126945ddc8324be
Deleted: sha256:17e8b88858e400f8c5e10e7cb3fbab9477f6d8aacba03b8167d34a91dbe4d8c1
Deleted: sha256:c04c087c2af9abd64ba32fe89d65e6d83da514758923de5da154541cc01a3a1e
Deleted: sha256:ab8bf065b402b99aec4f12c648535ef1b8dc954b4e1773bdffa10ae2027d3e00
Deleted: sha256:09687cd9cdf4c704fde969fdba370c2d848bc614689712bef1a31d0d581f2007
Deleted: sha256:b704a4a65bf536f82e5d8b86e633d19185e26313de8380162e778feb2852011a
Deleted: sha256:c37206160543786228aa0cce738e85343173851faa44bb4dc07dc9b7dc4ff1c1
Deleted: sha256:12912c9ec523f648130e663d9d4f0a47c1841a0064d4152bcf7b2a97f96326eb
Deleted: sha256:57d29ad88aa49f0f439592755722e70710501b366e2be6125c95accc43464844
Deleted: sha256:b17c024283d0302615c6f0c825137da9db607d49a83d2215a79733afbbaeb7c3
Deleted: sha256:13cb14c2acd34e45446a50af25cb05095a17624678dbafbcc9e26086547c1d74
Untagged: hello-world:latest
Untagged: hello-world@sha256:d58e752213a51785838f9eed2b7a498ffa1cb3aa7f946dda11af39286c3db9a9
Deleted: sha256:bf756fb1ae65adf866bd8c456593cd24beb6a0a061dedf42b26a993176745f6b
sunxiaoqing@sunxiaoqing-PC:~/Desktop$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
# 没有镜像在本地了

容器命令

说明:只有有了镜像才可以创建容器,测试在deepin系统里下载一个centos镜像来测试学习

docker pull centos
--------------------------------------------------------------------------------
sun@sun-PC:~/Desktop$ docker pull centos
Using default tag: latest
latest: Pulling from library/centos
6910e5a164f7: Pull complete 
Digest: sha256:4062bbdd1bb0801b0aa38e0f83dece70fb7a5e9bce223423a68de2d8b784b43b
Status: Downloaded newer image for centos:latest

新建容器并启动

docker run [可选参数] image
# 参数说明
--name="NAME"                容器名字    sun1    sun2    用来区分容器
-d                           以后台方式运行
-it                          使用交互方式运行,进入容器查看内容
-p                           指定容器的端口 如:  -p 8080:8080
	四种方式:
	-p 主机ip:主机端口:容器端口
	-p 主机端口:容器端口       将主机端口映射到容器端口(常用)
	-p 容器端口
	容器端口
-P(大写)                    随机指定端口

----------------------------------------------------------------------------------------
# 测试、启动并进入容器
sun@sun-PC:~/Desktop$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
centos              latest              831691599b88        11 days ago         215MB
sun@sun-PC:~/Desktop$ docker run -it /bin/bash
docker: invalid reference format.
See 'docker run --help'.
sun@sun-PC:~/Desktop$ docker run -it centos /bin/bash
[root@707fbf5e8c87 /]# ls               # 查看容器内的contos系统,基础版本,很多命令都不完善
bin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
[root@707fbf5e8c87 /]# exit             # 退回主机
exit
----------------------------------------------------------------------------------------

列出所有的运行容器

# docker ps命令
-a                        # 列出当前正在运行的容器,并带出历史运行的容器
-n=?                      # 列出最近创建的容器
-aq                       # 只显示容器的编号
----------------------------------------------------------------------------------------
sun@-PC:~/Desktop$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
centos              latest              831691599b88        11 days ago         215MB
sun@-PC:~/Desktop$ docker run -it /bin/bash
docker: invalid reference format.
See 'docker run --help'.
sun@sun-PC:~/Desktop$ docker run -it centos /bin/bash
[root@707fbf5e8c87 /]# ls
bin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
[root@707fbf5e8c87 /]# exit
exit
sun@sun-PC:~/Desktop$ cd
sun@sun-PC:~$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
sun@sun-PC:~$ docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                     PORTS               NAMES
707fbf5e8c87        centos              "/bin/bash"         4 minutes ago       Exited (0) 2 minutes ago                       zen_payne
eae029c81ffc        bf756fb1ae65        "/hello"            12 hours ago        Exited (0) 12 hours ago                        keen_grothendieck
sun@sun-PC:~$ docker ps -n=1
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                     PORTS               NAMES
707fbf5e8c87        centos              "/bin/bash"         7 minutes ago       Exited (0) 5 minutes ago                       zen_payne

退出容器

exit                     # 直接停止并退出容器
Ctrl + P +Q              # 退出但不停止运行(命令要大写)

sun@sun-PC:~$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
sun@sun-PC:~$ docker run -it centos /bin/bash
[root@ad2f2cd532b1 /]# sun@sun-PC:~$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
ad2f2cd532b1        centos              "/bin/bash"         2 minutes ago       Up 2 minutes                            objective_banach
# 这里使用了Ctrl + P +Q退出

删除容器

docker rm 容器ID                      # 删除指定的容器,不能删除正在运行的容器
docker rm -f $(docker ps -aq)        # 删除所有的容器,强制删除所有的容器
docker ps -a -q | xargs docker rm    # 删除所有的容器
sun@sun-PC:~$ docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                      PORTS               NAMES
ad2f2cd532b1        centos              "/bin/bash"         9 minutes ago       Up 9 minutes                                    objective_banach
707fbf5e8c87        centos              "/bin/bash"         22 minutes ago      Exited (0) 20 minutes ago                       zen_payne
eae029c81ffc        bf756fb1ae65        "/hello"            13 hours ago        Exited (0) 13 hours ago                         keen_grothendieck
sun@sun-PC:~$ docker rm 707fbf5e8c87
707fbf5e8c87
sun@sun-PC:~$ docker rm ad2f2cd532b1          # 不能删除正在运行的容器
Error response from daemon: You cannot remove a running container ad2f2cd532b1931598fecb1467cc3a72aeaee247700418b3572ee844a9b2ed83. Stop the container before attempting removal or force remove
----------------------------------------------------------------------------------------
sun@sun-PC:~$ docker rm -f $(docker ps -aq)   # 强制删除所有的容器
ad2f2cd532b1
eae029c81ffc
sun@sun-PC:~$ docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES

启动和停止容器的操作

docker start 容器ID               # 启动容器
docker restart 容器ID             # 重启容器
docker stop 容器ID                # 停止当前正在运行的容器
docker kill 容器ID                # 强制停止当前容器
sun@sun-PC:~$ docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
sun@sun-PC:~$ docker run -it centos /bin/bash
[root@10ec4078a6a6 /]# exit
exit
sun@sun-PC:~$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
sun@sun-PC:~$ docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                      PORTS               NAMES
10ec4078a6a6        centos              "/bin/bash"         44 seconds ago      Exited (0) 27 seconds ago                       distracted_heisenberg
sun@sun-PC:~$ docker start 10ec4078a6a6
10ec4078a6a6
sun@sun-PC:~$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED              STATUS              PORTS               NAMES
10ec4078a6a6        centos              "/bin/bash"         About a minute ago   Up 25 seconds                           distracted_heisenberg
sun@sun-PC:~$ docker stop 10ec4078a6a6
10ec4078a6a6
sun@sun-PC:~$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
sun@sun-PC:~$ docker kill 10ec4078a6a6
Error response from daemon: Cannot kill container: 10ec4078a6a6: Container 10ec4078a6a66eb0fdab984915c9c6a225f6b5a31b984faf1597abec8a1bb97a is not running
sun@sun-PC:~$ docker start 10ec4078a6a6
10ec4078a6a6
sun@sun-PC:~$ docker kill 10ec4078a6a6
10ec4078a6a6
sun@sun-PC:~$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES

其他常用命令

后台启动容器

# 命令:docker run -d 镜像名
root@ai1:~# docker run -d centos
d33b499f467935ff4be240a75a985bec83eda95336f528d7228dd2baba1454a8
root@ai1:~# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
# 问题docker ps,发现centos已经停止了
# 常见的坑:docker容器使用后台运行,就必须要有一个前台进程,docker发现没有应用,就会自杀

查看日志命令

命令:docker logs -f -t --tail 查看的日志数 容器id

root@ai1:~# docker logs --help
Options:  # 可选项
      --details        Show extra details provided to logs
  -f, --follow         Follow log output
      --since string   Show logs since timestamp (e.g. 2013-01-02T13:23:37) or relative (e.g. 42m for 42 minutes)
      --tail string    Number of lines to show from the end of the logs (default "all")
  -t, --timestamps     Show timestamps
      --until string   Show logs before a timestamp (e.g. 2013-01-02T13:23:37) or relative (e.g. 42m for 42 minutes)
------------------------------------------------------------------------------------------
root@ai1:~# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
root@ai1:~# docker run -it centos /bin/bash
[root@b2369309af4e /]# root@ai1:~# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED              STATUS              PORTS               NAMES
b2369309af4e        centos              "/bin/bash"         About a minute ago   Up About a minute                       pensive_hellman
root@ai1:~# docker logs -f -t --tail 10 b2369309af4e

# 木有任何日志输出,因为我们这里是centos系统,里面我们自己没有写任何操作
------------------------------------------------------------------------------------------
# 添加输出代码测试
root@ai1:~# docker run -d centos /bin/sh -c "while true;do echo shuju;sleep 2; done" 
e152d38e197627a837683bf31cf2650d3baea2131c3e28c633a8ade9df229546
root@ai1:~# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS               NAMES
e152d38e1976        centos              "/bin/sh -c 'while t…"   8 seconds ago       Up 6 seconds                            inspiring_leakey
b2369309af4e        centos              "/bin/bash"              9 minutes ago       Up 9 minutes                            pensive_hellman
root@ai1:~# docker logs -tf --tail 10 e152d38e1976
2020-07-04T04:27:41.258719887Z shuju
2020-07-04T04:27:43.260429003Z shuju
2020-07-04T04:27:45.262204113Z shuju
2020-07-04T04:27:47.263971132Z shuju
2020-07-04T04:27:49.265984007Z shuju
2020-07-04T04:27:51.267760135Z shuju
2020-07-04T04:27:53.269701320Z shuju
2020-07-04T04:27:55.271781304Z shuju
2020-07-04T04:27:57.273585752Z shuju
2020-07-04T04:27:59.275456823Z shuju
2020-07-04T04:28:01.277243215Z shuju
2020-07-04T04:28:03.278997862Z shuju
2020-07-04T04:28:05.280755754Z shuju
2020-07-04T04:28:07.282540332Z shuju
……  # 一直会刷新打印
-------------------------------------------------------------------------------------------
# 显示日志
 -tf    # 显示日志
 --tail # 后面接number,显示日志条数

查看容器中的进程信息

命令:docker top 容器id

root@ai1:~# docker top e152d38e1976
UID                 PID                 PPID                C                   STIME       
root                995                 969                 0                   12:27       
root                1224                995                 0                   12:31       
# uid:  用户id
# PID: 
# PPID:进程ID

查看镜像的元数据

命令:docker inspect 容器id

# 可选项
  -f, --format string   Format the output using the given Go template
  -s, --size            Display total file sizes if the type is container
      --type string     Return JSON for specified type
# 查看容器元数据
[
    {
        "Id": "e152d38e197627a837683bf31cf2650d3baea2131c3e28c633a8ade9df229546",
        "Created": "2020-07-04T04:27:24.709213575Z",
        "Path": "/bin/sh",
        "Args": [
            "-c",
            "while true;do echo shuju;sleep 2; done"
        ],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 995,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2020-07-04T04:27:25.244598138Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:831691599b88ad6cc2a4abbd0e89661a121aff14cfa289ad840fd3946f274f1f",
        "ResolvConfPath": "/var/lib/docker/containers/e152d38e197627a837683bf31cf2650d3baea2131c3e28c633a8ade9df229546/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/e152d38e197627a837683bf31cf2650d3baea2131c3e28c633a8ade9df229546/hostname",
        "HostsPath": "/var/lib/docker/containers/e152d38e197627a837683bf31cf2650d3baea2131c3e28c633a8ade9df229546/hosts",
        "LogPath": "/var/lib/docker/containers/e152d38e197627a837683bf31cf2650d3baea2131c3e28c633a8ade9df229546/e152d38e197627a837683bf31cf2650d3baea2131c3e28c633a8ade9df229546-json.log",
        "Name": "/inspiring_leakey",
        "RestartCount": 0,
        "Driver": "overlay2",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "docker-default",
        "ExecIDs": null,
        "HostConfig": {
            "Binds": null,
            "ContainerIDFile": "",
            "LogConfig": {
                "Type": "json-file",
                "Config": {}
            },
            "NetworkMode": "default",
            "PortBindings": {},
            "RestartPolicy": {
                "Name": "no",
                "MaximumRetryCount": 0
            },
            "AutoRemove": false,
            "VolumeDriver": "",
            "VolumesFrom": null,
            "CapAdd": null,
            "CapDrop": null,
            "Capabilities": null,
            "Dns": [],
            "DnsOptions": [],
            "DnsSearch": [],
            "ExtraHosts": null,
            "GroupAdd": null,
            "IpcMode": "private",
            "Cgroup": "",
            "Links": null,
            "OomScoreAdj": 0,
            "PidMode": "",
            "Privileged": false,
            "PublishAllPorts": false,
            "ReadonlyRootfs": false,
            "SecurityOpt": null,
            "UTSMode": "",
            "UsernsMode": "",
            "ShmSize": 67108864,
            "Runtime": "runc",
            "ConsoleSize": [
                0,
                0
            ],
            "Isolation": "",
            "CpuShares": 0,
            "Memory": 0,
            "NanoCpus": 0,
            "CgroupParent": "",
            "BlkioWeight": 0,
            "BlkioWeightDevice": [],
            "BlkioDeviceReadBps": null,
            "BlkioDeviceWriteBps": null,
            "BlkioDeviceReadIOps": null,
            "BlkioDeviceWriteIOps": null,
            "CpuPeriod": 0,
            "CpuQuota": 0,
            "CpuRealtimePeriod": 0,
            "CpuRealtimeRuntime": 0,
            "CpusetCpus": "",
            "CpusetMems": "",
            "Devices": [],
            "DeviceCgroupRules": null,
            "DeviceRequests": null,
            "KernelMemory": 0,
            "KernelMemoryTCP": 0,
            "MemoryReservation": 0,
            "MemorySwap": 0,
            "MemorySwappiness": null,
            "OomKillDisable": false,
            "PidsLimit": null,
            "Ulimits": null,
            "CpuCount": 0,
            "CpuPercent": 0,
            "IOMaximumIOps": 0,
            "IOMaximumBandwidth": 0,
            "MaskedPaths": [
                "/proc/asound",
                "/proc/acpi",
                "/proc/kcore",
                "/proc/keys",
                "/proc/latency_stats",
                "/proc/timer_list",
                "/proc/timer_stats",
                "/proc/sched_debug",
                "/proc/scsi",
                "/sys/firmware"
            ],
            "ReadonlyPaths": [
                "/proc/bus",
                "/proc/fs",
                "/proc/irq",
                "/proc/sys",
                "/proc/sysrq-trigger"
            ]
        },
        "GraphDriver": {
            "Data": {
                "LowerDir": "/var/lib/docker/overlay2/9874bde0157367981c65740acc24edea7f823b281ff25008d3392485256b64c3-init/diff:/var/lib/docker/overlay2/00dc9e7a7970c4edd9bb0223edfef86bfd3a459370eb9916fb0b821a9426a805/diff",
                "MergedDir": "/var/lib/docker/overlay2/9874bde0157367981c65740acc24edea7f823b281ff25008d3392485256b64c3/merged",
                "UpperDir": "/var/lib/docker/overlay2/9874bde0157367981c65740acc24edea7f823b281ff25008d3392485256b64c3/diff",
                "WorkDir": "/var/lib/docker/overlay2/9874bde0157367981c65740acc24edea7f823b281ff25008d3392485256b64c3/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "e152d38e1976",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
            ],
            "Cmd": [
                "/bin/sh",
                "-c",
                "while true;do echo shuju;sleep 2; done"
            ],
            "Image": "centos",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": {
                "org.label-schema.build-date": "20200611",
                "org.label-schema.license": "GPLv2",
                "org.label-schema.name": "CentOS Base Image",
                "org.label-schema.schema-version": "1.0",
                "org.label-schema.vendor": "CentOS"
            }
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "84050beaf1d100fcdee4b27b66a7e144ecddbc03a846bef563cbff4172c4ff62",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {},
            "SandboxKey": "/var/run/docker/netns/84050beaf1d1",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "aaccca192dba4ff1e2ea3703c909ca37fa7d81be1c8259b6ea022bdc9ef1f25e",
            "Gateway": "172.17.0.1",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "172.17.0.3",
            "IPPrefixLen": 16,
            "IPv6Gateway": "",
            "MacAddress": "02:42:ac:11:00:03",
            "Networks": {
                "bridge": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "NetworkID": "19c24ceb5fcb42a54c4e799e8970cb9e8f19f485e70c0f00672f8530e51f15d5",
                    "EndpointID": "aaccca192dba4ff1e2ea3703c909ca37fa7d81be1c8259b6ea022bdc9ef1f25e",
                    "Gateway": "172.17.0.1",
                    "IPAddress": "172.17.0.3",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:ac:11:00:03",
                    "DriverOpts": null
                }
            }
        }
    }
]

进入当前正在运行的容器

命令:docker exec -it 容器id baseshell(/bin/sh或者/bin/bash)

docker attach 容器id

# 方式一
root@ai1:~# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS               NAMES
e152d38e1976        centos              "/bin/sh -c 'while t…"   42 minutes ago      Up 42 minutes                           inspiring_leakey
b2369309af4e        centos              "/bin/bash"              51 minutes ago      Up 51 minutes                           pensive_hellman
root@ai1:~# docker exec -it e152d38e1976 /bin/bash
[root@e152d38e1976 /]# ls
bin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
------------------------------------------------------------------------------------------
# 方式二
docker attach 容器id 进去之后会打开正在执行的终端

# docker exec         # 进入容器后开启一个新的终端,可以在里面操作(常用)
# docker attach       # 进去容器正在执行的终端,不会启动新的进程!

从容器内拷贝文件到主机上

命令:docker cp 容器id:容器内路径 目标主机路径

root@ai1:/home# ls
dc  dockertest.java

# 进入docker容器
root@ai1:/home# docker attach b2369309af4e
[root@b2369309af4e /]# ls
bin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
[root@b2369309af4e /]# cd home
[root@b2369309af4e home]# ls    
[root@b2369309af4e home]# touch test.java
[root@b2369309af4e home]# exit
exit
root@ai1:/home# docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                     PORTS               NAMES
b2369309af4e        centos              "/bin/bash"         2 hours ago         Exited (0) 8 seconds ago                       pensive_hellman
d33b499f4679        centos              "/bin/bash"         2 hours ago         Exited (0) 2 hours ago                         heuristic_nobel
b02b6e141960        centos              "/bin/bash"         2 hours ago         Exited (0) 2 hours ago                         elated_noether
89edce4472ff        hello-world         "/hello"            2 hours ago         Exited (0) 2 hours ago                         nifty_hawking
root@ai1:/home# docker cp b2369309af4e:/home/test.java /home
root@ai1:/home# ls
dc  dockertest.java  test.java

# 拷贝是一个手动过程,未来我们会使用数据卷同步数据

docker 常用命令小结

attach      Attach to a runing container                     # 当前shell下attach连接指定运行镜像
build       Build an image from d Dockerfile                 # 通过Dockerfile 定制镜像
commit      Create a new image from a container changes      # 提交当前容器为新的镜像
cp          Copy files/folders from the container filesystem to the host path
            # 从当前容器中拷贝指定文件或者目录到宿主机中
create      Create a new container                           # 创建一个新的容器,同run,但是不启动容器
diff        Inspect changes on a container's filesystem      # 查看docker容器变化
events      Get real time events from server                 # 从docker服务获取容器实时事件
exec        Run a command in an existing container           # 在已存在的容器上运行命令
export      Stream the contents of a container as tar archive
            # 导出容器的内容流作为一个tar归档文件[对应import]
history     Show the history of an image                     # 展示一个镜像形成历史
images      List images                                      # 镜像列表
import      Create a new filesystem image from the contents of a tarball
            # 从tar包中的内容创建一个新的文件系统系统[对应export]
info        Display system-wide  information on a container  # 显示系统相关信息
inspect     Ruturn low-level information on a container      # 查看容器详细信息
kill        Kill a runing container                          # kill指定docker容器
load        Load an image from a tar archive                 # 从一个tar包中加载一个镜像[对应save]
login       Register or login to the docker registry server  # 注册或登录一个docker源服务器
logout      Log out from a Docker registry server            # 从当前的Docker registry 退出
logs        Fetch the logs of a container                    # 输出指定容器的日志信息
port        Lookup the punlic-facing port ehich is NAT-ed PRIVATE_PORT
            # 查看映射端口对应的容器内部源端口
pause       Pause all processes within a container           # 暂停容器
ps          list containers                                  # 列出容器列表
pull        Pull an image or a registory from the docker registry server
            # 从docker镜像源服务器拉取指定镜像或者库镜像
push        Push an image or registory to the docker registry server
            # 推送指定镜像或者库镜像至docker源服务器
restart     # 重启一个在运行的容器
rm          # 移除一个或者多个容器
rmi         # 移除一个或多个镜像[镜像有容器运行时,不能删除,除非加-f强制删除]
run         # 创建一个新的容器并运行一个命令
save        # 保存一个镜像为一个tar包[对应load]
search      # 在docker hub中搜索镜像
start       # 启动容器
stop        # 停止容器
tag         # 给源中镜像打标签
top         # 查看容器中运行的进程
unpause     # 取消暂停容器
version     # 查看docker版本号
wait        # 截取容器停止时的退出状态值

docker in ubantu

docker 安装

安装参考文档:https://docs.docker.com/engine/install/ubuntu/

第一步:删除之前的docker版本

sudo apt-get remove docker docker-engine docker.io containerd runc

(base) dc@dell-PowerEdge-T640:~$ sudo apt-get remove docker docker-engine docker.io containerd runc
[sudo] dc 的密码: 
正在读取软件包列表... 完成
正在分析软件包的依赖关系树       
正在读取状态信息... 完成       
软件包 docker-engine 未安装,所以不会被卸载
软件包 docker 未安装,所以不会被卸载
软件包 containerd 未安装,所以不会被卸载
软件包 docker.io 未安装,所以不会被卸载
软件包 runc 未安装,所以不会被卸载
下列软件包是自动安装的并且现在不需要了:
  linux-oem-headers-4.15.0-1037
使用'sudo apt autoremove'来卸载它(它们)。
升级了 0 个软件包,新安装了 0 个软件包,要卸载 0 个软件包,有 15 个软件包未被升级。

第二步:更新软件并安装相关配置

$ sudo apt-get update
$ sudo apt-get install \
    apt-transport-https \
    ca-certificates \
    curl \
    gnupg-agent \
    software-properties-common

安装过程中遇到您希望继续执行吗? [Y/n] y选择“y”

第三步:添加docker的官方GPG密钥

$ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -

第四步:验证密钥

$ sudo apt-key fingerprint 0EBFCD88

pub   rsa4096 2017-02-22 [SCEA]
      9DC8 5822 9FC7 DD38 854A  E2D8 8D81 803C 0EBF CD88
uid           [ unknown] Docker Release (CE deb) <docker@docker.com>
sub   rsa4096 2017-02-22 [S]

第五步:添加镜像仓库(注意自己的ubantu系统版本)

arch可选项:amd64、armhf、arm64

$ sudo add-apt-repository \
   "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
   $(lsb_release -cs) \
   stable"

第六步:更新软件并安装docker-ce

$ sudo apt-get update
$ sudo apt-get install docker-ce docker-ce-cli containerd.io

第七步:验证是否安装成功

$ sudo docker run hello-world
(base) xxx@dell-PowerEdge-T640:~$ sudo docker run hello-world
[sudo] xxx 的密码: 
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
0e03bdcc26d7: Pull complete 
Digest: sha256:d58e752213a51785838f9eed2b7a498ffa1cb3aa7f946dda11af39286c3db9a9
Status: Downloaded newer image for hello-world:latest

Hello from Docker!         # 运行成功的标志
This message shows that your installation appears to be working correctly.

To generate this message, Docker took the following steps:
 1. The Docker client contacted the Docker daemon.
 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
    (amd64)
 3. The Docker daemon created a new container from that image which runs the
    executable that produces the output you are currently reading.
 4. The Docker daemon streamed that output to the Docker client, which sent it
    to your terminal.

To try something more ambitious, you can run an Ubuntu container with:
 $ docker run -it ubuntu bash

Share images, automate workflows, and more with a free Docker ID:
 https://hub.docker.com/

For more examples and ideas, visit:
 https://docs.docker.com/get-started/

第八步:测试命令是否可以执行

(base) xxx@dell-PowerEdge-T640:~$ docker images
Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Get http://%2Fvar%2Frun%2Fdocker.sock/v1.40/images/json: dial unix /var/run/docker.sock: connect: permission denied

docker权限不够,解决办法:(添加用户到docker组,在需要议添加对用户下执行就可以)

sudo groupadd docker
sudo gpasswd -a $USER docker
newgrp docker
root@dell-PowerEdge-T640:/var/run# sudo groupadd docker
groupadd:“docker”组已存在
root@dell-PowerEdge-T640:/var/run# sudo gpasswd -a $USER docker
正在将用户“root”加入到“docker”组中
root@dell-PowerEdge-T640:/var/run# su xxx
(base) xxx@dell-PowerEdge-T640:/var/run$ sudo gpasswd -a $USER docker
正在将用户“xxx”加入到“docker”组中
(base) xxx@dell-PowerEdge-T640:/var/run$ newgrp docker
(base) xxx@dell-PowerEdge-T640:/var/run$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
hello-world         latest              bf756fb1ae65        5 months ago        13.3kB

docker设置国内镜像加速

在上一部分deepin系统中我们已经设置过加速了,原理一样。将下面对文件添加如下内容,没有就创建,源对地址可以更换。

(base) xxx@dell-PowerEdge-T640:~$ cat /etc/docker/daemon.json 
{
	"registry-mirrors": ["https://05vdq5jc.mirror.aliyuncs.com", "https://docker.mirrors.ustc.edu.cn/", "https://hub-mirror.c.163.com/"],
        "data-root": "/data1/docker/docker"
}

重启docker服务

systemctl daemon-reload
sudo service docker restart

可以使用docker info查看换源是否成功。

设置后,下载mysql试一下:

(base) xxx@dell-PowerEdge-T640:~$ docker pull mysql
Using default tag: latest
latest: Pulling from library/mysql
8559a31e96f4: Pull complete 
d51ce1c2e575: Pull complete 
c2344adc4858: Pull complete 
fcf3ceff18fc: Pull complete 
16da0c38dc5b: Pull complete 
b905d1797e97: Pull complete 
4b50d1c6b05c: Pull complete 
c75914a65ca2: Pull complete 
1ae8042bdd09: Pull complete 
453ac13c00a3: Pull complete 
9e680cd72f08: Pull complete 
a6b5dc864b6c: Pull complete 
Digest: sha256:8b7b328a7ff6de46ef96bcf83af048cb00a1c86282bfca0cb119c84568b4caf6
Status: Downloaded newer image for mysql:latest
docker.io/library/mysql:latest

docker更换存储地址

$ sudo vim /etc/docker/daemon.json
# 添加data-root,不是graph
"data-root": "/data1/docker/docker"
$ systemctl daemon-reload
$ systemctl restart docker.service
posted @ 2020-06-27 15:29  巴蜀秀才  阅读(3039)  评论(0编辑  收藏  举报