Docker自学笔记(一)

Docker

容器化技术不是模拟一个完整的操作系统

概念

完整的Docker服务需要Client,Docker_Host、Registry

  • Client包含Build、Pull、Run,即运行命令的终端,可以与host处于同一物理机上

  • Docker_Host包含Containers(容器)、Images(镜像)、Daemon(服务)

    • Daemon:Docker守护进程,运行Containers

    • Containers:运行一个或者多个应用

    • Images:用于创建Containers

  • Registry是用来存储镜像的仓库


架构

CS架构,Client和Server可以同时存在于同一台物理机,docker以守护进程形式存在,不同的容器以localhost:<port>的形式作为访问


Docker安装

环境准备

检查内核

[root@docker_host ~]# uname -r
3.10.0-1160.el7.x86_64

检查系统版本

[root@docker_host ~]# cat /etc/os-release
NAME="CentOS Linux"
VERSION="7 (Core)"
ID="centos"
ID_LIKE="rhel fedora"
VERSION_ID="7"
PRETTY_NAME="CentOS Linux 7 (Core)"
ANSI_COLOR="0;31"
CPE_NAME="cpe:/o:centos:centos:7"
HOME_URL="https://www.centos.org/"
BUG_REPORT_URL="https://bugs.centos.org/"
​
CENTOS_MANTISBT_PROJECT="CentOS-7"
CENTOS_MANTISBT_PROJECT_VERSION="7"
REDHAT_SUPPORT_PRODUCT="centos"
REDHAT_SUPPORT_PRODUCT_VERSION="7"

卸载旧版本

yum remove docker \
          docker-client \
          docker-client-latest \
          docker-common \
          docker-latest \
          docker-latest-logrotate \
          docker-logrotate \
          docker-engine

需要的安装包

yum install -y yum-utils

设置镜像仓库

yum-config-manager \
   --add-repo \ https://download.docker.com/linux/centos/docker-ce.repo
#默认是国外的镜像库,国内库安装更快

安装docker相关的包

[root@docker_host ~]# yum install docker-ce docker-ce-cli containerd.io
#ce为社区版,ee为企业版需要许可证

启动docker

[root@docker_host ~]# systemctl start docker

测试是否可用——docker run hello-world

[root@docker_host ~]# docker run hello-world
Unable to find image 'hello-world:latest' locally   #查找本地是否有images
latest: Pulling from library/hello-world            #本地无images,去registry库pull镜像
2db29710123e: Pull complete
Digest: sha256:cc15c5b292d8525effc0f89cb299f1804f3a725c8d05e158653a563f15e4f685
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/
​

run流程

查看下载的images

[root@docker_host ~]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED        SIZE
hello-world   latest    feb5d9fea6a5   2 months ago   13.3kB
​

卸载docker

#1、卸载依赖
yum remove docker-ce docker-ce-cli containerd.io
​
#2、删除资源
 rm -rf /var/lib/docker #/var/lib/docker为docker的默认工作路径


Docker常用命令

帮助命令

docker versionc
docker info
docker <命令> --help

更多的命令可在docker官网命令帮助文档查询

镜像命令

1. docker images #查看本地images

#Usage:
docker images [OPTIONS] [REPOSITORY[:TAG]]
#e.g.
[root@docker_host ~]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED        SIZE
hello-world   latest    feb5d9fea6a5   2 months ago   13.3kB
​
#Annotation:
REPOSITORY  镜像的仓库源
TAG         镜像的标签
IMAGE ID    镜像的id
CREATED     镜像的创建时间
SIZE        镜像的大小
​
#Options:
  -a, --all             Show all images (default hides intermediate images)
      --digests         Show digests
  -f, --filter filter   Filter output based on conditions provided
      --format string   Pretty-print images using a Go template
      --no-trunc        Don't truncate output
  -q, --quiet           Only show image IDs
​

2. docker search #查看images

#Usage:
docker search [OPTIONS] TERM
#e.g.
[root@docker_host ~]# docker search mysql --filter=STARS=3000
NAME      DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
mysql     MySQL is a widely used, open-source relation…   11716     [OK]
mariadb   MariaDB Server is a high performing open sou…   4466      [OK]
​
​
#Options:
  -f, --filter filter   Filter output based on conditions provided
      --format string   Pretty-print search using a Go template
      --limit int       Max number of search results (default 25)
      --no-trunc        Don't truncate output
