Docker容器技术

Posted 酷酷的二连长

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Docker容器技术相关的知识,希望对你有一定的参考价值。

Docker介绍

什么是容器

Linux容器是与系统其他部分隔离开的一系列进程,从另一个系统镜像运行,并由该镜像提供支持进程所需的全部文件。

容器镜像包含了应用的所有依赖项,因而在从开发到测试再到生产的整个过程中,它都具有可移植性和一致性。

来源:https://www.redhat.com/zh/topics/containers/whats-a-linux-container

容器就是虚拟化吗?

虚拟化使得许多操作系统可同时在单个系统上运行。

容器只能共享操作系统内核,将应用进程与系统其他部分,隔离开。

容器和虚拟化的区别

linux容器技术,容器虚拟化和kvm虚拟化的区别

kvm虚拟化:需要硬件的支持,需要模拟硬件,可以运行不同的操作系统,启动时间分钟级(开机启动流程)

容器虚拟化:不需要硬件的支持。不需要模拟硬件,共用宿主机的内核,启动时间秒级(没有开机启动流程)

容器总结:

(1)与宿主机使用同一个内核,性能损耗小;

(2)不需要指令级模拟;

(3)容器可以在CPU核心的本地运行指令,不需要任何专门的解释机制;

(4)避免了准虚拟化和系统调用替换中的复杂性;

(5)轻量级隔离,在隔离的同时还提供共享机制,以实现容器与宿主机的资源共享。

容器技术的发展过程

chroot技术,新建一个子系统

chroot,即 change root directory (更改 root 目录)。在 linux 系统中,系统默认的目录结构都是以 `/`,即是以根 (root) 开始的。而在使用 chroot 之后,系统的目录结构将以指定的位置作为 `/` 位置。

参考资料:https://www.ibm.com/developerworks/cn/linux/l-cn-chroot/

使用chroot监狱限制SSH用户访问指定目录和使用指定命令:https://linux.cn/article-8313-1.html

lxc部署

Linux Container容器是一种内核虚拟化技术,可以提供轻量级的虚拟化,以便隔离进程和资源。

安装lxc

需要使用epel源

#安装epel源

yum install epel-release -y

#编译epel源配置文件

vi  /etc/yum.repos.d/epel.repo
[epel]
name=Extra Packages for Enterprise Linux 7 - $basearch
baseurl=https://mirrors.tuna.tsinghua.edu.cn/epel/7/$basearch
#mirrorlist=https://mirrors.fedoraproject.org/metalink?repo=epel-7&arch=$basearch
failovermethod=priority
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7

[epel-debuginfo]
name=Extra Packages for Enterprise Linux 7 - $basearch - Debug
baseurl=https://mirrors.tuna.tsinghua.edu.cn/epel/7/$basearch/debug
#mirrorlist=https://mirrors.fedoraproject.org/metalink?repo=epel-debug-7&arch=$basearch
failovermethod=priority
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7
gpgcheck=1

[epel-source]
name=Extra Packages for Enterprise Linux 7 - $basearch - Source
baseurl=https://mirrors.tuna.tsinghua.edu.cn/epel/7/SRPMS
#mirrorlist=https://mirrors.fedoraproject.org/metalink?repo=epel-source-7&arch=$basearch
failovermethod=priority
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7
gpgcheck=1

##安装lxc

yum install lxc-* -y
yum install libcgroup* -y
yum install bridge-utils.x86_64 -y

交接网卡

[root@controller ~]# cat /etc/sysconfig/network-scripts/ifcfg-eth0 
TYPE=Ethernet
BOOTPROTO=none
NAME=eth0
DEVICE=eth0
ONBOOT=yes
BRIDGE=br0

[root@controller ~]# cat /etc/sysconfig/network-scripts/ifcfg-br0 
TYPE=Bridge
BOOTPROTO=static
NAME=br0
DEVICE=br0
ONBOOT=yes
IPADDR=10.0.0.11
NETMASK=255.255.255.0
GATEWAY=10.0.0.254
DNS1=223.5.5.5

修改lxc默认配置

vi /etc/lxc/default.conf
修改第2行为:lxc.network.link = br0

启动cgroup服务

systemctl enable cgconfig.service
systemctl start cgconfig.service

创建lxc容器

方法1:
lxc-create -t download -n centos7 -- --server mirrors.tuna.tsinghua.edu.cn/lxc-images -d centos -r 7 -a amd64
方法2:
lxc-create -t centos -n test

