docker容器技术基础入门

1、LXC常用操作

环境centos7

//准备工作
[root@localhost ~]# yum -y install epel-release  //安装epel源

[root@localhost ~]# yum -y install lxc lxc-templates bridge-utils lxc-libs libcgroup libvirt perl debootstrap   //安装lxc的依赖包

//依赖包详解
lxc           //主程序包
lxc-templates //lxc的配置模板
bridge-utils  //网桥管理工具
lxc-libs      //lxc所需的库文件
libcgroup     //cgroup是为Linux内核提供任务聚集和划分的机制,通过一组参数集合将一些任务组织成一个或多个子系统。
libvirt       //管理Linux的虚拟化功能所需的服务器端守护程序。 需要针对特定驱动程序的管理程序。


//启动服务
[root@localhost ~]# systemctl start lxc     //启动
[root@localhost ~]# systemctl start libvirtd
[root@localhost ~]# systemctl status lxc.service       //查看一下
● lxc.service - LXC Container Initialization and Autoboot Code
   Loaded: loaded (/usr/lib/systemd/system/lxc.service; disabled; vendor preset: disabled)
   Active: active (exited) since 日 2022-04-24 15:47:26 CST; 30s ago
  Process: 77992 ExecStart=/usr/libexec/lxc/lxc-autostart-helper start (code=exited, status=0/SUCCESS)
  Process: 77985 ExecStartPre=/usr/libexec/lxc/lxc-devsetup (code=exited, status=0/SUCCESS)
 Main PID: 77992 (code=exited, status=0/SUCCESS)
    Tasks: 0
   Memory: 0B
   CGroup: /system.slice/lxc.service


//命令使用
[root@localhost ~]# lxc-checkconfig       //查看能否满足使用容器需求
Kernel configuration not found at /proc/config.gz; searching...
Kernel configuration found at /boot/config-3.10.0-1062.el7.x86_64
--- Namespaces ---
Namespaces: enabled
Utsname namespace: enabled
Ipc namespace: enabled
Pid namespace: enabled
User namespace: enabled
Warning: newuidmap is not setuid-root
Warning: newgidmap is not setuid-root
Network namespace: enabled
Multiple /dev/pts instances: enabled

--- Control groups ---
Cgroup: enabled
Cgroup clone_children flag: enabled
Cgroup device: enabled
Cgroup sched: enabled
Cgroup cpu account: enabled
Cgroup memory controller: enabled
Cgroup cpuset: enabled

--- Misc ---
Veth pair device: enabled
Macvlan: enabled
Vlan: enabled
Bridges: enabled
Advanced netfilter: enabled
CONFIG_NF_NAT_IPV4: enabled
CONFIG_NF_NAT_IPV6: enabled
CONFIG_IP_NF_TARGET_MASQUERADE: enabled
CONFIG_IP6_NF_TARGET_MASQUERADE: enabled
CONFIG_NETFILTER_XT_TARGET_CHECKSUM: enabled

--- Checkpoint/Restore ---
checkpoint restore: enabled
CONFIG_FHANDLE: enabled
CONFIG_EVENTFD: enabled
CONFIG_EPOLL: enabled
CONFIG_UNIX_DIAG: enabled
CONFIG_INET_DIAG: enabled
CONFIG_PACKET_DIAG: enabled
CONFIG_NETLINK_DIAG: enabled
File capabilities: enabled

Note : Before booting a new kernel, you can check its configuration
usage : CONFIG=/path/to/config /usr/bin/lxc-checkconfig

//存放模板的目录
[root@localhost ~]# ls /usr/share/lxc/templates/  //用于查看系统可用的lxc模板
lxc-alpine     lxc-centos    lxc-fedora        lxc-oracle  lxc-ubuntu-cloud
lxc-altlinux   lxc-cirros    lxc-gentoo        lxc-plamo
lxc-archlinux  lxc-debian    lxc-openmandriva  lxc-sshd
lxc-busybox    lxc-download  lxc-opensuse      lxc-ubuntu