​

3. docker pull #下载镜像

#Usage:
docker pull [OPTIONS] NAME[:TAG|@DIGEST]
#e.g.
[root@docker_host ~]# docker pull mysql
Using default tag: latest               #如果命令不加tag,默认为latest
latest: Pulling from library/mysql
a10c77af2613: Pull complete             #分层下载,docker iamges的核心,联合文件系统
b76a7eb51ffd: Pull complete
258223f927e4: Pull complete
2d2c75386df9: Pull complete
63e92e4046c9: Pull complete
f5845c731544: Pull complete
bd0401123a9b: Pull complete
3ef07ec35f1a: Pull complete
c93a31315089: Pull complete
3349ed800d44: Pull complete
6d01857ca4c1: Pull complete
4cc13890eda8: Pull complete
Digest: sha256:aeecae58035f3868bf4f00e5fc623630d8b438db9d05f4d8c6538deb14d4c31b #签名
Status: Downloaded newer image for mysql:latest
docker.io/library/mysql:latest
​
#等价于
docker pull mysql
docker pull docker.io/library/mysql:latest
​
#Options:
  -a, --all-tags                Download all tagged images in the repository
      --disable-content-trust   Skip image verification (default true)
      --platform string         Set platform if server is multi-platform capable
  -q, --quiet                   Suppress verbose output
​

4. docker rmi #删除镜像

#Usage:
docker rmi [OPTIONS] IMAGE ID [IMAGE ID...]
#e.g.
[root@docker_host ~]# docker rmi -f feb5d9fea6a5			#删除指定容器
Untagged: hello-world:latest
Untagged: hello-world@sha256:cc15c5b292d8525effc0f89cb299f1804f3a725c8d05e158653a563f15e4f685
Deleted: sha256:feb5d9fea6a5e9606aa995e879d862b825965ba48de054caab5ef356dc6b3412

[root@docker_host ~]# docker rmi -f $(docker images -qa)	#删除所有容器
Untagged: mysql:5.7
Untagged: mysql@sha256:7a3a7b7a29e6fbff433c339fc52245435fa2c308586481f2f92ab1df239d6a29
Deleted: sha256:8b43c6af2ad08d95cdcb415d245446909a6cbc1875604c48c4325972e5b00442
Deleted: sha256:aad43f4d2f66438acd2d156216cd544a728851238714975c38d9a690f68afc57
Deleted: sha256:7b9addbc002c1e828aee7ec5c2679b04a591b6fa2b96002701ddee9d4ed54395
Deleted: sha256:b00f8e4e6ce8920fb563615503f232799ab380b338c3f2cbb5e86a2d762a6e80
Deleted: sha256:8fbabb17fd7b46a59cc15301741bf73a527b862f59cc6e84fae15b4dd5c425c0
Untagged: mysql:latest
Untagged: mysql@sha256:aeecae58035f3868bf4f00e5fc623630d8b438db9d05f4d8c6538deb14d4c31b
Deleted: sha256:b05128b000ddbafb0a0d2713086c6a1cc23280dee3529d37f03c98c97c8cf1ed
Deleted: sha256:2920230e18d6833c32c9f851905df9d3e2958a43b771c84908234ac031b25a45
Deleted: sha256:a790dd6a368bc9aa7d1b251b46ac2fc718ebae5a38ed51ff89ff99955dadaa35
Deleted: sha256:cd87c1db4b159f37f092e73a52c10d5ccb837ed7bfcdc3b008038540390454a4
Deleted: sha256:7f92300b04af4aef96d5ef6fab1e27456cef354eca04733d396ad74478bee7d8
Deleted: sha256:6a59f55eb4945598b4889ea269d79f8b99563c96e97ba2373e19712732d20352
Deleted: sha256:87030c256d8077b4d969e5819f5da01ed08f29e115eaec61b58b3f3134175e1e
Deleted: sha256:b1694d0bb0b1be63e940478b93aa34f46e18f8371539ccee3b5d580cbf576812
Deleted: sha256:f323fd0baccb89f82a5711fa6291f3b4c977b85c3bbba59b1080205b498133b1
Deleted: sha256:47a2799e90faa9d9aaaa4b63457390dcbf5b26ce67f0926821c50b982d741e32
Deleted: sha256:156f55d34ef3e567ef39380f8d86f7c946927a099a43205de8721e60bfef526e
Deleted: sha256:bb282bb84eb90a6040504a46f462ebe55cb9623df13219fc39f434a53ccd1687
Deleted: sha256:77b323d4ec74aad770337f99a60e862a64ccc53f4775b5f4945df0e606f78b90