为容器指定ip和网关

vi /var/lib/lxc/centos7/config
lxc.network.name = eth0
lxc.network.ipv4 = 10.0.0.111/24
lxc.network.ipv4.gateway = 10.0.0.254

启动容器

lxc-start -n centos7

lxc实操

#查看虚拟机

[root@docker opt]# lxc-ls   
centos7  

修改子系统root密码

[root@docker opt]# chroot /var/lib/lxc/centos7/rootfs passwd    
Changing password for user root. 
New password: 
BAD PASSWORD: The password is shorter than 8 characters
Retype new password: 
passwd: all authentication tokens updated successfully.

启动子系统

[root@docker opt]# lxc-start -n centos7   
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)!

检测

[root@docker ~]# lxc-checkconfig     
Kernel configuration not found at /proc/config.gz; searching...
Kernel configuration found at /boot/config-3.10.0-327.el7.x86_64
--- Namespaces ---
Namespaces: enabled
Utsname namespace: enabled
Ipc namespace: enabled
Pid namespace: enabled
User namespace: enabled
newuidmap is not installed
newgidmap is not installed
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

docker容器

Docker是通过内核虚拟化技术(namespaces及cgroups cpu、内存、磁盘io等)来提供容器的资源隔离与安全保障等。由于Docker通过操作系统层的虚拟化实现隔离,所以Docker容器在运行时,不需要类似虚拟机(VM)额外的操作系统开销,提高资源利用率。

docker的主要目标是"Build,Ship and Run any App,Angwhere",构建,运输,处处运行

构建:做一个docker镜像

运输:docker pull

运行:启动一个容器

每一个容器,他都有自己的文件系统rootfs.

kvm解决了硬件和操作系统之间的依赖

docker解决了软件和操作系统环境之间的依赖,能够让独立服务或应用程序在不同的环境中,得到相同的运行结果。

docker容器是一种轻量级、可移植、自包含的软件打包技术,使应用程序可以在几乎任何地方以相同的方式运行。开发人员在自己笔记本上创建并测试好的容器,无需任何修改就能够在生产系统的虚拟机、物理服务器或公有云主机上运行。

Docker的部署

wget -O /etc/yum.repos.d/docker-ce.repo https://mirrors.ustc.edu.cn/docker-ce/linux/centos/docker-ce.repo

sed -i \'s#download.docker.com#mirrors.ustc.edu.cn/docker-ce#g\' /etc/yum.repos.d/docker-ce.repo

yum install docker-ce -y

docker的主要组成部分

docker是传统的CS架构分为docker client和docker server,向mysql一样

命令:docker version

[root@controller ~]# docker version 
Client:
 Version:    17.12.0-ce
 API version:    1.35
 Go version:    go1.9.2
 Git commit:    c97c6d6
 Built:    Wed Dec 27 20:10:14 2017
 OS/Arch:    linux/amd64

Server:
 Engine:
  Version:    17.12.0-ce
  API version:    1.35 (minimum version 1.12)
  Go version:    go1.9.2
  Git commit:    c97c6d6
  Built:    Wed Dec 27 20:12:46 2017
  OS/Arch:    linux/amd64
  Experimental:    false

设置docker远程执行

systemd详解:http://www.ruanyifeng.com/blog/2016/03/systemd-tutorial-part-two.html

在linux-node1设置

vim /usr/lib/systemd/system/docker.service
ExecStart=/usr/bin/dockerd -H unix:///var/run/docker.sock -H tcp://10.0.0.11:2375

systemctl daemon-reload systemctl restart docker.service
ps
-ef检查

在linux-node2设置

wget -O /etc/yum.repos.d/docker-ce.repo https://mirrors.ustc.edu.cn/docker-ce/linux/centos/docker-ce.repo

sed -i \'s#download.docker.com#mirrors.ustc.edu.cn/docker-ce#g\' /etc/yum.repos.d/docker-ce.repo

yum install docker-ce -y

docker -H 10.0.0.11 info     ---  远程执行 info 展示docker的信息

docker主要组件有:镜像、容器、仓库

启动第一个容器

命令:docker run -d -p 80:80 nginx

实操:

