Docker的基本用法

Docker的基本用法

什么是Docker

docker中的容器:

lxc --> libcontainer --> runC

OCI&OCF

OCI

开源的容器协议(Open Container-initiative)

  • 由Linux基金会主导于2015年6月创立
  • 旨在围绕容器格式和运行时制定一个开放的工业化标准
  • 包含以下两个标准
    • 运行规范(runtime-spec)
    • 图像规范(image-spec)

OCF

开源的容器格式(Open Container Format)

runC 是一个命令行工具,运行容器记录的一个标准

  • 容器是以runC为子进程的方式启动,并且可以被其他的系统引用,不需要启动为守护模式进程
  • runC 可以构建我们的容器,并且可以被数以百万的存储引擎使用

docker提供了一个专门容纳容器镜像的站点:https://hub.docker.com

以下是网站的注册与使用步骤

打开上面这个网址

点击右上角的sign up注册,填写信息即可

点击sign up进入网站之后,可以搜索你需要的镜像仓库

以httpd为例,可以自行选择

Docker架构

  • 这里的ClientDOCKER_HOST(docker server)都是在本地的,docker仓库Registry是在远程的,也可以在本地

  • Client的docker命令通过Docker daemondocker server镜像交互

  • images镜像是由应用已经被docker打包好的镜像,如java、nginx的镜像,这些镜像可以运行在容器containers

  • 每一个container容器都是运行在docker server(宿主机)上的,每一个container容器都是隔离的、独立的

  • 每一个container容器相当于一个Linux操作系统,每一个container容器都有自己的ip地址,所以可以在不同的container上设置相同的端口号

Docker镜像与镜像仓库

为什么镜像仓库名字是Registry而不是repository?在docker中仓库的名字是以应用的名称取名的。

镜像是静态的,而容器是动态的,容器有其生命周期,镜像与容器的关系类似于程序与进程的关系。镜像类似于文件系统中的程序文件,而容器则类似于将一个程序运行起来的状态,也即进程。所以容器是可以删除的,容器被删除后其镜像是不会被删除的。

Docker对象

当您使用docker时,您可以创建和使用镜像、容器、网络、存储卷、插件和其他对象。

  • 镜像
    • 一个镜像是只读的模板,是用来创建docker容器的
    • 经常情况, 一个镜像是基于另外一个镜像生成的,加上一些特定的内同
    • 您可以创建您自己的镜像,也可以使用别人在网站上传的镜像
  • 容器
    • 容器是一个用镜像运行的实例
    • 您可以使用命令行模式或者API进行创建,运行,停止,移动,删除容器
    • 您可以将容器连接到一个或多个网络,将存储连接到容器,甚至可以基于其当前状态创建新映像。

安装及使用Docker

Docker安装

//进入目录
[root@localhost ~]# cd /etc/yum.repos.d/

//下载
[root@localhost yum.repos.d]# curl -o docker-ce.repo https://mirrors.tuna.tsinghua.edu.cn/docker-ce/linux/centos/docker-ce.repo
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  1919  100  1919    0     0    347      0  0:00:05  0:00:05 --:--:--   431

//查看一下
[root@localhost yum.repos.d]# ls
CentOS-Base.repo   epel-playground.repo       epel-testing.repo
docker-ce.repo     epel.repo                  redhat.repo
epel-modular.repo  epel-testing-modular.repo

//清理缓存
[root@localhost yum.repos.d]# yum clean all
Updating Subscription Management repositories.
Unable to read consumer identity
This system is not registered to Red Hat Subscription Management. You can use subscription-manager to register.
34 files removed