#Options:
  -f, --force      Force removal of the image
      --no-prune   Do not delete untagged parents

容器命令

拥有Images之后才能创建Containers,下载一个Centos image

[root@docker_host ~]# docker pull centos

1. 新建容器并启动——docker run

#Usage:
docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
​
#Options:
--name="Name"       容器名字,用于区分容器
-d                  后台方式运行
-it                 使用交户繁使运行,进入容器查看内容
-p                  指定容器端口
    -p ip:主机端口:容器端口
    -p 主机端口:容器端口
    -p 容器端口
    容器端口
-P                  随机指定端口
​
#启动并进入容器
[root@docker_host /]# docker run -it centos
[root@b78a9bc63f28 /]# ls
bin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
​
#退出容器
[root@b78a9bc63f28 /]# exit
exit
[root@docker_host /]# ls
bin  boot  dev  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var

2. 列出运行容器——docker ps

#Usage:
docker ps [OPTIONS]
​
#Options:
  -a, --all             Show all containers (default shows just running)
  -f, --filter filter   Filter output based on conditions provided
      --format string   Pretty-print containers using a Go template
  -n, --last int        Show n last created containers (includes all states) (default -1)
  -l, --latest          Show the latest created container (includes all states)
      --no-trunc        Don't truncate output
  -q, --quiet           Only display container IDs
  -s, --size            Display total file sizes
​
​
#e.g.
[root@docker_host /]# docker ps         #查看运行中的容器
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
[root@docker_host /]# docker ps -a      #查看历史运行
CONTAINER ID   IMAGE          COMMAND       CREATED              STATUS                          PORTS     NAMES
b78a9bc63f28   centos         "/bin/bash"   About a minute ago   Exited (0) About a minute ago             sad_hermann
[root@docker_host /]# docker ps -a -n=2 #查看最近运行的2个容器
CONTAINER ID   IMAGE     COMMAND       CREATED         STATUS                     PORTS     NAMES
b78a9bc63f28   centos    "/bin/bash"   4 minutes ago   Exited (0) 4 minutes ago             sad_hermann
b3fb1be5e602   centos    "/bin/bash"   5 minutes ago   Exited (0) 5 minutes ago             exciting_kilby
[root@docker_host /]# docker ps -aq     #列出最近运行的容器ID
b78a9bc63f28
b3fb1be5e602

3. 退出容器

exit		#直接容器停止并退出
Ctrl+P+Q 	#容器不停止退出
#不停止退出
[root@docker_host ~]# docker run -it centos
[root@6296ee0351ac /]# [root@docker_host ~]#
[root@docker_host ~]# docker ps
CONTAINER ID   IMAGE     COMMAND       CREATED          STATUS          PORTS     NAMES
6296ee0351ac   centos    "/bin/bash"   11 seconds ago   Up 11 seconds             pensive_knuth

4. 删除容器--docker rm

#Usage:
docker rm [OPTIONS] CONTAINER [CONTAINER...]

#Options:
  -f, --force     Force the removal of a running container (uses SIGKILL)
  -l, --link      Remove the specified link
  -v, --volumes   Remove anonymous volumes associated with the container

#e.g.
[root@docker_host ~]# docker rm b78a9bc63f28			#删除指定容器
b78a9bc63f28
[root@docker_host ~]# docker rm 6296ee0351ac			#无法删除正在运行的容器,需要添加-f选项
Error response from daemon: You cannot remove a running container 6296ee0351ac8f9b0c9782d05627496956857e224dfb60098c0b5be7e8acd1c8. Stop the container before attempting removal or force remove
[root@docker_host ~]# docker rm -f $(docker ps -aq)		#删除所有容器
6296ee0351ac
f40bf429a83b
7af74e991c70
ef1a07ea65f9