[root@docker-node1 ~]# docker run -d -p 80:80 nginx
Unable to find image \'nginx:latest\' locally
latest: Pulling from library/nginx
e7bb522d92ff: Pull complete 
6edc05228666: Pull complete 
cd866a17e81f: Pull complete 
Digest: sha256:285b49d42c703fdf257d1e2422765c4ba9d3e37768d6ea83d7fe2043dad6e63d
Status: Downloaded newer image for nginx:latest
e1cb110a537622e4a5c885161bca69478adc5d218e6eb4e0307c7fe0c1350012
#run: 创建并运行一个容器,
#-d:放在后台
#-p:端口映射
#80:80:前面是宿主机的,后面是容器的
#nginx:镜像的名字

docker的镜像管理

搜索镜像

命令:docker search

实操:

[root@docker-node1 ~]# docker search centos
NAME(镜像名)     DESCRIPTION(说明)             STARS(送心数)  OFFICIAL(是否是官方的)    AUTOMATED(是否自动)
centos             The official build of CentOS.   3992               [OK]

获取镜像

命令:docker pull

实操:

[root@docker-node1 ~]# docker pull centos    --- 拉取一个镜像centos(不指定版本默认为最新版,只写名字默认在官方拉取)
Using default tag: latest
latest: Pulling from library/centos
af4b0a2388c6: Pull complete 
Digest: sha256:2671f7a3eea36ce43609e9fe7435ade83094291055f1c96d9d1d1d7c0b986a5d
Status: Downloaded newer image for centos:latest
[root@docker-node1 ~]# docker images 
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
centos              latest              ff426288ea90        3 weeks ago         207MB
nginx               latest              3f8a4339aadd        5 weeks ago         108MB

拉取非官网的镜像:

[root@docker-node1 ~]# docker pull index.tenxcloud.com/tenxcloud/httpd:2.4
2.4: Pulling from tenxcloud/httpd
8b87079b7a06: Downloading  11.53MB/51.36MB
a3ed95caeb02: Download complete 
0c30bf087cf7: Download complete 
79f2be53847c: Downloading  11.14MB/11.7MB
7063c4b35837: Download complete 
5c27df81ae71: Download complete

镜像加速

镜像加速器:阿里云加速器,daocloud加速器,中科大加速器,Docker 中国官方镜像加速:https://registry.docker-cn.com

镜像加速配置:

vi /etc/docker/daemon.json
{
  "registry-mirrors": ["https://registry.docker-cn.com"]
}    

第三方docker镜像仓库,使用方法

docker pull index.tenxcloud.com/tenxcloud/httpd:latest

镜像操作

查看镜像 

docker images

删除镜像

docker rmi  例子:docker image rm centos:latest

实操:

[root@docker ~]# docker image rm centos:latest (名字:版本)
Untagged: centos:latest
Untagged: centos@sha256:2671f7a3eea36ce43609e9fe7435ade83094291055f1c96d9d1d1d7c0b986a5d
Deleted: sha256:ff426288ea903fcf8d91aca97460c613348f7a27195606b45f19ae91776ca23d
Deleted: sha256:e15afa4858b655f8a5da4c4a41e05b908229f6fab8543434db79207478511ff7
[root@docker ~]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
nginx               latest              3f8a4339aadd        5 weeks ago         108MB

导出镜像

docker save  例子:docker image save centos > docker-centos7.4.tar.gz

实操:

[root@docker ~]# docker image save centos > docker-centos7.4.tar.gz
[root@docker ~]# ls docker-centos7.4.tar.gz
docker-centos7.4.tar.gz

导入镜像

docker load  例子:docker image load -i docker-centos7.4.tar.gz

实操:

[root@docker ~]# docker image load -i docker-centos7.4.tar.gz 
e15afa4858b6: Loading layer  215.8MB/215.8MB
Loaded image: centos:latest
[root@docker ~]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
centos              latest              ff426288ea90        3 weeks ago         207MB
nginx               latest              3f8a4339aadd        5 weeks ago         108MB

查看镜像详细信息