//查看一些docker有哪些包
[root@localhost yum.repos.d]# yum list all|grep docker
containerd.io.x86_64                                   1.4.3-3.1.el8                                     docker-ce-stable
docker-ce.x86_64                                       3:20.10.3-3.el8                                   docker-ce-stable
docker-ce-cli.x86_64                                   1:20.10.3-3.el8                                   docker-ce-stable
docker-ce-rootless-extras.x86_64                       20.10.3-3.el8                                     docker-ce-stable
pcp-pmda-docker.x86_64                                 5.1.1-3.el8                                       AppStream       
podman-docker.noarch                                   2.2.1-7.module_el8.3.0+699+d61d9c41               AppStream       
python2-dockerpty.noarch                               0.4.1-18.el8                                      epel            
python3-dockerpty.noarch                               0.4.1-18.el8                                      epel            
standard-test-roles-inventory-docker.noarch            4.10-1.el8                                        epel

//安装docker-ce包
[root@localhost yum.repos.d]# yum -y install docker-ce
Updating Subscription Management repositories.
Unable to read consumer identity
This system is not registered to Red Hat Subscription Management. You can use subscription-manager to register.
AppStream                                            1.7 MB/s | 6.3 MB     00:03    
BaseOS                                               1.4 MB/s | 2.3 MB     00:01    
Docker CE Stable - x86_64                            103  B/s | 9.2 kB     01:31    
epel                                                 3.8 MB/s | 8.9 MB     00:02    
Last metadata expiration check: 0:00:01 ago on Thu 25 Feb 2021 09:22:09 PM CST.
Dependencies resolved.
=====================================================================================
 Package           Arch   Version                             Repository        Size
=====================================================================================
Installing:
 docker-ce         x86_64 3:20.10.3-3.el8                     docker-ce-stable  27 M
Upgrading:
 libsemanage       x86_64 2.9-3.el8                           BaseOS           165 k
Installing dependencies:
 checkpolicy       x86_64 2.9-1.el8                           BaseOS           348 k

Installed:
  checkpolicy-2.9-1.el8.x86_64                                                       
                                               
  docker-ce-3:20.10.3-3.el8.x86_64                                                   
  ......                                 
  python3-setools-4.3.0-2.el8.x86_64                                                 
  slirp4netns-1.1.8-1.module_el8.3.0+699+d61d9c41.x86_64                             

Complete!

//启动docker
[root@localhost ~]# systemctl enable  --now docker
Created symlink /etc/systemd/system/multi-user.target.wants/docker.service → /usr/lib/systemd/system/docker.service.