//修改密码
[root@localhost ~]# lxc-create -t centos -n test
Copy /var/cache/lxc/centos/x86_64/7/rootfs to /var/lib/lxc/test/rootfs ... 
Copying rootfs to /var/lib/lxc/test/rootfs ...
sed:无法读取 /var/lib/lxc/test/rootfs/etc/init/tty.conf:没有那个文件或目录
Storing root password in '/var/lib/lxc/test/tmp_root_pass'
chpasswd:无法打开 /etc/passwd
正在终止用户 root 的密码。
passwd: Libuser error at line: 425 - Error replacing `/etc/passwd': 权限不够.
passwd: 错误
sed:无法读取 /var/lib/lxc/test/rootfs/etc/rc.sysinit:没有那个文件或目录
sed:无法读取 /var/lib/lxc/test/rootfs/etc/rc.d/rc.sysinit:没有那个文件或目录

Container rootfs and config have been created.
Edit the config file to check/enable networking setup.

The temporary root password is stored in:

        '/var/lib/lxc/test/tmp_root_pass'   //存放初始密码的文件


The root password is set up as expired and will require it to be changed
at first login, which you should do as soon as possible.  If you lose the
root password or wish to change it without starting the container, you
can change it from the host by running the following command (which will
also reset the expired flag):

        chroot /var/lib/lxc/test/rootfs passwd  //修改密码的命令

[root@localhost ~]# setenforce 0  //修改密码需要将selinux关闭

[root@localhost ~]# chroot /var/lib/lxc/test/rootfs passwd
更改用户 root 的密码 。
新的 密码:
重新输入新的 密码:
passwd:所有的身份验证令牌已经成功更新。

//启动容器
[root@localhost ~]# lxc-start -n test  //启动容器
lxc-start: conf.c: remount_all_slave: 4204 No such file or directory - Failed to make /run/media/kurumi/CentOS\0407\040x86_64 rslave
                                                   lxc-start: conf.c: remount_all_slave: 4205 Continuing...
                          systemd 219 running in system mode. (+PAM +AUDIT +SELINUX +IMA -APPARMOR +SMACK +SYSVINIT +UTMP +LIBCRYPTSETUP +GCRYPT +GNUTLS +ACL +XZ +LZ4 -SECCOMP +BLKID +ELFUTILS +KMOD +IDN)
Detected virtualization lxc.
Detected architecture x86-64.

Welcome to CentOS Linux 7 (Core)!

Running in a container, ignoring fstab device entry for /dev/root.
Cannot add dependency job for unit display-manager.service, ignoring: Unit not found.
[  OK  ] Started Dispatch Password Requests to Console Directory Watch.
[  OK  ] Created slice Root Slice.
[  OK  ] Created slice System Slice.
[  OK  ] Listening on Delayed Shutdown Socket.
[  OK  ] Listening on /dev/initctl Compatibility Named Pipe.
[  OK  ] Started Forward Password Requests to Wall Directory Watch.
[  OK  ] Reached target Paths.
[  OK  ] Created slice User and Session Slice.
[  OK  ] Reached target Swap.
[  OK  ] Created slice system-getty.slice.
[  OK  ] Listening on Journal Socket.
         Mounting Huge Pages File System...
         Starting Journal Service...
         Mounting POSIX Message Queue File System...
[  OK  ] Reached target Local Encrypted Volumes.
[  OK  ] Reached target Slices.
         Starting Remount Root and Kernel File Systems...
         Mounting FUSE Control File System...
[  OK  ] Reached target Remote File Systems.
         Starting Read and set NIS domainname from /etc/sysconfig/network...
[  OK  ] Mounted FUSE Control File System.
[  OK  ] Mounted POSIX Message Queue File System.
[  OK  ] Mounted Huge Pages File System.
[  OK  ] Started Journal Service.
[  OK  ] Started Read and set NIS domainname from /etc/sysconfig/network.
[  OK  ] Started Remount Root and Kernel File Systems.
         Starting Flush Journal to Persistent Storage...
[  OK  ] Reached target Local File Systems (Pre).
         Starting Configure read-only root support...
         Starting Rebuild Hardware Database...
<46>systemd-journald[15]: Received request to flush runtime journal from PID 1
[  OK  ] Started Flush Journal to Persistent Storage.
[  OK  ] Started Configure read-only root support.
         Starting Load/Save Random Seed...
[  OK  ] Reached target Local File Systems.
         Starting Mark the need to relabel after reboot...
         Starting Rebuild Journal Catalog...
         Starting Create Volatile Files and Directories...
[  OK  ] Started Load/Save Random Seed.
[  OK  ] Started Mark the need to relabel after reboot.
[  OK  ] Started Rebuild Journal Catalog.
[  OK  ] Started Create Volatile Files and Directories.
         Starting Update UTMP about System Boot/Shutdown...
[  OK  ] Started Update UTMP about System Boot/Shutdown.
[  OK  ] Started Rebuild Hardware Database.
         Starting Update is Completed...
[  OK  ] Started Update is Completed.
[  OK  ] Reached target System Initialization.
[  OK  ] Listening on D-Bus System Message Bus Socket.
[  OK  ] Reached target Sockets.
[  OK  ] Started Daily Cleanup of Temporary Directories.
[  OK  ] Reached target Timers.
[  OK  ] Reached target Basic System.
         Starting Login Service...
         Starting LSB: Bring up/down networking...
         Starting Permit User Sessions...
         Starting OpenSSH Server Key Generation...
[  OK  ] Started D-Bus System Message Bus.
[  OK  ] Started Permit User Sessions.
         Starting Cleanup of Temporary Directories...
[  OK  ] Started Command Scheduler.
[  OK  ] Started Console Getty.
[  OK  ] Reached target Login Prompts.
[  OK  ] Started Login Service.
[  OK  ] Started Cleanup of Temporary Directories.
[  OK  ] Started OpenSSH Server Key Generation.

CentOS Linux 7 (Core)
Kernel 3.10.0-1062.el7.x86_64 on an x86_64

test login: root   //root账户
Password:          //之前chroot创建的密码
<28>systemd-sysctl[297]: Failed to write '1' to '/proc/sys/fs/protected_symlinks': Read-only file system
[root@test ~]# ip a   
1: lo:  mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
5: eth0@if6:  mtu 1500 qdisc noqueue state UP group default qlen 1000
    link/ether fe:a0:72:d8:3a:d0 brd ff:ff:ff:ff:ff:ff link-netnsid 0
    inet 192.168.122.132/24 brd 192.168.122.255 scope global dynamic eth0
       valid_lft 3302sec preferred_lft 3302sec
    inet6 fe80::fca0:72ff:fed8:3ad0/64 scope link 
       valid_lft forever preferred_lft forever


//命令使用
[root@localhost ~]# lxc-info -n test  //查看容器相关信息
Name:           test
State:          RUNNING
PID:            92109
IP:             192.168.122.132
CPU use:        0.13 seconds
BlkIO use:      912.00 KiB
Memory use:     1.56 MiB
KMem use:       0 bytes
Link:           vethJ9X2KO
 TX bytes:      1.77 KiB
 RX bytes:      12.64 KiB
 Total bytes:   14.41 KiB
[root@localhost ~]# lxc-stop  //停止容器中所有的进程

lxc-console
//附加至指定容器的控制台;
格式:lxc-console -n NAME -t NUMBER

lxc-stop
//停止容器;

lxc-destory
//删除处于停机状态的容器;

lxc-snapshot
//创建和恢复快照;

//退出容器方式:








 

2、容器的工作方式

为了使容器的使用更加易于管理,docker采取一个用户空间只跑一个业务进程的方式,在一个容器内只运行一个进程,比如我们要在一台主机上安装一个nginx和一个tomcat,那么nginx就运行在nginx的容器中,tomcat运行在tomcat的容器中,二者用容器间的通信逻辑来进行通信。

LXC是把一个容器当一个用户空间使用,当虚拟机一样使用,里面可以运行N个进程,这就使得我们在容器内去管理时极为不便,而docker用这种限制性的方式,在一个容器中只运行一个进程的方式,使得容器的管理更加方便。

docker容器技术基础入门_第1张图片

使用docker的优劣:

  • 删除一个容器不会影响其他容器
  • 调试不便,占空间(每个容器中都必须自带调试工具,比如ps命令)
  • 分发容易,真正意义上一次编写到处运行,比java的跨平台更彻底
  • 部署容易,无论底层系统是什么,只要有docker,直接run就可以了
  • 分层构建,联合挂载

docker容器技术基础入门_第2张图片

在容器中有数据称作有状态,没有数据称作无状态。在容器的使用中,我们应以有状态为耻,以无状态为荣。数据不应该放在容器中,而应放置于外部存储中,通过挂载到容器中从而进行数据的存储。

3、CGroup的功能

控制组(CGroups)是Linux内核的一个特性,用来对共享资源进行隔离、限制、审计等。只有能控制分配到容器的资源,Docker才能避免多个容器同时运行时的系统资源竞争。

控制组可以提供对容器的内存、CPU、磁盘IO等资源进行限制。

CGroups能够限制的资源有:

  • blkio:块设备IO
  • cpu:CPU
  • cpuacct:CPU资源使用报告
  • cpuset:多处理器平台上的CPU集合
  • devices:设备访问
  • freezer:挂起或恢复任务
  • memory:内存用量及报告
  • perf_event:对cgroup中的任务进行统一性能测试
  • net_cls:cgroup中的任务创建的数据报文的类别标识符

具体来看,控制组提供如下功能:

  • 资源限制(Resource Limitting)组可以设置为不超过设定的内存限制。比如:内存子系统可以为进行组设定一个内存使用上限,一旦进程组使用的内存达到限额再申请内存,就会发出Out of Memory警告
  • 优先级(Prioritization)通过优先级让一些组优先得到更多的CPU等资源
  • 资源审计(Accounting)用来统计系统实际上把多少资源用到合适的目的上,可以使用cpuacct子系统记录某个进程组使用的CPU时间
  • 隔离(Isolation)为组隔离命名空间,这样一个组不会看到另一个组的进程、网络连接和文件系统
  • 控制(Control)挂起、恢复和重启等操作

安装Docker后,用户可以在/sys/fs/cgroup/memory/docker/目录下看到对Docker组应用的各种限制项,包括

[root@localhost ~]# cd /sys/fs/cgroup/memory/
[root@localhost memory]# ls
cgroup.clone_children           memory.kmem.slabinfo                memory.memsw.limit_in_bytes      memory.swappiness
cgroup.event_control            memory.kmem.tcp.failcnt             memory.memsw.max_usage_in_bytes  memory.usage_in_bytes
cgroup.procs                    memory.kmem.tcp.limit_in_bytes      memory.memsw.usage_in_bytes      memory.use_hierarchy
cgroup.sane_behavior            memory.kmem.tcp.max_usage_in_bytes  memory.move_charge_at_immigrate  notify_on_release
memory.failcnt                  memory.kmem.tcp.usage_in_bytes      memory.numa_stat                 release_agent
memory.force_empty              memory.kmem.usage_in_bytes          memory.oom_control               system.slice
memory.kmem.failcnt             memory.limit_in_bytes               memory.pressure_level            tasks
memory.kmem.limit_in_bytes      memory.max_usage_in_bytes           memory.soft_limit_in_bytes       user.slice
memory.kmem.max_usage_in_bytes  memory.memsw.failcnt                memory.stat

用户可以通过修改这些文件值来控制组限制Docker应用资源。

4、docker基本概念

docker是容器技术的一个前端工具,容器是内核的一项技术,docker只是把这一项技术的使用得以简化,使之普及而已。

LXC进行大规模创建容器很难,想在另一台主机上复刻一个一模一样的容器也很难,而docker就是从这方面着手去找解决方案。所以docker早期的版本其核心就是一个LXC,docker对其进行了二次封装,功能的实现是通过LXC做容器管理引擎,但是在创建容器时,不再是像LXC一样用模板去现场安装,而是事先通过一种类似镜像技术,就像在KVM中一样,将一个操作系统打包成一个镜像,然后将这个镜像拷贝到目标主机上直接部署启动。

我们可以尝试着把一个操作系统用户空间需要用到的所有组件,事先准备、编排好,编排好以后整体打包成一个文件,这个文件我们称其为镜像文件(image)。

docker的镜像文件是放在一个集中统一的互联网仓库中的,把一些人们常用的镜像文件放在互联网仓库中,比如最小化的centos系统,有时我们需要在操作系统上安装一些应用,比如nginx,我们就可以在一个最小化的centos系统中安装一个nginx,然后将其打包成镜像,将其放在互联网仓库中,当人们想启动一个容器的时候,docker会到这个互联网仓库中去下载我们需要的镜像到本地,并基于镜像来启动容器。

自docker 0.9版本起,docker除了继续支持LXC外,还开始引入自家的libcontainer,试图打造更通用的底层容器虚拟化库。如今的docker基本上都已经是使用libcontainer而非LXC了。

从操作系统功能上看,docker底层依赖的核心技术主要包括Linux操作系统的命名空间、控制组、联合文件系统和Linux虚拟网络支持。

5、docker的部署安装

安装一下yum源

docker容器技术基础入门_第3张图片

[root@localhost ~]# cd /etc/yum.repos.d/
[root@localhost yum.repos.d]# ls
redhat.repo
[root@localhost yum.repos.d]# rm -rf *     //删掉原有的源
[root@localhost yum.repos.d]# ls
[root@localhost yum.repos.d]# cat /etc/redhat-release     //查看版本
Red Hat Enterprise Linux release 8.5 (Ootpa)
[root@localhost yum.repos.d]# curl -o /etc/yum.repos.d/CentOS-Base.repo  
https://mirrors.aliyun.com/repo/Centos-vault-8.5.2111.repo     //下载阿里云的源
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  2495  100  2495    0     0  16414      0 --:--:-- --:--:-- --:--:-- 16414
[root@localhost yum.repos.d]# ls
CentOS-Base.repo
[root@localhost yum.repos.d]# sed -i -e '/mirrors.cloud.aliyuncs.com/d' -e '/mirrors.aliyuncs.com/d' /etc/yum.repos.d/CentOS-Base.repo
[root@localhost yum.repos.d]# cd
[root@localhost ~]# yum clean all   //清理缓存
正在更新 Subscription Management 软件仓库。
无法读取客户身份

本系统尚未在权利服务器中注册。可使用 subscription-manager 进行注册。

0 文件已删除
[root@localhost ~]# yum install -y https://mirrors.aliyun.com/epel/epel-release-latest-8.noarch.rpm
正在更新 Subscription Management 软件仓库。
无法读取客户身份

 ....                    

完毕!
[root@localhost ~]# sed -i 's|^#baseurl=https://download.example/pub|baseurl=https://mirrors.aliyun.com|' /etc/yum.repos.d/epel*
[root@localhost ~]# sed -i 's|^metalink|#metalink|' /etc/yum.repos.d/epel*
[root@localhost ~]# yum clean all
正在更新 Subscription Management 软件仓库。
无法读取客户身份

本系统尚未在权利服务器中注册。可使用 subscription-manager 进行注册。

43 文件已删除
[root@localhost ~]# yum makecache    //重建缓存
正在更新 Subscription Management 软件仓库。
无法读取客户身份

本系统尚未在权利服务器中注册。可使用 subscription-manager 进行注册。

CentOS-8.5.2111 - Base - mirrors.aliyun.com     1.2 MB/s | 4.6 MB     00:03    
CentOS-8.5.2111 - Extras - mirrors.aliyun.com    95 kB/s |  10 kB     00:00    
CentOS-8.5.2111 - AppStream - mirrors.aliyun.co 843 kB/s | 8.4 MB     00:10    
Docker CE Stable - x86_64                       100 kB/s |  23 kB     00:00    
Extra Packages for Enterprise Linux 8 - x86_64  901 kB/s |  11 MB     00:12    
Extra Packages for Enterprise Linux Modular 8 - 613 kB/s | 1.0 MB     00:01    
元数据缓存已建立。

 下载安装docker

docker容器技术基础入门_第4张图片

 

docker容器技术基础入门_第5张图片

docker容器技术基础入门_第6张图片 

 docker容器技术基础入门_第7张图片

 

docker容器技术基础入门_第8张图片

 

//下载安装docker
[root@localhost ~]# yum -y install wget vim
[root@localhost ~]# cd /etc/yum.repos.d/
[root@localhost yum.repos.d]# ls
CentOS-Base.repo   epel.repo                  epel-testing.repo
epel-modular.repo  epel-testing-modular.repo  redhat.repo
[root@localhost yum.repos.d]# wget https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
--2022-04-24 17:11:11--  https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
正在解析主机 mirrors.aliyun.com (mirrors.aliyun.com)... 119.36.224.209, 119.36.224.211, 119.36.224.212, ...
正在连接 mirrors.aliyun.com (mirrors.aliyun.com)|119.36.224.209|:443... 已连接。
已发出 HTTP 请求,正在等待回应... 200 OK
长度:2081 (2.0K) [application/octet-stream]
正在保存至: “docker-ce.repo”

docker-ce.repo      100%[===================>]   2.03K  --.-KB/s  用时 0.002s  

2022-04-24 17:11:11 (951 KB/s) - 已保存 “docker-ce.repo” [2081/2081])

[root@localhost yum.repos.d]# ls
CentOS-Base.repo  epel-modular.repo  epel-testing-modular.repo  redhat.repo
docker-ce.repo    epel.repo          epel-testing.repo
[root@localhost yum.repos.d]# cd
[root@localhost ~]# yum list all | grep docker
containerd.io.x86_64                                              1.5.11-3.1.el8                                         docker-ce-stable
docker-ce.x86_64                                                  3:20.10.14-3.el8                                       docker-ce-stable
docker-ce-cli.x86_64                                              1:20.10.14-3.el8                                       docker-ce-stable
docker-ce-rootless-extras.x86_64                                  20.10.14-3.el8                                         docker-ce-stable
docker-compose-plugin.x86_64                                      2.3.3-3.el8                                            docker-ce-stable
docker-scan-plugin.x86_64                                         0.17.0-3.el8                                           docker-ce-stable
pcp-pmda-docker.x86_64                                            5.3.1-5.el8                                            AppStream       
podman-docker.noarch                                              3.3.1-9.module_el8.5.0+988+b1f0b741                    AppStream       
python-docker-tests.noarch                                        5.0.0-2.el8                                            epel            
python2-dockerpty.noarch                                          0.4.1-18.el8                                           epel            
python3-docker.noarch                                             5.0.0-2.el8                                            epel            
python3-dockerpty.noarch                                          0.4.1-18.el8                                           epel            
standard-test-roles-inventory-docker.noarch                       4.10-1.el8                                             epel            
[root@localhost ~]# yum -y install docker-ce




//报错
[root@localhost ~]# yum -y install docker-ce
- 软件包 containerd.io-1.4.8-3.1.el8.x86_64 取代了 runc(由 runc-1.0.2-1.module_el8.5.0+911+f19012f9.x86_64 提供)
- 无法为该任务安装最佳候选
  - 软件包 runc-1.0.0-56.rc5.dev.git2abd837.module_el8.3.0+569+1bada2e4.x86_64 被模块过滤过滤掉
  - 软件包 runc-1.0.0-66.rc10.module_el8.5.0+1004+c00a74f5.x86_64 被模块过滤过滤掉
  - 软件包 runc-1.0.0-72.rc92.module_el8.5.0+1006+8d0e68a2.x86_64 被模块过滤过滤掉
(尝试在命令行中添加 '--allowerasing' 来替换冲突的软件包 或 '--skip-broken' 来跳过无法安装的软件包 或 '--nobest' 来不只使用软件包的最佳候选)
//解决
[root@localhost ~]# yum -y install docker-ce --allowerasing    //替代冲突的依赖包

 安装加速器

使用阿里云个人私有加速器

docker容器技术基础入门_第9张图片

 docker容器技术基础入门_第10张图片

 docker容器技术基础入门_第11张图片

 docker容器技术基础入门_第12张图片

 

//安装加速器
[root@localhost ~]# ls /etc/docker
ls: 无法访问'/etc/docker': 没有那个文件或目录
[root@localhost ~]# systemctl enable --now docker   //必须设置开机自启
Created symlink /etc/systemd/system/multi-user.target.wants/docker.service → /usr/lib/systemd/system/docker.service.
[root@localhost ~]# systemctl status docker
● docker.service - Docker Application Container Engine
   Loaded: loaded (/usr/lib/systemd/system/docker.service; enabled; vendor pres>
   Active: active (running) since Sun 2022-04-24 17:18:41 CST; 13s ago
     Docs: https://docs.docker.com
 Main PID: 34052 (dockerd)
    Tasks: 7
   Memory: 28.8M
   CGroup: /system.slice/docker.service
           └─34052 /usr/bin/dockerd -H fd:// --containerd=/run/containerd/conta>

4月 24 17:18:40 localhost.localdomain dockerd[34052]: time="2022-04-24T17:18:40>
4月 24 17:18:40 localhost.localdomain dockerd[34052]: time="2022-04-24T17:18:40>
4月 24 17:18:40 localhost.localdomain dockerd[34052]: time="2022-04-24T17:18:40>
4月 24 17:18:41 localhost.localdomain dockerd[34052]: time="2022-04-24T17:18:41>
4月 24 17:18:41 localhost.localdomain dockerd[34052]: time="2022-04-24T17:18:41>
4月 24 17:18:41 localhost.localdomain dockerd[34052]: time="2022-04-24T17:18:41>
4月 24 17:18:41 localhost.localdomain dockerd[34052]: time="2022-04-24T17:18:41>
4月 24 17:18:41 localhost.localdomain dockerd[34052]: time="2022-04-24T17:18:41>
4月 24 17:18:41 localhost.localdomain systemd[1]: Started Docker Application Co>
4月 24 17:18:41 localhost.localdomain dockerd[34052]: time="2022-04-24T17:18:41>
[root@localhost ~]# ls /etc/docker/
key.json


[root@localhost ~]# cd /etc/docker/
[root@localhost docker]# ls
key.json
[root@localhost docker]# vi daemon.json
{
  "registry-mirrors": ["https://6mi7k79l.mirror.aliyuncs.com"]
}
[root@localhost docker]# systemctl daemon-reload    //重新加载
[root@localhost docker]# systemctl restart docker    //重启docker
[root@localhost docker]# docker info     //查看docker运行的环境
Client:
 Context:    default
 Debug Mode: false
 Plugins:
  app: Docker App (Docker Inc., v0.9.1-beta3)
  buildx: Docker Buildx (Docker Inc., v0.8.1-docker)
  scan: Docker Scan (Docker Inc., v0.17.0)

Server:
 Containers: 0
  Running: 0
  Paused: 0
  Stopped: 0
 Images: 0
 Server Version: 20.10.14
 Storage Driver: overlay2
  Backing Filesystem: xfs
  Supports d_type: true
  Native Overlay Diff: true
  userxattr: false
 Logging Driver: json-file
 Cgroup Driver: cgroupfs
 Cgroup Version: 1
 Plugins:
  Volume: local
  Network: bridge host ipvlan macvlan null overlay
  Log: awslogs fluentd gcplogs gelf journald json-file local logentries splunk syslog
 Swarm: inactive
 Runtimes: io.containerd.runc.v2 io.containerd.runtime.v1.linux runc
 Default Runtime: runc
 Init Binary: docker-init
 containerd version: 3df54a852345ae127d1fa3092b95168e4a88e2f8
 runc version: v1.0.3-0-gf46b6ba
 init version: de40ad0
 Security Options:
  seccomp
   Profile: default
 Kernel Version: 4.18.0-348.el8.x86_64
 Operating System: Red Hat Enterprise Linux 8.5 (Ootpa)
 OSType: linux
 Architecture: x86_64
 CPUs: 1
 Total Memory: 1.748GiB
 Name: localhost.localdomain
 ID: O3H7:V4M2:AWSS:2ZQL:KSOJ:27CK:HKM3:CZSY:VNQR:4W2S:TXOF:5EJO
 Docker Root Dir: /var/lib/docker
 Debug Mode: false
 Registry: https://index.docker.io/v1/
 Labels:
 Experimental: false
 Insecure Registries:
  127.0.0.0/8
 Registry Mirrors:
  https://6mi7k79l.mirror.aliyuncs.com/         //看到这个说明加速器配置成功了
 Live Restore Enabled: false

[root@localhost ~]# docker version     //查看版本号
Client: Docker Engine - Community
 Version:           20.10.14
 API version:       1.41
 Go version:        go1.16.15
 Git commit:        a224086
 Built:             Thu Mar 24 01:47:44 2022
 OS/Arch:           linux/amd64
 Context:           default
 Experimental:      true

Server: Docker Engine - Community
 Engine:
  Version:          20.10.14
  API version:      1.41 (minimum version 1.12)
  Go version:       go1.16.15
  Git commit:       87a90dc
  Built:            Thu Mar 24 01:46:10 2022
  OS/Arch:          linux/amd64
  Experimental:     false
 containerd:
  Version:          1.5.11
  GitCommit:        3df54a852345ae127d1fa3092b95168e4a88e2f8
 runc:
  Version:          1.0.3
  GitCommit:        v1.0.3-0-gf46b6ba
 docker-init:
  Version:          0.19.0
  GitCommit:        de40ad0


[root@localhost ~]# ls /var/lib/docker/     //存放的位置
buildkit    image    overlay2  runtimes  tmp    volumes
containers  network  plugins   swarm     trust

6、docker的常用命令操作

Docker Hub镜像仓库

命令 功能
docker search Search the Docker Hub for images(在 Docker 中心搜索镜像)
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(返回有关 Docker 对象的低级信息)
[root@localhost ~]# docker search seancheng1002/httpd    //搜索官方的
NAME                  DESCRIPTION   STARS     OFFICIAL   AUTOMATED
seancheng1002/httpd                 0                    
[root@localhost ~]# docker search httpd        //搜索所有的包括官方的(数字越大越受欢迎)
NAME                                 DESCRIPTION                                     STARS     OFFICIAL(官方)   AUTOMATED
httpd                                The Apache HTTP Server Project                3976      [OK]       
centos/httpd-24-centos7              Platform for running Apache httpd 2.4 or bui…   44                   
centos/httpd                                                                         35                   [OK]
hypoport/httpd-cgi                   httpd-cgi                                       2                    [OK]
solsson/httpd-openidc                mod_auth_openidc on official httpd image, ve…   2                    [OK]
manageiq/httpd                       Container with httpd, built on CentOS for Ma…   1                    [OK]
lead4good/httpd-fpm                  httpd server which connects via fcgi proxy h…   1                    [OK]
dockerpinata/httpd                                                                   1                    
publici/httpd                        httpd:latest                                    1                    [OK]
dariko/httpd-rproxy-ldap             Apache httpd reverse proxy with LDAP authent…   1                    [OK]
inanimate/httpd-ssl                  A play container with httpd, ssl enabled, an…   1                    [OK]
centos/httpd-24-centos8                                                              1                    
clearlinux/httpd                     httpd HyperText Transfer Protocol (HTTP) ser…   1                    
manageiq/httpd_configmap_generator   Httpd Configmap Generator                       0                    [OK]
manasip/httpd                                                                        0                    
e2eteam/httpd                                                                        0                    
paketobuildpacks/httpd                                                               0                    
httpdocker/kubia                                                                     0                    
sandeep1988/httpd-new                httpd-new                                       0                    
httpdocker/kubia-unhealthy                                                           0                    
amd64/httpd                          The Apache HTTP Server Project                  0                    
patrickha/httpd-err                                                                  0                    
httpdss/archerysec                   ArcherySec repository                           0                    [OK]
19022021/httpd-connection_test       This httpd image will test the connectivity …   0                    
itsziget/httpd24                     Extended HTTPD Docker image based on the off…   0                    [OK]


[root@localhost ~]# docker images    //列出所有镜像,显示里面没有镜像
REPOSITORY   TAG       IMAGE ID   CREATED   SIZE
[root@localhost ~]# docker pull httpd    //拉取httpd镜像,没有写序列号就拉取最新版本
Using default tag: latest
latest: Pulling from library/httpd
a2abf6c4d29d: Pull complete 
dcc4698797c8: Pull complete 
41c22baa66ec: Pull complete 
67283bbdd4a0: Pull complete 
d982c879c57e: Pull complete 
Digest: sha256:0954cc1af252d824860b2c5dc0a10720af2b7a3d3435581ca788dff8480c7b32
Status: Downloaded newer image for httpd:latest
docker.io/library/httpd:latest
[root@localhost ~]# docker images
REPOSITORY   TAG       IMAGE ID       CREATED        SIZE
httpd        latest    dabbfbe0c57b   4 months ago   144MB
[root@localhost ~]# docker images
REPOSITORY   TAG       IMAGE ID       CREATED        SIZE
httpd        latest    dabbfbe0c57b   4 months ago   144MB
[root@localhost ~]# docker pull httpd:2.4.53
2.4.53: Pulling from library/httpd
1fe172e4850f: Pull complete 
e2fa1fe9b1ec: Pull complete 
60dd7398e74e: Pull complete 
ea2ca81c6d4c: Pull complete 
f646c69a26ec: Pull complete 
Digest: sha256:e02a2ef36151905c790efb0a8472f690010150f062639bd8c0760e7b1e884c07
Status: Downloaded newer image for httpd:2.4.53
docker.io/library/httpd:2.4.53
[root@localhost ~]# docker images
REPOSITORY   TAG       IMAGE ID       CREATED        SIZE
httpd        2.4.53    c30a46771695   4 days ago     144MB
httpd        latest    dabbfbe0c57b   4 months ago   144MB


[root@localhost ~]# docker create --help
[root@localhost ~]# docker create --name web -p 80:80 httpd     //创建一个容器name=名字, -p——端口号,httpd后面没加序列号自动用最新版本latest
8018e485d9834a18cfc68ec067d405fac5604b8c4f395a688f53b07cffb522ca
[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
8018e485d983   httpd     "httpd-foreground"   About a minute ago   Created             web

[root@localhost ~]# docker start web   //启动,可以用名字也可以用ID
web
[root@localhost ~]# docker ps
CONTAINER ID   IMAGE     COMMAND              CREATED         STATUS         PORTS                               NAMES
8018e485d983   httpd     "httpd-foreground"   4 minutes ago   Up 3 seconds   0.0.0.0:80->80/tcp, :::80->80/tcp   web   //有个端口号的映射,可以在真机上访问了
[root@localhost ~]# systemctl disable --now firewalld   //防火墙关掉
Removed /etc/systemd/system/multi-user.target.wants/firewalld.service.
Removed /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service.
[root@localhost ~]# vi /etc/selinux/config 
[root@localhost ~]# setenforce 0  
//然后就可以访问了,用ip访问,显示it works!访问成功
[root@localhost ~]# docker stop 8018e485d983   //停用,名字和ID都可以
8018e485d983
[root@localhost ~]# docker ps -a
CONTAINER ID   IMAGE     COMMAND              CREATED         STATUS                      PORTS     NAMES
8018e485d983   httpd     "httpd-foreground"   9 minutes ago   Exited (0) 10 seconds ago             web

[root@localhost ~]# systemctl start firewalld   //防火墙得开启才能启动容器
[root@localhost ~]# docker start web
web
[root@localhost ~]# docker ps
CONTAINER ID   IMAGE     COMMAND              CREATED          STATUS         PORTS                               NAMES
8018e485d983   httpd     "httpd-foreground"   12 minutes ago   Up 9 seconds   0.0.0.0:80->80/tcp, :::80->80/tcp   web
[root@localhost ~]# firewall-cmd --list-all
public (active)
  target: default
  icmp-block-inversion: no
  interfaces: ens160
  sources: 
  services: cockpit dhcpv6-client ssh
  ports: 
  protocols: 
  forward: no
  masquerade: no
  forward-ports: 
  source-ports: 
  icmp-blocks: 
  rich rules: 
[root@localhost ~]# firewall-cmd --add-rich-rule 'rule family=ipv4 source address=0.0.0.0/0 service name=http accept' --permanent    //在防火墙里给服务httpd做放行
success 
[root@localhost ~]# firewall-cmd --reload
success
[root@localhost ~]# firewall-cmd --list-all
public (active)
  target: default
  icmp-block-inversion: no
  interfaces: ens160
  sources: 
  services: cockpit dhcpv6-client ssh
  ports: 
  protocols: 
  forward: no
  masquerade: no
  forward-ports: 
  source-ports: 
  icmp-blocks: 
  rich rules: 
	rule family="ipv4" source address="0.0.0.0/0" service name="http" accept
//然后在防火墙开启时也可以在真机上访问,没有放行规则就访问不了


[root@localhost ~]# docker restart web   //重启
web
[root@localhost ~]# docker ps
CONTAINER ID   IMAGE     COMMAND              CREATED          STATUS         PORTS                               NAMES
8018e485d983   httpd     "httpd-foreground"   19 minutes ago   Up 3 seconds   0.0.0.0:80->80/tcp, :::80->80/tcp   web

[root@localhost ~]# docker kill web    //强制杀掉
web
[root@localhost ~]# docker ps -a
CONTAINER ID   IMAGE     COMMAND              CREATED          STATUS                       PORTS     NAMES
8018e485d983   httpd     "httpd-foreground"   19 minutes ago   Exited (137) 9 seconds ago             web


[root@localhost ~]# docker logs web   //访问日志
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
[Sun Apr 24 10:22:29.325806 2022] [mpm_event:notice] [pid 1:tid 140016680467776] AH00489: Apache/2.4.52 (Unix) configured -- resuming normal operations
[Sun Apr 24 10:22:29.342965 2022] [core:notice] [pid 1:tid 140016680467776] AH00094: Command line: 'httpd -D FOREGROUND'
172.17.0.1 - - [24/Apr/2022:10:26:34 +0000] "GET / HTTP/1.1" 200 45
172.17.0.1 - - [24/Apr/2022:10:26:35 +0000] "GET /favicon.ico HTTP/1.1" 404 196
172.17.0.1 - - [24/Apr/2022:10:26:38 +0000] "GET / HTTP/1.1" 304 -
172.17.0.1 - - [24/Apr/2022:10:27:27 +0000] "-" 408 -
[Sun Apr 24 10:28:08.186975 2022] [mpm_event:notice] [pid 1:tid 140016680467776] AH00492: caught SIGWINCH, shutting down gracefully
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
[Sun Apr 24 10:30:30.632447 2022] [mpm_event:notice] [pid 1:tid 140110102748480] AH00489: Apache/2.4.52 (Unix) configured -- resuming normal operations
[Sun Apr 24 10:30:30.632544 2022] [core:notice] [pid 1:tid 140110102748480] AH00094: Command line: 'httpd -D FOREGROUND'
[Sun Apr 24 10:37:25.183831 2022] [mpm_event:notice] [pid 1:tid 140110102748480] AH00492: caught SIGWINCH, shutting down gracefully
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
[Sun Apr 24 10:37:26.830777 2022] [mpm_event:notice] [pid 1:tid 140239884594496] AH00489: Apache/2.4.52 (Unix) configured -- resuming normal operations
[Sun Apr 24 10:37:26.830851 2022] [core:notice] [pid 1:tid 140239884594496] AH00094: Command line: 'httpd -D FOREGROUND'
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
[Sun Apr 24 10:39:24.842407 2022] [mpm_event:notice] [pid 1:tid 139952675552576] AH00489: Apache/2.4.52 (Unix) configured -- resuming normal operations
[Sun Apr 24 10:39:24.842508 2022] [core:notice] [pid 1:tid 139952675552576] AH00094: Command line: 'httpd -D FOREGROUND'
192.168.160.1 - - [24/Apr/2022:10:40:04 +0000] "GET / HTTP/1.1" 304 -
192.168.160.1 - - [24/Apr/2022:10:40:05 +0000] "GET / HTTP/1.1" 304 -   //访问记录


[root@localhost ~]# docker rm -f web   //强制删除正在运行的容器,docker rm name是不能删除正在运行的容器的
web
[root@localhost ~]# docker ps -a
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
[root@localhost ~]# docker images     //容器删除但是镜像是没删的
REPOSITORY   TAG       IMAGE ID       CREATED        SIZE
httpd        2.4.53    c30a46771695   4 days ago     144MB
httpd        latest    dabbfbe0c57b   4 months ago   144MB



[root@localhost ~]# docker images
REPOSITORY   TAG       IMAGE ID       CREATED        SIZE
httpd        2.4.53    c30a46771695   4 days ago     144MB
httpd        latest    dabbfbe0c57b   4 months ago   144MB
[root@localhost ~]# docker run -it --name test busybox /bin/sh   //可以直接把镜像下载,创建容器并启动,-it交互模式,--name容器名字,busybox镜像下载到/bin/sh里面
Unable to find image 'busybox:latest' locally
latest: Pulling from library/busybox
5cc84ad355aa: Pull complete 
Digest: sha256:5acba83a746c7608ed544dc1533b87c737a0b0fb730301639a0179f9344b1678
Status: Downloaded newer image for busybox:latest
/ # ip a  //查看ip
1: lo:  mtu 65536 qdisc noqueue qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
14: eth0@if15:  mtu 1500 qdisc noqueue 
    link/ether 02:42:ac:11:00:02 brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.2/16 brd 172.17.255.255 scope global eth0
       valid_lft forever preferred_lft forever
/ # exit
[root@localhost ~]# docker start test      //启动了但是没有进去
test
[root@localhost ~]# docker ps
CONTAINER ID   IMAGE     COMMAND     CREATED         STATUS         PORTS     NAMES
e9c6bc665bfe   busybox   "/bin/sh"   4 minutes ago   Up 4 seconds             test
[root@localhost ~]# docker exec -it test /bin/sh    //用这个方式进去就算退出了也还在运行
/ # ip a
1: lo:  mtu 65536 qdisc noqueue qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
16: eth0@if17:  mtu 1500 qdisc noqueue 
    link/ether 02:42:ac:11:00:02 brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.2/16 brd 172.17.255.255 scope global eth0
       valid_lft forever preferred_lft forever
/ # exit
[root@localhost ~]# docker ps
CONTAINER ID   IMAGE     COMMAND     CREATED         STATUS              PORTS     NAMES
e9c6bc665bfe   busybox   "/bin/sh"   6 minutes ago   Up About a minute             test

[root@localhost ~]# docker attch test   //用这种方式进去,exit之后就停掉了


 

你可能感兴趣的:(docker)