[root@docker ~]# docker image inspect centos
[
    {
        "Id": "sha256:ff426288ea903fcf8d91aca97460c613348f7a27195606b45f19ae91776ca23d",
        "RepoTags": [
            "centos:latest"
        ],
        "RepoDigests": [],
        "Parent": "",
        "Comment": "",
        "Created": "2018-01-08T19:58:27.63047329Z",
        "Container": "dd31c81a4b47b90a14cf6d1c7389465060e390f12a0b71189d181a0458d8443f",
        "ContainerConfig": {
            "Hostname": "dd31c81a4b47",
            "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",
                "#(nop) ",
                "CMD [\\"/bin/bash\\"]"
            ],
            "ArgsEscaped": true,
            "Image": "sha256:5a28642a68c5af8083107fca9ffbc025179211209961eae9b1f40f928331fa90",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": {
                "build-date": "20180107",
                "license": "GPLv2",
                "name": "CentOS Base Image",
                "vendor": "CentOS"
            }
        },
        "DockerVersion": "17.06.2-ce",
        "Author": "",
        "Config": {
            "Hostname": "",
            "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/bash"
            ],
            "ArgsEscaped": true,
            "Image": "sha256:5a28642a68c5af8083107fca9ffbc025179211209961eae9b1f40f928331fa90",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": {
                "build-date": "20180107",
                "license": "GPLv2",
                "name": "CentOS Base Image",
                "vendor": "CentOS"
            }
        },
        "Architecture": "amd64",
        "Os": "linux",
        "Size": 207191530,
        "VirtualSize": 207191530,
        "GraphDriver": {
            "Data": {
                "DeviceId": "10",
                "DeviceName": "docker-8:2-667845-6de21ff18b07a4a121111b78d105af3ae3d1eccf0d5bcf3dff957e3640a79dac",
                "DeviceSize": "10737418240"
            },
            "Name": "devicemapper"
        },
        "RootFS": {
            "Type": "layers",
            "Layers": [
                "sha256:e15afa4858b655f8a5da4c4a41e05b908229f6fab8543434db79207478511ff7"
            ]
        },
        "Metadata": {
            "LastTagTime": "0001-01-01T00:00:00Z"
        }
    }
]
查看镜像详细信息

Docker的容器管理

启动一个容器

docker run -d -p 80:80 nginx

查看启动的容器(两种方法):

[root@docker-node1 ~]# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                NAMES
75516b38df19        nginx               "nginx -g \'daemon of…"   3 hours ago         Up 3 hours          0.0.0.0:80->80/tcp   inspiring_euler

[root@docker-node1 ~]# docker container ls
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                NAMES
75516b38df19        nginx               "nginx -g \'daemon of…"   3 hours ago         Up 3 hours          0.0.0.0:80->80/tcp   inspiring_euler

显示所有状态的容器

[root@docker-node1 ~]# docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                   PORTS                NAMES
75516b38df19        nginx               "nginx -g \'daemon of…"   3 hours ago         Up 3 hours               0.0.0.0:80->80/tcp   inspiring_euler
e1cb110a5376        nginx               "nginx -g \'daemon of…"   3 hours ago         Exited (0) 3 hours ago                        thirsty_brattain

只显示容器id

[root@docker-node1 ~]# docker ps -a -q
7cef098bebc7
75516b38df19

查看容器ip

docker container inspect id或name

[root@docker-node1 ~]# docker container inspect 75516b38df19
[
    {
        "Id": "75516b38df194d00fbb2d5ce51316f621f76a1037a0fdf1d578d14498a68d8a3",
        "Created": "2018-01-31T12:12:06.387035752Z",
        "Path": "nginx",
        "Args": [
            "-g",
            "daemon off;"
        ],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 19388,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2018-01-31T12:12:06.710448922Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:3f8a4339aadda5897b744682f5f774dc69991a81af8d715d37a616bb4c99edf5",
        "ResolvConfPath": "/var/lib/docker/containers/75516b38df194d00fbb2d5ce51316f621f76a1037a0fdf1d578d14498a68d8a3/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/75516b38df194d00fbb2d5ce51316f621f76a1037a0fdf1d578d14498a68d8a3/hostname",
        "HostsPath": "/var/lib/docker/containers/75516b38df194d00fbb2d5ce51316f621f76a1037a0fdf1d578d14498a68d8a3/hosts",
        "LogPath": "/var/lib/docker/containers/75516b38df194d00fbb2d5ce51316f621f76a1037a0fdf1d578d14498a68d8a3/75516b38df194d00fbb2d5ce51316f621f76a1037a0fdf1d578d14498a68d8a3-json.log",
        "Name": "/inspiring_euler",
        "RestartCount": 0,
        "Driver": "devicemapper",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "",
        "ExecIDs": null,
        "HostConfig": {
            "Binds": 以上是关于Docker容器技术的主要内容,如果未能解决你的问题,请参考以下文章

Docker 容器相关技术

微服务架构:基于微服务和Docker容器技术的PaaS云平台架构设计

Docker容器技术和传统虚拟机技术的特性比较

Docker容器

docker容器技术

Docker容器基础介绍