//查看docker运行状态
[root@localhost ~]# systemctl status docker
● docker.service - Docker Application Container Engine
   Loaded: loaded (/usr/lib/systemd/system/docker.service; enabled; vendor preset: d>
   Active: active (running) since Thu 2021-02-25 21:36:19 CST; 12s ago
     Docs: https://docs.docker.com
 Main PID: 13448 (dockerd)
    Tasks: 12
   Memory: 48.6M
   CGroup: /system.slice/docker.service
           └─13448 /usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd>

Feb 25 21:36:19 localhost.localdomain dockerd[13448]: time="2021-02-25T21:36:19.2105>
Feb 25 21:36:19 localhost.localdomain dockerd[13448]: time="2021-02-25T21:36:19.2400>
Feb 25 21:36:19 localhost.localdomain dockerd[13448]: time="2021-02-25T21:36:19.2401>
Feb 25 21:36:19 localhost.localdomain dockerd[13448]: time="2021-02-25T21:36:19.2403>
Feb 25 21:36:19 localhost.localdomain dockerd[13448]: time="2021-02-25T21:36:19.4002>
Feb 25 21:36:19 localhost.localdomain dockerd[13448]: time="2021-02-25T21:36:19.4721>
Feb 25 21:36:19 localhost.localdomain dockerd[13448]: time="2021-02-25T21:36:19.4919>
Feb 25 21:36:19 localhost.localdomain dockerd[13448]: time="2021-02-25T21:36:19.4921>
Feb 25 21:36:19 localhost.localdomain systemd[1]: Started Docker Application Contain>
Feb 25 21:36:19 localhost.localdomain dockerd[13448]: time="2021-02-25T21:36:19.5139>

Docker加速

docker-ce的配置文件是/etc/docker/daemon.json,此文件默认不存在,需要我们手动创建并进行配置,而docker的加速就是通过配置此文件来实现的。

docker的加速有多种方式:

  • docker cn
  • 中国科技大学加速器
  • 阿里云加速器(需要通过阿里云开发者平台注册帐号,免费使用个人私有的加速器)

这里使用的是阿里云加速器,获取加速方式如下

https://www.aliyun.com/

登录账号

点击右上角我的阿里云,点击我的账号,看到下面的画面

点击左上方的橙色图标,点击产品与服务,选择容器镜像服务

点击左侧镜像加速器

复制加速地址,粘贴到daemon.json文件中即可

设置加速器

//编辑daemon.json
[root@localhost ~]# vim /etc/docker/daemon.json

{
            "registry-mirrors": ["https://zyva0762.mirror.aliyuncs.com"]
}

//重读一下文件,重启rocker
[root@localhost ~]# systemctl daemon-reload
[root@localhost ~]# systemctl restart docker

//查看一下docker的信息
[root@localhost ~]# docker info
Client:
 Context:    default
 Debug Mode: false
 Plugins:
  app: Docker App (Docker Inc., v0.9.1-beta3)
  buildx: Build with BuildKit (Docker Inc., v0.5.1-docker)
....
....
....
 Registry Mirrors:
  https://zyva0762.mirror.aliyuncs.com/       #已经修改成我的加速器了
 Live Restore Enabled: false

WARNING: No blkio weight support
WARNING: No blkio weight_device support

Docker的常用操作

命令 功能
docker search Search the Docker Hub for images
docker pull Pull an image or a repository from a registry
docker images List images
docker create Create a new conntainer
docker start Start one or more stopped containers
docker run Run a command in a new container
docker attach Attach to a runninng container
docker ps List containers
docker logs Fetch the logs of a container
docker restart Restart a container
docker stop Stop one or more running containers
docker kill Kill one or more running containers
docker rm Remove onne or more containers
docker exec Run a command in a running container
docker info Display system-wide information
docker inspect Return low-level information on Docker objects

演示如下:

  1. docker search 在官网上搜索镜像
[root@localhost ~]# docker search httpd
NAME                                    DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
httpd                                   The Apache HTTP Server Project                  3371      [OK]       
centos/httpd-24-centos7                 Platform for running Apache httpd 2.4 or bui…   36                   
centos/httpd                                                                            33                   [OK]
polinux/httpd-php                       Apache with PHP in Docker (Supervisor, CentO…   4                    [OK]
salim1983hoop/httpd24                   Dockerfile running apache config                2                    [OK]
lead4good/httpd-fpm                     httpd server which connects via fcgi proxy h…   1                    [OK]
solsson/httpd-openidc                   mod_auth_openidc on official httpd image, ve…   1                    [OK]
inanimate/httpd-ssl                     A play container with httpd, ssl enabled, an…   1                    [OK]
  1. docker pull 下载官网的镜像,不加版本号默认下载最新版本
[root@localhost ~]# docker pull httpd
Using default tag: latest
latest: Pulling from library/httpd
a076a628af6f: Pull complete 
e444656f7792: Pull complete 
0ec35e191b09: Pull complete 
4aad5d8db1a6: Pull complete 
eb1da3ea630f: Pull complete 
Digest: sha256:2fab99fb3b1c7ddfa99d7dc55de8dad0a62dbe3e7c605d78ecbdf2c6c49fd636
Status: Downloaded newer image for httpd:latest
docker.io/library/httpd:latest

//下载2.4版本
[root@localhost ~]# docker pull httpd:2.4-alpine
2.4-alpine: Pulling from library/httpd
801bfaa63ef2: Pull complete 
ac8f86b44b17: Pull complete 
078b6c86de97: Pull complete 
55f318a9c48a: Pull complete 
5da5afdb6ea0: Pull complete 
Digest: sha256:17e9cafb91cbe2388a685d74c3ee2084d3bfbd144f839a5f2245b7f8ef350564
Status: Downloaded newer image for httpd:2.4-alpine
docker.io/library/httpd:2.4-alpine
  1. docker images 查看有哪些镜像
[root@localhost ~]# docker images
REPOSITORY   TAG          IMAGE ID       CREATED        SIZE
httpd        latest       683a7aad17d3   6 weeks ago    138MB
httpd        2.4-alpine   5d779ff71c18   2 months ago   55.5MB
  1. docker create 创建一个容器
[root@localhost ~]# docker create httpd:2.4-alpine
479549495e63afa91382de2f073d3a4d5592ce03eac899f4eefda883ed86d1b5
  1. docker ps 查看正在运行的容器;-a 表示所有的容器
[root@localhost ~]# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
[root@localhost ~]# docker ps -a
CONTAINER ID   IMAGE              COMMAND              CREATED          STATUS    PORTS     NAMES
479549495e63   httpd:2.4-alpine   "httpd-foreground"   16 seconds ago   Created             dreamy_zhukovsky
  1. docker start 启动容器
[root@localhost ~]# docker start 479549495e63
479549495e63
[root@localhost ~]# docker ps
CONTAINER ID   IMAGE              COMMAND              CREATED         STATUS          PORTS     NAMES
479549495e63   httpd:2.4-alpine   "httpd-foreground"   2 minutes ago   Up 11 seconds   80/tcp    dreamy_zhukovsky
  1. docker stop 停止容器运行
[root@localhost ~]# docker stop 479549495e63
479549495e63
[root@localhost ~]# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
  1. docker restart 重启容器
[root@localhost ~]# docker start 479549495e63
479549495e63
[root@localhost ~]# docker restart 479549495e63
479549495e63
[root@localhost ~]# docker ps -a
CONTAINER ID   IMAGE              COMMAND              CREATED         STATUS         PORTS     NAMES
479549495e63   httpd:2.4-alpine   "httpd-foreground"   4 minutes ago   Up 5 seconds   80/tcp    dreamy_zhukovsky
  1. docker kill 强制终止一个容器;不推荐使用,使用docker stop就可以了
[root@localhost ~]# docker kill 479549495e63
479549495e63
[root@localhost ~]# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
  1. docker rm 删除一个容器,不能删除正在运行的容器;-f可以删除正在运行的容器;rmi删除镜像
[root@localhost ~]# docker rm 479549495e63
479549495e63
[root@localhost ~]# docker ps -a
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES

//docker rm -f 加ID
[root@localhost ~]# docker ps
CONTAINER ID   IMAGE          COMMAND              CREATED         STATUS         PORTS     NAMES
f129d2d151f2   httpd:latest   "httpd-foreground"   3 minutes ago   Up 3 minutes   80/tcp    amazing_easley
[root@localhost ~]# docker rm -f f129d2d151f2
f129d2d151f2
[root@localhost ~]# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES

//docker rmi 镜像,镜像在被容器使用的时候是不能被删除的
[root@localhost ~]# docker images
REPOSITORY   TAG          IMAGE ID       CREATED        SIZE
httpd        latest       683a7aad17d3   6 weeks ago    138MB
httpd        2.4-alpine   5d779ff71c18   2 months ago   55.5MB
[root@localhost ~]# docker rmi httpd:2.4-alpine
Untagged: httpd:2.4-alpine
Untagged: httpd@sha256:17e9cafb91cbe2388a685d74c3ee2084d3bfbd144f839a5f2245b7f8ef350564
Deleted: sha256:5d779ff71c188aa6da896ffdab929ca0cb1d859dc74650e57b9d8ce2bb6debff
Deleted: sha256:7ff2770ecf5a3570c9ba55503b58520ebac9d4a1d84e5eb3b693060d337cdd69
Deleted: sha256:9a48afd4f32baa214eb8c5bdf7012db015d2b08f788e72a67034fb42154d5497
Deleted: sha256:af27dad83ccfd6e69381c331c1065c5f3673f0ffdff9497561c54dbfad8c072a
Deleted: sha256:1e8b3e8b01c784685f9aea947db87649956275ee322a06461deba37bf969ae91
Deleted: sha256:777b2c648970480f50f5b4d0af8f9a8ea798eea43dbcf40ce4a8c7118736bdcf
[root@localhost ~]# docker images
REPOSITORY   TAG       IMAGE ID       CREATED       SIZE
httpd        latest    683a7aad17d3   6 weeks ago   138MB
  1. docker run 直接运行一个容器;-d在后台运行
[root@localhost ~]# docker run httpd:latest
AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using 172.17.0.2. Set the 'ServerName' directive globally to suppress this message
AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using 172.17.0.2. Set the 'ServerName' directive globally to suppress this message
[Thu Feb 25 16:55:11.715951 2021] [mpm_event:notice] [pid 1:tid 139832154334336] AH00489: Apache/2.4.46 (Unix) configured -- resuming normal operations
[Thu Feb 25 16:55:11.716402 2021] [core:notice] [pid 1:tid 139832154334336] AH00094: Command line: 'httpd -D FOREGROUND'

//在另一个终端上查看,正在运行
[root@localhost ~]# docker ps
CONTAINER ID   IMAGE          COMMAND              CREATED          STATUS          PORTS     NAMES
f129d2d151f2   httpd:latest   "httpd-foreground"   19 seconds ago   Up 18 seconds   80/tcp    amazing_easley

//docker run -d 加ID
[root@localhost ~]# docker run -d httpd:latest
7e9aac433228658270891940761d3f913405d2d98b79e150e7de57faee162cfc
[root@localhost ~]# docker ps
CONTAINER ID   IMAGE          COMMAND              CREATED         STATUS         PORTS     NAMES
7e9aac433228   httpd:latest   "httpd-foreground"   9 seconds ago   Up 7 seconds   80/tcp    adoring_keldysh
  1. docker logs 查看容器日志
[root@localhost ~]# docker logs 7e9aac433228
AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using 172.17.0.2. Set the 'ServerName' directive globally to suppress this message
AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using 172.17.0.2. Set the 'ServerName' directive globally to suppress this message
[Thu Feb 25 17:01:08.595134 2021] [mpm_event:notice] [pid 1:tid 140342005355648] AH00489: Apache/2.4.46 (Unix) configured -- resuming normal operations
[Thu Feb 25 17:01:08.595473 2021] [core:notice] [pid 1:tid 140342005355648] AH00094: Command line: 'httpd -D FOREGROUND'

//在一台终端上访问IP
[root@localhost ~]# curl 172.17.0.2
<html><body><h1>It works!</h1></body></html>

//生成新的日志
[root@localhost ~]# docker logs 7e9aac433228
AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using 172.17.0.2. Set the 'ServerName' directive globally to suppress this message
AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using 172.17.0.2. Set the 'ServerName' directive globally to suppress this message
[Thu Feb 25 17:01:08.595134 2021] [mpm_event:notice] [pid 1:tid 140342005355648] AH00489: Apache/2.4.46 (Unix) configured -- resuming normal operations
[Thu Feb 25 17:01:08.595473 2021] [core:notice] [pid 1:tid 140342005355648] AH00094: Command line: 'httpd -D FOREGROUND'
172.17.0.1 - - [25/Feb/2021:17:04:59 +0000] "GET / HTTP/1.1" 200 45

  1. docker inspect 查看容器的各种信息
[root@localhost ~]# docker inspect 7e9aac433228

                    "Gateway": "172.17.0.1",
                    "IPAddress": "172.17.0.2",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:ac:11:00:02",
                    "DriverOpts": null                  
  1. docker info 查看docker整个的信息
[root@localhost ~]# docker info
Client:
 Context:    default
 Debug Mode: false
 Plugins:
  app: Docker App (Docker Inc., v0.9.1-beta3)
  buildx: Build with BuildKit (Docker Inc., v0.5.1-docker)

Server:
 Containers: 1
  Running: 1
  Paused: 0
  Stopped: 0
 Images: 2
 Server Version: 20.10.3
 Storage Driver: overlay2
  Backing Filesystem: xfs
  Supports d_type: true
  Native Overlay Diff: true
 Logging Driver: json-file
 Cgroup Driver: cgroupfs
 Cgroup Version: 1
.....
.....
WARNING: No blkio weight support
WARNING: No blkio weight_device support
  1. docker attach 进入容器内部,但是不能操作,退出会终止容器,不推荐使用
[root@localhost ~]# docker images
REPOSITORY   TAG       IMAGE ID       CREATED       SIZE
httpd        latest    683a7aad17d3   6 weeks ago   138MB
[root@localhost ~]# docker run -d httpd
61a144d4c0400fa09d3c14ed3ef0e18cf063e277624cd42d93a9d5186e4c610f
[root@localhost ~]# docker ps
CONTAINER ID   IMAGE     COMMAND              CREATED         STATUS         PORTS     NAMES
61a144d4c040   httpd     "httpd-foreground"   5 seconds ago   Up 4 seconds   80/tcp    stoic_hofstadter

//在另外一个终端查看网站
[root@localhost ~]# curl 172.17.0.2
<html><body><h1>It works!</h1></body></html>
[root@localhost ~]# curl 172.17.0.2
<html><body><h1>It works!</h1></body></html>
[root@localhost ~]# curl 172.17.0.2
<html><body><h1>It works!</h1></body></html>
[root@localhost ~]# curl 172.17.0.2
<html><body><h1>It works!</h1></body></html>
[root@localhost ~]# curl 172.17.0.2
<html><body><h1>It works!</h1></body></html>
[root@localhost ~]# curl 172.17.0.2
<html><body><h1>It works!</h1></body></html>

//进入容器可以看见有人在访问容器,但是不能进行任何操作,只可以观察,而且不方便退出
[root@localhost ~]# docker attach 61a144d4c040
172.17.0.1 - - [25/Feb/2021:17:23:21 +0000] "GET / HTTP/1.1" 200 45
172.17.0.1 - - [25/Feb/2021:17:23:21 +0000] "GET / HTTP/1.1" 200 45
172.17.0.1 - - [25/Feb/2021:17:23:22 +0000] "GET / HTTP/1.1" 200 45
172.17.0.1 - - [25/Feb/2021:17:23:22 +0000] "GET / HTTP/1.1" 200 45
172.17.0.1 - - [25/Feb/2021:17:23:23 +0000] "GET / HTTP/1.1" 200 45

  1. docker exec 进入容器;-it 表示交互模式,可以执行命令并且退出不会停止容器,exit退出
//后面加上bin/bash 可以执行命令
[root@localhost ~]# docker exec -it 61a144d4c040 /bin/bash
root@61a144d4c040:/usr/local/apache2# ls
bin  build  cgi-bin  conf  error  htdocs  icons  include  logs	modules
root@61a144d4c040:/usr/local/apache2# cd bin/
root@61a144d4c040:/usr/local/apache2/bin# ls
ab	   apxs      dbmmanage	envvars-std  htcacheclean  htdigest  httpd	logresolve  suexec
apachectl  checkgid  envvars	fcgistarter  htdbm	   htpasswd  httxt2dbm	rotatelogs
root@61a144d4c040:/usr/local/apache2# exit
exit
[root@localhost ~]# docker ps
CONTAINER ID   IMAGE     COMMAND              CREATED          STATUS         PORTS     NAMES
61a144d4c040   httpd     "httpd-foreground"   13 minutes ago   Up 5 minutes   80/tcp    stoic_hofstadter

Docker event state

img

一个容器在某个时刻可能处于以下几种状态之一:

  • created:已经被创建 (使用 docker ps -a 命令可以列出)但是还没有被启动 (使用 docker ps 命令还无法列出)
  • running:运行中
  • paused:容器的进程被暂停了
  • restarting:容器的进程正在重启过程中
  • exited:上图中的 stopped 状态,表示容器之前运行过但是现在处于停止状态(要区别于 created 状态,它是指一个新创出的尚未运行过的容器)。可以通过 start 命令使其重新进入 running 状态
  • destroyed:容器被删除了,再也不存在了
原文地址:https://www.cnblogs.com/leixixi/p/14450259.html