docker ps -a -q|xargs docker rm #删除所有容器

5. 启动和停止容器的操作

docker start [Containter ID]	#启动容器
docker restart [Containter ID]	#重启容器
docker stop [Containter ID]		#停止当前运行的容器
docker kill [Containter ID]		#强制停止当前容器

常用命令

后台启动容器

#docker run -d [IMAGE ID]
#后台启动容器
[root@docker_host ~]# docker run -d centos
049c7ed4ee62e33152f77fd3b9172442893cda4d83c6cf088539c0e6144127f3
[root@docker_host ~]# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
​
#? docker ps查看,发现容器停止
docker容器使用后台运行,就必须要有一个前台进程,docker发现没有应用,就会自动停止,
例如nginx,容器启动后,发现没有提供服务,就会自动停止,就是没有程序了.

查看后台日志

docker logs     #查看后台日志
​
#Usage:
docker logs [OPTIONS] CONTAINER
​
#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:37Z) or relative (e.g. 42m for 42 minutes)
  -n, --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:37Z) or relative (e.g. 42m for 42 minutes)
​
#e.g.
[root@docker_host ~]# docker run -d centos /bin/bash -c "while true;do echo 1;sleep 2;done"
7d48587375ff57bc3ed0a61edd5ed0d8e6c6fac0cc1e8c04a58b90c496f1c367
[root@docker_host ~]# docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED         STATUS         PORTS     NAMES
7d48587375ff   centos    "/bin/bash -c 'while…"   5 seconds ago   Up 5 seconds             nervous_panini
[root@docker_host ~]# docker logs -tf --tail 10 7d48587375ff
2021-11-24T05:53:52.547262585Z 1
2021-11-24T05:53:54.550174812Z 1
2021-11-24T05:53:56.555363368Z 1
2021-11-24T05:53:58.558915139Z 1
2021-11-24T05:54:00.562202370Z 1
2021-11-24T05:54:02.566820454Z 1
2021-11-24T05:54:04.569069262Z 1
2021-11-24T05:54:06.572305808Z 1
2021-11-24T05:54:08.575295196Z 1
2021-11-24T05:54:10.578249903Z 1
2021-11-24T05:54:12.582419678Z 1
​

查看容器中进程信息

docker top      #查看容器中进程
​
#Usage:
docker top CONTAINER [ps OPTIONS]
​
#e.g.
[root@docker_host ~]# docker top 7d48587375ff
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                21716               21697               0                   00:53               ?                   00:00:00            /bin/bash -c while true;do echo 1;sleep 2;done
root                21923               21716               0                   00:57               ?                   00:00:00            /usr/bin/coreutils --coreutils-prog-shebang=sleep /usr/bin/sleep 2
​

查看容器的元数据

docker inspect  #查看容器元数据
​
#Usage:
docker inspect [OPTIONS] NAME|ID [NAME|ID...]
​
#Options:
  -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
​

操作当前正在运行的容器

方式一:
docker exec     #操作正在运行的容器,进入容器后开启一个新的终端,可以在里面操作
​
#Usage:
docker exec [OPTIONS] CONTAINER COMMAND [ARG...]
​
#Options:
  -d, --detach               Detached mode: run command in the background
      --detach-keys string   Override the key sequence for detaching a container
  -e, --env list             Set environment variables
      --env-file list        Read in a file of environment variables
  -i, --interactive          Keep STDIN open even if not attached
      --privileged           Give extended privileges to the command
  -t, --tty                  Allocate a pseudo-TTY
  -u, --user string          Username or UID (format: <name|uid>[:<group|gid>])
  -w, --workdir string       Working directory inside the container
​
#e.g.
[root@docker_host ~]# docker exec -it 7d48587375ff /bin/bash
[root@7d48587375ff /]# ps -ef
UID         PID   PPID  C STIME TTY          TIME CMD
root          1      0  0 05:53 ?        00:00:00 /bin/bash -c while true;do echo 1;sleep 2;done
root        293      0  0 06:03 pts/0    00:00:00 /bin/bash
root        316      1  0 06:03 ?        00:00:00 /usr/bin/coreutils --coreutils-prog-shebang=sleep /usr/bin/sleep 2
root        317    293  0 06:03 pts/0    00:00:00 ps -ef
​
​
方式二:
docker attach   #将本地标准输入、输出和错误流附加到运行的容器,进入容器正在执行的终端,不会启动新的终端
​
#Usage:
docker attach [OPTIONS] CONTAINER
​
#Options:
      --detach-keys string   Override the key sequence for detaching a container
      --no-stdin             Do not attach STDIN
      --sig-proxy            Proxy all received signals to the process (default true)
​

拷贝文件

docker cp   #拷贝容器内容的数据
​
#Usage:
docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH|-
docker cp [OPTIONS] SRC_PATH|- CONTAINER:DEST_PATH
​
#Options:
  -a, --archive       Archive mode (copy all uid/gid information)
  -L, --follow-link   Always follow symbol link in SRC_PATH
​
#e.g.
#在容器内创建文件
[root@e50d4bc9fdaf home]# echo "hello world" > work
[root@e50d4bc9fdaf home]# ls
work
​
#将容器中的文件拷贝到主机上
[root@docker_host ~]# docker cp e50d4bc9fdaf:/home/work .

总结


练习

部署Nginx

#1、查找Nginx镜像
[root@docker_host ~]# docker search nginx
[root@docker_host ~]# docker pull nginx
​
#2、下载镜像到本地
[root@docker_host ~]# docker images
REPOSITORY   TAG       IMAGE ID       CREATED        SIZE
nginx        latest    ea335eea17ab   7 days ago     141MB
centos       latest    5d0da3dc9764   2 months ago   231MB
​
#3、启动容器,指定端口映射
[root@docker_host ~]# docker run -d -p 80:80 --name nginx01 nginx
0c3dcff8bd06658dcdec8c7cb6a9f23510be1298e60794c32d8c8b23a263137a
[root@docker_host ~]# docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED         STATUS         PORTS                                   NAMES
0c3dcff8bd06   nginx     "/docker-entrypoint.…"   5 seconds ago   Up 3 seconds   0.0.0.0:80->80/tcp, :::9602->80/tcp   nginx01
​
#4、成功创建
[root@docker_host ~]# curl localhost

部署多个nginx容器

#创建第2个nginx时会报错,可能会出现以下报错
[root@docker_host ~]# docker run -it -p 80:80 --name nginx01 nginx
/docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
/docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
/docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
10-listen-on-ipv6-by-default.sh: info: Getting the checksum of /etc/nginx/conf.d/default.conf
10-listen-on-ipv6-by-default.sh: info: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf
/docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
/docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh
/docker-entrypoint.sh: Configuration complete; ready for start up
2021/11/24 13:42:33 [notice] 1#1: using the "epoll" event method
​
#此时无法创建新的nginx,可能是缺少nginx的配置文件
#拷贝容器的配置文件
[root@docker_host ~]# docker cp nginx01:/etc/nginx /home/nginx
[root@docker_host nginx]# docker cp nginx01:/usr/share/nginx/html /home/html
​
#通过挂载的形式启动第二个nginx容器
[root@docker_host html]# docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED         STATUS         PORTS                               NAMES
5b9d98c9fe99   nginx     "/docker-entrypoint.…"   5 minutes ago   Up 5 minutes   0.0.0.0:80->80/tcp, :::80->80/tcp   nginx01
[root@docker_host html]# docker run -d --name nginx-test -p 9024:80 -v /home/html:/usr/share/nginx/html -v /home/nginx:/etc/nginx nginx
5e6b0c275ef80ffa1e61fb4acdfd90a025ea9edd38e13e37a871a0b7d259ad01
[root@docker_host html]# docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED         STATUS         PORTS                                   NAMES
5e6b0c275ef8   nginx     "/docker-entrypoint.…"   9 seconds ago   Up 8 seconds   0.0.0.0:9024->80/tcp, :::9024->80/tcp   nginx-test
5b9d98c9fe99   nginx     "/docker-entrypoint.…"   6 minutes ago   Up 6 minutes   0.0.0.0:80->80/tcp, :::80->80/tcp       nginx01
​

容器端口暴露

创建容器指定端口:docker run -p [port1]:[port2]

port1为对外提供服务的端口==>[docker host]:[port1]

port2为docker hosts内部访问容器的端口==>[Container2]:[port2]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值