Docker入门到部署

文章目录

    • 1. docker安装
      • 1.1 系统环境
      • 1.2 yum源准备
      • 1.3 安装依赖包
      • 1.4 安装docker-ce
      • 1.5 启动docker服务
      • 1.6 配置镜像加速
    • 2. Docker镜像基本管理
      • 2.1 基础镜像拉取
      • 2.2 镜像查看
      • 2.3 镜像详细信息查看
      • 2.4 查看镜像ID
      • 2.5 镜像导入和导出
      • 2.6 镜像删除
    • 3. 容器的管理
      • 3.1 容器运行
        • 3.1.1 交互式启动容器
        • 3.1.2 守护式容器
      • 3.2 容器应用场景
      • 3.3 启动
      • 3.4 连接容器
    • 4. docker容器网络访问
    • 5. 容器其他管理
    • 6. Docker数据卷实现持久化存储
      • 6.1 手工交互数据
      • 6.2 Volume实现宿主机和容器的数据共享
      • 6.3 数据卷容器
    • 7. 构建本地yum源
      • 7.1 安装vsftpd服务
      • 7.2 配置Yum仓库
      • 7.3 ssh登录容器
    • 8. 镜像制作
    • 9. 构建LAMP镜像
      • 9.1 基于(Centos6.9)LAMP制作基础镜像
    • 10. 镜像制作dockerfile
      • 10.1 dockerfile常用指令
      • 10.2 dockerfile基本制作
      • 10.3 dockerfile 构建LAMP基础环境镜像
      • 10.4 copy命令和add命令解释
    • 11. 构建私有registry
    • 12. docker registry验证
      • 12.1 registry加密验证
    • 13. harbor安装
      • 13.1 habor实现图形化镜像仓库
    • 14. docker网络类型
      • 14.1 本地网络
      • 14.2 网络类型
      • 14.3 跨主机网络访问-macvlan实现
      • 14.4 docker 跨主机访问-overlay实现

1. docker安装

1.1 系统环境

系统版本: [root@wldev08 ~]# cat /etc/redhat-release 
CentOS Linux release 7.3.1611 (Core)

1.2 yum源准备

[root@wldev08 ~]# curl  http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo -o /etc/yum.repos.d/docker-ce.repo
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  2640  100  2640    0     0  12280      0 --:--:-- --:--:-- --:--:-- 12336
[root@wldev08 ~]# wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
[root@wldev08 ~]# curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  2523  100  2523    0     0  35338      0 --:--:-- --:--:-- --:--:-- 35535

1.3 安装依赖包

[root@wldev08 ~]# yum install -y yum-utils device-mapper-persistent-data lvm2
[root@wldev08 ~]# yum list docker-ce.x86_64 --showduplicates | sort -r
已加载插件:fastestmirror
可安装的软件包
 * updates: mirrors.aliyun.com
Loading mirror speeds from cached hostfile
 * extras: mirrors.aliyun.com
docker-ce.x86_64            3:19.03.4-3.el7                     docker-ce-stable
docker-ce.x86_64            3:19.03.3-3.el7                     docker-ce-stable
docker-ce.x86_64            3:19.03.2-3.el7  
docker-ce.x86_64            3:18.09.2-3.el7                     docker-ce-stable
docker-ce.x86_64            3:18.09.1-3.el7                     docker-ce-stable
docker-ce.x86_64            3:18.09.0-3.el7                     docker-ce-stable
docker-ce.x86_64            18.06.3.ce-3.el7                    docker-ce-stable
docker-ce.x86_64            18.06.2.ce-3.el7                    docker-ce-stable
docker-ce.x86_64            18.06.1.ce-3.el7                    docker-ce-stable
docker-ce.x86_64            18.06.0.ce-3.el7                    docker-ce-stable
docker-ce.x86_64            18.03.1.ce-1.el7.centos             
docker-ce.x86_64            17.09.1.ce-1.el7.centos             docker-ce-stable
docker-ce.x86_64            17.09.0.ce-1.el7.centos             docker-ce-stable
docker-ce.x86_64            17.06.2.ce-1.el7.centos             docker-ce-stable
docker-ce.x86_64            17.06.1.ce-1.el7.centos             docker-ce-stable
docker-ce.x86_64            17.06.0.ce-1.el7.centos             docker-ce-stable
docker-ce.x86_64            17.03.3.ce-1.el7                    docker-ce-stable
docker-ce.x86_64            17.03.2.ce-1.el7.centos             docker-ce-stable
docker-ce.x86_64            17.03.1.ce-1.el7.centos             docker-ce-stable
docker-ce.x86_64            17.03.0.ce-1.el7.centos             docker-ce-stable
 * base: mirrors.aliyun.com

1.4 安装docker-ce

[root@wldev08 ~]# yum -y install docker-ce
yum install -y --setopt=obsoletes=0 \
docker-ce-17.03.2.ce-1.el7.centos.x86_64 \
docker-ce-selinux-17.03.2.ce-1.el7.centos.noarch

1.5 启动docker服务

[root@wldev08 ~]# systemctl daemon-reload
[root@wldev08 ~]# systemctl restart docker
[root@wldev08 ~]# docker version
Client: Docker Engine - Community
 Version:           19.03.4
 API version:       1.40
 Go version:        go1.12.10
 Git commit:        9013bf583a
 Built:             Fri Oct 18 15:52:22 2019
 OS/Arch:           linux/amd64
 Experimental:      false

Server: Docker Engine - Community
 Engine:
  Version:          19.03.4
  API version:      1.40 (minimum version 1.12)
  Go version:       go1.12.10
  Git commit:       9013bf583a
  Built:            Fri Oct 18 15:50:54 2019
  OS/Arch:          linux/amd64
  Experimental:     false
 containerd:
  Version:          1.2.10
  GitCommit:        b34a5c8af56e510852c35414db4c1f4fa6172339
 runc:
  Version:          1.0.0-rc8+dev
  GitCommit:        3e425f80a8c931f88e6d94a8c831b9d5aa481657
 docker-init:
  Version:          0.18.0
  GitCommit:        fec3683
[root@wldev08 ~]# docker info
Client:
 Debug Mode: false

Server:
 Containers: 0
  Running: 0
  Paused: 0
  Stopped: 0
 Images: 0
 Server Version: 19.03.4
 Storage Driver: overlay2
  Backing Filesystem: xfs
  Supports d_type: true
  Native Overlay Diff: false
 Logging Driver: json-file
 Cgroup Driver: cgroupfs
 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: runc
 Default Runtime: runc
 Init Binary: docker-init
 containerd version: b34a5c8af56e510852c35414db4c1f4fa6172339
 runc version: 3e425f80a8c931f88e6d94a8c831b9d5aa481657
 init version: fec3683
 Security Options:
  seccomp
   Profile: default
 Kernel Version: 3.10.0-514.el7.x86_64
 Operating System: CentOS Linux 7 (Core)
 OSType: linux
 Architecture: x86_64
 CPUs: 1
 Total Memory: 7.64GiB
 Name: wldev08
 ID: ZD2X:YYD3:6ZFN:NQH4:WXTU:LCIK:3BEA:LL4M:CL2L:QLZB:77X2:XKIV
 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
 Live Restore Enabled: false

[root@wldev08 ~]# 

1.6 配置镜像加速

这里使用的是阿里云镜像加速,选择镜像加速器,地址:
https://cr.console.aliyun.com/cn-hangzhou/mirrors

[root@wldev08 ~]# mkdir -p /etc/docker
[root@wldev08 ~]# tee /etc/docker/daemon.json <<-'EOF'
> {
>   "registry-mirrors": ["https://b3z80jv9.mirror.aliyuncs.com"]
> }
> EOF
{
  "registry-mirrors": ["https://b3z80jv9.mirror.aliyuncs.com"]
}
[root@wldev08 ~]# systemctl daemon-reload
[root@wldev08 ~]# systemctl restart docker

或者
vim   /etc/docker/daemon.json

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

docker体系结构 Docker入门到部署_第1张图片

2. Docker镜像基本管理

2.1 基础镜像拉取

[root@wldev08 ~]# docker search centos
NAME                               DESCRIPTION                                     STARS               OFFICIAL            AUTOMATED
centos                             The official build of CentOS.                   5637                [OK]                
ansible/centos7-ansible            Ansible on Centos7                              125                                     [OK]
jdeathe/centos-ssh                 OpenSSH / Supervisor / EPEL/IUS/SCL Repos - …   114                                     [OK]
consol/centos-xfce-vnc             Centos container with "headless" VNC session…   100                                     [OK]
centos/mysql-57-centos7            MySQL 5.7 SQL database server                   63                                      
imagine10255/centos6-lnmp-php56    centos6-lnmp-php56                              57                                      [OK]
tutum/centos                       Simple CentOS docker image with SSH access      44                                      
centos/postgresql-96-centos7       PostgreSQL is an advanced Object-Relational …   39                                      
kinogmt/centos-ssh                 CentOS with SSH                                 29                                      [OK]
pivotaldata/centos-gpdb-dev        CentOS image for GPDB development. Tag names…   10                                      
nathonfowlie/centos-jre            Latest CentOS image with the JRE pre-install…   8                                       [OK]
drecom/centos-ruby                 centos ruby                                     6                                       [OK]
mamohr/centos-java                 Oracle Java 8 Docker image based on Centos 7    3                                       [OK]
darksheer/centos                   Base Centos Image -- Updated hourly             3                                       [OK]
pivotaldata/centos                 Base centos, freshened up a little with a Do…   3                                       
pivotaldata/centos-mingw           Using the mingw toolchain to cross-compile t…   2                                       
pivotaldata/centos-gcc-toolchain   CentOS with a toolchain, but unaffiliated wi…   2                                       
miko2u/centos6                     CentOS6 日本語環境                                   2                                       [OK]
indigo/centos-maven                Vanilla CentOS 7 with Oracle Java Developmen…   1                                       [OK]
blacklabelops/centos               CentOS Base Image! Built and Updates Daily!     1                                       [OK]
mcnaughton/centos-base             centos base image                               1                                       [OK]
pivotaldata/centos6.8-dev          CentosOS 6.8 image for GPDB development         0                                       
pivotaldata/centos7-dev            CentosOS 7 image for GPDB development           0                                       
smartentry/centos                  centos with smartentry                          0                                       [OK]
fortinj66/centos7-s2i-nodejs       based off of ryanj/centos7-s2i-nodejs.  Bigg…   0                                       
[root@wldev08 ~]# docker pull centos:6.9
6.9: Pulling from library/centos
831490506c47: Pull complete 
Digest: sha256:6fff0a9edc920968351eb357c5b84016000fec6956e6d745f695e5a34f18ecd2
Status: Downloaded newer image for centos:6.9
docker.io/library/centos:6.9
[root@wldev08 ~]# docker pull centos:7.5.1804
7.5.1804: Pulling from library/centos
5ad559c5ae16: Pull complete 
Digest: sha256:7a45e4a1efbaafc1d9aa89925b6fdb33288a96d35ea0581412316e2f0ad3720a
Status: Downloaded newer image for centos:7.5.1804
docker.io/library/centos:7.5.1804
[root@wldev08 ~]# docker pull nginx
Using default tag: latest
latest: Pulling from library/nginx
8d691f585fa8: Pull complete 
5b07f4e08ad0: Pull complete 
abc291867bca: Pull complete 
Digest: sha256:922c815aa4df050d4df476e92daed4231f466acc8ee90e0e774951b0fd7195a4
Status: Downloaded newer image for nginx:latest
docker.io/library/nginx:latest

2.2 镜像查看

[root@wldev08 ~]# docker images 
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
nginx               latest              540a289bab6c        7 days ago          126MB
centos              6.9                 2199b8eb8390        7 months ago        195MB
centos              7.5.1804            cf49811e3cdb        7 months ago        200MB
[root@wldev08 ~]# docker image list
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
nginx               latest              540a289bab6c        7 days ago          126MB
centos              6.9                 2199b8eb8390        7 months ago        195MB
centos              7.5.1804            cf49811e3cdb        7 months ago        200MB

标识镜像唯一性的方法:
1. REPOSITORY:TAG
centos:7.5.1804 
2. IMAGE ID (sha256:64位的号码,默认只截取12位)
82f3b5f3c58

2.3 镜像详细信息查看

[root@wldev08 ~]# docker image inspect nginx:latest

nginx:镜像名称
latest:TAG

或者

[root@wldev08 ~]# docker image inspect 540a289bab6c

540a289bab6c: image tag 标签

2.4 查看镜像ID

[root@wldev08 ~]# docker image ls -q
540a289bab6c
2199b8eb8390
cf49811e3cdb

2.5 镜像导入和导出

[root@wldev08 ~]# docker image list
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
nginx               latest              540a289bab6c        7 days ago          126MB
centos              6.9                 2199b8eb8390        7 months ago        195MB
centos              7.5.1804            cf49811e3cdb        7 months ago        200MB
[root@wldev08 ~]# docker image save 540a289bab6c >/tmp/nginx-v1.tar
[root@wldev08 ~]# docker image rm 540a289bab6c
Untagged: nginx:latest
Untagged: nginx@sha256:922c815aa4df050d4df476e92daed4231f466acc8ee90e0e774951b0fd7195a4
Deleted: sha256:540a289bab6cb1bf880086a9b803cf0c4cefe38cbb5cdefa199b69614525199f
Deleted: sha256:ab18af7cee69bfb22c1771e54d5e0e68b1a1bf57bb46516142da0380b1771f4a
Deleted: sha256:02f7daf1e14541cd61a3dda1a61cc0f78fee8de2984d488b8ba5bbd3cbad9b57
Deleted: sha256:b67d19e65ef653823ed62a5835399c610a40e8205c16f839c5cc567954fcf594
[root@wldev08 ~]# docker image load -i /tmp/nginx-v1.tar 
b67d19e65ef6: Loading layer [==================================================>]   72.5MB/72.5MB
6eaad811af02: Loading layer [==================================================>]  57.54MB/57.54MB
a89b8f05da3a: Loading layer [==================================================>]  3.584kB/3.584kB
Loaded image ID: sha256:540a289bab6cb1bf880086a9b803cf0c4cefe38cbb5cdefa199b69614525199f
[root@wldev08 ~]# docker image tag 540a289bab6c nginx:v2
[root@wldev08 ~]# docker image list
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
nginx               v2                  540a289bab6c        7 days ago          126MB
centos              6.9                 2199b8eb8390        7 months ago        195MB
centos              7.5.1804            cf49811e3cdb        7 months ago        200MB

2.6 镜像删除

[root@wldev08 ~]# docker image rm -f 540a289bab6c
删除指定的镜像
或者

[root@wldev08 ~]# docker image rm -f 'docker image ls -q'

删除所有的镜像

3. 容器的管理

3.1 容器运行

3.1.1 交互式启动容器
[root@wldev08 ~]# docker image list
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
nginx               v2                  540a289bab6c        7 days ago          126MB
centos              6.9                 2199b8eb8390        7 months ago        195MB
centos              7.5.1804            cf49811e3cdb        7 months ago        200MB
[root@wldev08 ~]# docker container run -it cf49811e3cdb
[root@5c04b3982b49 /]# cat /etc/redhat-release 
CentOS Linux release 7.5.1804 (Core) 
[root@5c04b3982b49 /]# 

宿主机
[root@wldev08 ~]# cat /etc/redhat-release 
CentOS Linux release 7.3.1611 (Core) 
[root@wldev08 ~]# docker container ls
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
5c04b3982b49        cf49811e3cdb        "/bin/bash"         40 seconds ago      Up 40 seconds                           boring_kapitsa
[root@wldev08 ~]# 

CONTAINER ID : 容器的唯一号码(自动生成的)
NAMES		 : 容器的名字(可以自动,也可以手工指定)
STATUS	     : 容器的运行状态( Exited , Up)

  • 手动指定名字启动容器
[root@wldev08 ~]# docker image ls
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
nginx               v2                  540a289bab6c        7 days ago          126MB
centos              6.9                 2199b8eb8390        7 months ago        195MB
centos              7.5.1804            cf49811e3cdb        7 months ago        200MB
[root@wldev08 ~]# docker container run -it --name="centos-v1" cf49811e3cdb
[root@2117378dd5cd /]# 

宿主机查看
[root@wldev08 ~]# docker container ls
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
2117378dd5cd        cf49811e3cdb        "/bin/bash"         7 seconds ago       Up 7 seconds                            centos-v1
5c04b3982b49        cf49811e3cdb        "/bin/bash"         6 minutes ago       Up 6 minutes                            boring_kapitsa
[root@wldev08 ~]# 

[root@wldev08 ~]# docker container ls -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                     PORTS               NAMES
2117378dd5cd        cf49811e3cdb        "/bin/bash"         5 minutes ago       Exited (0) 4 seconds ago                       centos-v1
5c04b3982b49        cf49811e3cdb        "/bin/bash"         11 minutes ago      Up 11 minutes                                  boring_kapitsa
[root@wldev08 ~]#
3.1.2 守护式容器
[root@wldev08 ~]# docker run -d --name="nginx-1.14" nginx:1.14
Unable to find image 'nginx:1.14' locally
1.14: Pulling from library/nginx
27833a3ba0a5: Pull complete 
0f23e58bd0b7: Pull complete 
8ca774778e85: Pull complete 
Digest: sha256:f7988fb6c02e0ce69257d9bd9cf37ae20a60f1df7563c3a2a6abe24160306b8d
Status: Downloaded newer image for nginx:1.14
e57937d57ac01aa892074527729fc0bafa804ccf78c0ba660475e4892995c75e

如果本地仓库没有镜像,则会自动下载镜像并在后台启动
[root@wldev08 ~]# docker container ls
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS               NAMES
e57937d57ac0        nginx:1.14          "nginx -g 'daemon of…"   20 seconds ago      Up 19 seconds       80/tcp              nginx-1.14
5c04b3982b49        cf49811e3cdb        "/bin/bash"              22 minutes ago      Up 22 minutes                           boring_kapitsa
[root@wldev08 ~]#
  • 查看容器详细信息
[root@wldev08 ~]# docker container inspect nginx-1.14
[
    {
        "Id": "e57937d57ac01aa892074527729fc0bafa804ccf78c0ba660475e4892995c75e",
        "Created": "2019-10-30T09:00:40.990713718Z",
        "Path": "nginx",
        "Args": [
            "-g",
            "daemon off;"
        ],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 12870,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2019-10-30T09:00:41.29981676Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:295c7be079025306c4f1d65997fcf7adb411c88f139ad1d34b537164aa060369",
        "ResolvConfPath": "/var/lib/docker/containers/e57937d57ac01aa892074527729fc0bafa804ccf78c0ba660475e4892995c75e/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/e57937d57ac01aa892074527729fc0bafa804ccf78c0ba660475e4892995c75e/hostname",
        "HostsPath": "/var/lib/docker/containers/e57937d57ac01aa892074527729fc0bafa804ccf78c0ba660475e4892995c75e/hosts",
        "LogPath": "/var/lib/docker/containers/e57937d57ac01aa892074527729fc0bafa804ccf78c0ba660475e4892995c75e/e57937d57ac01aa892074527729fc0bafa804ccf78c0ba660475e4892995c75e-json.log",
        "Name": "/nginx-1.14",
        "RestartCount": 0,
        "Driver": "overlay2",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "",
        "ExecIDs": null,
        "HostConfig": {
            "Binds": null,
            "ContainerIDFile": "",
            "LogConfig": {
                "Type": "json-file",
                "Config": {}
            },
            "NetworkMode": "default",
            "PortBindings": {},
            "RestartPolicy": {
                "Name": "no",
                "MaximumRetryCount": 0
            },
            "AutoRemove": false,
            "VolumeDriver": "",
            "VolumesFrom": null,
            "CapAdd": null,
            "CapDrop": null,
            "Capabilities": null,
            "Dns": [],
            "DnsOptions": [],
            "DnsSearch": [],
            "ExtraHosts": null,
            "GroupAdd": null,
            "IpcMode": "private",
            "Cgroup": "",
            "Links": null,
            "OomScoreAdj": 0,
            "PidMode": "",
            "Privileged": false,
            "PublishAllPorts": false,
            "ReadonlyRootfs": false,
            "SecurityOpt": null,
            "UTSMode": "",
            "UsernsMode": "",
            "ShmSize": 67108864,
            "Runtime": "runc",
            "ConsoleSize": [
                0,
                0
            ],
            "Isolation": "",
            "CpuShares": 0,
            "Memory": 0,
            "NanoCpus": 0,
            "CgroupParent": "",
            "BlkioWeight": 0,
            "BlkioWeightDevice": [],
            "BlkioDeviceReadBps": null,
            "BlkioDeviceWriteBps": null,
            "BlkioDeviceReadIOps": null,
            "BlkioDeviceWriteIOps": null,
            "CpuPeriod": 0,
            "CpuQuota": 0,
            "CpuRealtimePeriod": 0,
            "CpuRealtimeRuntime": 0,
            "CpusetCpus": "",
            "CpusetMems": "",
            "Devices": [],
            "DeviceCgroupRules": null,
            "DeviceRequests": null,
            "KernelMemory": 0,
            "KernelMemoryTCP": 0,
            "MemoryReservation": 0,
            "MemorySwap": 0,
            "MemorySwappiness": null,
            "OomKillDisable": false,
            "PidsLimit": null,
            "Ulimits": null,
            "CpuCount": 0,
            "CpuPercent": 0,
            "IOMaximumIOps": 0,
            "IOMaximumBandwidth": 0,
            "MaskedPaths": [
                "/proc/asound",
                "/proc/acpi",
                "/proc/kcore",
                "/proc/keys",
                "/proc/latency_stats",
                "/proc/timer_list",
                "/proc/timer_stats",
                "/proc/sched_debug",
                "/proc/scsi",
                "/sys/firmware"
            ],
            "ReadonlyPaths": [
                "/proc/bus",
                "/proc/fs",
                "/proc/irq",
                "/proc/sys",
                "/proc/sysrq-trigger"
            ]
        },
        "GraphDriver": {
            "Data": {
                "LowerDir": "/var/lib/docker/overlay2/5a38c9e102f7cbaa04da40d04f24cda552acc958fbe958cbcac930b312ecaf90-init/diff:/var/lib/docker/overlay2/da3fd6791dac5adae9c430642cf27015ac88ab44403c5bb10b3e2929255ac308/diff:/var/lib/docker/overlay2/bbadf1aa0e035c8694710d356daf8b764cffae025c2cdb288e034b3a1411da06/diff:/var/lib/docker/overlay2/3ebb467dfbefcbd09d7d680913dc3f1b8e2871cc14779fddb195d1ce8568eeb3/diff",
                "MergedDir": "/var/lib/docker/overlay2/5a38c9e102f7cbaa04da40d04f24cda552acc958fbe958cbcac930b312ecaf90/merged",
                "UpperDir": "/var/lib/docker/overlay2/5a38c9e102f7cbaa04da40d04f24cda552acc958fbe958cbcac930b312ecaf90/diff",
                "WorkDir": "/var/lib/docker/overlay2/5a38c9e102f7cbaa04da40d04f24cda552acc958fbe958cbcac930b312ecaf90/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "e57937d57ac0",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "ExposedPorts": {
                "80/tcp": {}
            },
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                "NGINX_VERSION=1.14.2-1~stretch",
                "NJS_VERSION=1.14.2.0.2.6-1~stretch"
            ],
            "Cmd": [
                "nginx",
                "-g",
                "daemon off;"
            ],
            "Image": "nginx:1.14",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": {
                "maintainer": "NGINX Docker Maintainers "
            },
            "StopSignal": "SIGTERM"
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "7bbe8b03dd3483046d2e2ccd89591abc68ac6cbef4320b3d3de0d1bd26aea65d",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {
                "80/tcp": null
            },
            "SandboxKey": "/var/run/docker/netns/7bbe8b03dd34",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "5edb8c9423979d4d8f52da6618b392e09bbdcf9aa07ca43b5c157fcbbb7e89d8",
            "Gateway": "172.17.0.1",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "172.17.0.3",
            "IPPrefixLen": 16,
            "IPv6Gateway": "",
            "MacAddress": "02:42:ac:11:00:03",
            "Networks": {
                "bridge": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "NetworkID": "c5c78bb74325753ec615a9323ed07158081fdafbc124419af8dbc601cd92a514",
                    "EndpointID": "5edb8c9423979d4d8f52da6618b392e09bbdcf9aa07ca43b5c157fcbbb7e89d8",
                    "Gateway": "172.17.0.1",
                    "IPAddress": "172.17.0.3",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:ac:11:00:03",
                    "DriverOpts": null
                }
            }
        }
    }
]
[root@wldev08 ~]#
[root@wldev08 ~]# curl -I 172.17.0.3
HTTP/1.1 200 OK
Server: nginx/1.14.2
Date: Wed, 30 Oct 2019 09:03:55 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Tue, 04 Dec 2018 14:44:49 GMT
Connection: keep-alive
ETag: "5c0692e1-264"
Accept-Ranges: bytes

[root@wldev08 ~]#

3.2 容器应用场景

  • 交互式的容器: 工具类: 开发,测试,临时性的任务()
退出自动关闭,需手动删除容器
[root@wldev08 ~]# docker container ls -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                      PORTS               NAMES
e57937d57ac0        nginx:1.14          "nginx -g 'daemon of…"   25 minutes ago      Up 25 minutes               80/tcp              nginx-1.14
2117378dd5cd        cf49811e3cdb        "/bin/bash"              41 minutes ago      Exited (0) 36 minutes ago                       centos-v1
5c04b3982b49        cf49811e3cdb        "/bin/bash"              47 minutes ago      Exited (0) 46 seconds ago                       boring_kapitsa
[root@wldev08 ~]# docker container rm boring_kapitsa
boring_kapitsa
[root@wldev08 ~]# docker container ls -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                      PORTS               NAMES
e57937d57ac0        nginx:1.14          "nginx -g 'daemon of…"   26 minutes ago      Up 26 minutes               80/tcp              nginx-1.14
2117378dd5cd        cf49811e3cdb        "/bin/bash"              42 minutes ago      Exited (0) 36 minutes ago                       centos-v1
[root@wldev08 ~]# 

启动时加入删除容器,退出自动删除
[root@wldev08 ~]# docker image ls
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
nginx               v2                  540a289bab6c        7 days ago          126MB
nginx               1.14                295c7be07902        7 months ago        109MB
centos              6.9                 2199b8eb8390        7 months ago        195MB
centos              7.5.1804            cf49811e3cdb        7 months ago        200MB
[root@wldev08 ~]# docker container run -it --name="centos-v2" --rm 2199b8eb8390

[root@wldev08 ~]# docker container ls -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                      PORTS               NAMES
e74bdd03c671        2199b8eb8390        "/bin/bash"              15 seconds ago      Up 14 seconds                                   centos-v2
e57937d57ac0        nginx:1.14          "nginx -g 'daemon of…"   29 minutes ago      Up 29 minutes               80/tcp              nginx-1.14
2117378dd5cd        cf49811e3cdb        "/bin/bash"              45 minutes ago      Exited (0) 39 minutes ago                       centos-v1

[root@e74bdd03c671 /]# exit
exit
[root@wldev08 ~]# docker container ls -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                      PORTS               NAMES
e57937d57ac0        nginx:1.14          "nginx -g 'daemon of…"   29 minutes ago      Up 29 minutes               80/tcp              nginx-1.14
2117378dd5cd        cf49811e3cdb        "/bin/bash"              45 minutes ago      Exited (0) 40 minutes ago                       centos-v1
[root@wldev08 ~]#
  • 守护式容器: 网络服务
[root@wldev08 ~]# docker run -d --name="nginx-1.14" nginx:1.14
是无法对外访问的
[root@wldev08 ~]# docker image ls
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
nginx               v2                  540a289bab6c        7 days ago          126MB
nginx               1.14                295c7be07902        7 months ago        109MB
centos              6.9                 2199b8eb8390        7 months ago        195MB
centos              7.5.1804            cf49811e3cdb        7 months ago        200MB
[root@wldev08 ~]# docker container ls -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                      PORTS               NAMES
e57937d57ac0        nginx:1.14          "nginx -g 'daemon of…"   36 minutes ago      Up 36 minutes               80/tcp              nginx-1.14
2117378dd5cd        cf49811e3cdb        "/bin/bash"              52 minutes ago      Exited (0) 46 minutes ago                       centos-v1
[root@wldev08 ~]# docker run -d -p 8080:80 --name="nginx-web" 295c7be07902
70a62f1987e0bf27117012fbdae9326ec35e2de4a0730d5155dd937b035fc247
[root@wldev08 ~]#
对外暴露80端口
[root@wldev08 ~]# docker container ls -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                      PORTS                  NAMES
70a62f1987e0        295c7be07902        "nginx -g 'daemon of…"   27 seconds ago      Up 26 seconds               0.0.0.0:8080->80/tcp   nginx-web
e57937d57ac0        nginx:1.14          "nginx -g 'daemon of…"   37 minutes ago      Up 37 minutes               80/tcp                 nginx-1.14
2117378dd5cd        cf49811e3cdb        "/bin/bash"              53 minutes ago      Exited (0) 48 minutes ago                          centos-v1
[root@wldev08 ~]#
[root@wldev08 ~]# curl -I localhost:8080
HTTP/1.1 200 OK
Server: nginx/1.14.2
Date: Wed, 30 Oct 2019 09:39:15 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Tue, 04 Dec 2018 14:44:49 GMT
Connection: keep-alive
ETag: "5c0692e1-264"
Accept-Ranges: bytes

3.3 启动

[root@wldev08 ~]# docker container ls -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                    PORTS                  NAMES
70a62f1987e0        295c7be07902        "nginx -g 'daemon of…"   16 hours ago        Up 16 hours               0.0.0.0:8080->80/tcp   nginx-web
e57937d57ac0        nginx:1.14          "nginx -g 'daemon of…"   16 hours ago        Up 16 hours               80/tcp                 nginx-1.14
2117378dd5cd        cf49811e3cdb        "/bin/bash"              17 hours ago        Exited (0) 17 hours ago                          centos-v1

[root@wldev08 ~]# docker container start/stop 2117378dd5cd
// 只启动不连接,适用于守护式容器
[root@wldev08 ~]# docker container start -i 2117378dd5cd
// 启动并连接,适用于交互式容器
[root@2117378dd5cd /]#

-i 启动后直接登录到容器

3.4 连接容器

  • 登录到已存在(后台)的容器
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                     PORTS                  NAMES
70a62f1987e0        295c7be07902        "nginx -g 'daemon of…"   16 hours ago        Up 16 hours                0.0.0.0:8080->80/tcp   nginx-web
e57937d57ac0        nginx:1.14          "nginx -g 'daemon of…"   17 hours ago        Up 17 hours                80/tcp                 nginx-1.14
2117378dd5cd        cf49811e3cdb        "/bin/bash"              17 hours ago        Exited (0) 7 seconds ago                          centos-v1
[root@wldev08 ~]# docker container start centos-v1
centos-v1
[root@wldev08 ~]# docker container ls -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                  NAMES
70a62f1987e0        295c7be07902        "nginx -g 'daemon of…"   16 hours ago        Up 16 hours         0.0.0.0:8080->80/tcp   nginx-web
e57937d57ac0        nginx:1.14          "nginx -g 'daemon of…"   17 hours ago        Up 17 hours         80/tcp                 nginx-1.14
2117378dd5cd        cf49811e3cdb        "/bin/bash"              17 hours ago        Up 2 seconds                               centos-v1
[root@wldev08 ~]# docker container attach centos-v1
[root@2117378dd5cd /]#
  • 子进程方式登录(在已有工作容器中生成子进程,可以进行容器调试,退出不影响容器)
[root@wldev08 ~]# docker container start centos-v1
centos-v1
[root@wldev08 ~]# docker container ls -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                  NAMES
70a62f1987e0        295c7be07902        "nginx -g 'daemon of…"   16 hours ago        Up 16 hours         0.0.0.0:8080->80/tcp   nginx-web
e57937d57ac0        nginx:1.14          "nginx -g 'daemon of…"   17 hours ago        Up 17 hours         80/tcp                 nginx-1.14
2117378dd5cd        cf49811e3cdb        "/bin/bash"              17 hours ago        Up 3 seconds                               centos-v1
[root@wldev08 ~]# docker container exec -it centos-v1 /bin/bash
[root@2117378dd5cd /]# exit
[root@wldev08 ~]# docker container ls -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                  NAMES
70a62f1987e0        295c7be07902        "nginx -g 'daemon of…"   16 hours ago        Up 16 hours         0.0.0.0:8080->80/tcp   nginx-web
e57937d57ac0        nginx:1.14          "nginx -g 'daemon of…"   17 hours ago        Up 17 hours         80/tcp                 nginx-1.14
2117378dd5cd        cf49811e3cdb        "/bin/bash"              17 hours ago        Up 19 seconds                              centos-v1
[root@wldev08 ~]# 
  • 容器后台与前台运行
  1. ctrl+P,Q 切换至后台运行

attach 可以将容器调用到前台

  1. 死循环方式 如sleep 100000
  1. 让程序前台一直运行(夯在前台)

制作守护式容器时,常用的方法

4. docker容器网络访问

  • 指定映射(docker 会自动添加一条iptables规则来实现端口映射)
-p hostPort:containerPort
-p ip:hostPort:containerPort 
-p ip::containerPort(随机端口:32768-60999)
-p hostPort:containerPort/udp
-p 81:80 –p 443:443   // 多端口映射

如:
[root@docker ~]# docker container run -d -p 8080:80 --name='n2' nginx:1.14    
[root@docker ~]# docker container run -d -p 10.0.0.100:8081:80 --name='n3' nginx:1.14

  • 随机映射
docker run -P 80(随机端口)

[root@docker ~]# docker container run -d -p 80 --name='n5' nginx:1.14

[root@docker ~]# docker container run -d -p 172.16.1.200::80 --name='n6' nginx:1.14
  • 查看映射端口
[root@wldev08 ~]# docker container port 70a62f1987e0
80/tcp -> 0.0.0.0:8080
[root@wldev08 ~]# docker port 70a62f1987e0
80/tcp -> 0.0.0.0:8080
[root@wldev08 ~]# 

5. 容器其他管理

  • 查看所有容器ID
[root@wldev08 ~]# docker container ls -a -q
70a62f1987e0
e57937d57ac0
2117378dd5cd
[root@wldev08 ~]# docker ps -a -q
70a62f1987e0
e57937d57ac0
2117378dd5cd
[root@wldev08 ~]# 

  • 查看容器的进程信息
[root@wldev08 ~]# docker container top 70a62f1987e0
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                13209               13194               0                   10月30               ?                   00:00:00            nginx: master process nginx -g daemon off;
101                 13240               13209               0                   10月30               ?                   00:00:00            nginx: worker process
[root@wldev08 ~]# docker top 70a62f1987e0
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                13209               13194               0                   10月30               ?                   00:00:00            nginx: master process nginx -g daemon off;
101                 13240               13209               0                   10月30               ?                   00:00:00            nginx: worker process
[root@wldev08 ~]# 
  • 查看日志
[root@oldboy docker]# docker logs testxx
[root@oldboy docker]# docker logs -tf testxx

[root@oldboy docker]# docker logs -t testxx
[root@oldboy docker]# docker logs -tf  --tail 10 testxx
[root@oldboy docker]# docker logs -tf  --tail 0 testxx

6. Docker数据卷实现持久化存储

6.1 手工交互数据

[root@docker opt]# docker container cp index.html n1:/usr/share/nginx/html/
将/opt/目录下的index.html拷贝到容器

[root@docker opt]# docker container cp n1:/usr/share/nginx/html/50x.html ./
将容器里的html拷贝到当前目录

6.2 Volume实现宿主机和容器的数据共享

[root@docker opt]# mkdir -p /opt/html
[root@docker ~]# docker run -d --name="nginx_3" -p 83:80 -v /opt/html:/usr/share/nginx/html nginx

类似与软连接形式,作用: 数据持久化

6.3 数据卷容器

  • 宿主机创建数据目录
[root@wldev08 ~]# mkdir -p /opt/Volume/a
[root@wldev08 ~]# mkdir -p /opt/Volume/b
[root@wldev08 ~]# touch /opt/Volume/a/a.txt
[root@wldev08 ~]# touch /opt/Volume/b/b.txt
[root@wldev08 ~]# tree /opt/Volume/
/opt/Volume/
├── a
│   └── a.txt
└── b
    └── b.txt

2 directories, 2 files
[root@wldev08 ~]#
  • 启动数据卷容器
[root@wldev08 ~]# docker image ls
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
nginx               v2                  540a289bab6c        8 days ago          126MB
nginx               1.14                295c7be07902        7 months ago        109MB
centos              6.9                 2199b8eb8390        7 months ago        195MB
centos              7.5.1804            cf49811e3cdb        7 months ago        200MB
[root@wldev08 ~]# docker run -it --name="nginx_volumes" -v /opt/Volume/a:/opt/a -v /opt/Volume/b:/opt/b centos:6.9 /bin/bash
[root@3a5b7e9c3714 /]#
此处不能直接退出,否则容器会直接关闭
ctrl+p,q
  • 使用数据卷容器
[root@wldev08 ~]# docker container ls 
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                  NAMES
3895eac17824        nginx               "nginx -g 'daemon of…"   About an hour ago   Up About an hour    0.0.0.0:8086->80/tcp   nginx_8086

8b38eef11715        nginx               "nginx -g 'daemon of…"   About an hour ago   Up About an hour    0.0.0.0:8085->80/tcp   nginx_8085

ce66cc9aebda        centos:6.9          "/bin/bash"              About an hour ago   Up About an hour                           nginx_volumes
[root@wldev08 ~]#
[root@wldev08 ~]# docker container exec -it nginx_8085 /bin/bash
root@8b38eef11715:/# ls /opt/a/
a.txt
root@8b38eef11715:/# ls /opt/b/
b.txt

作用: 在集中管理集群中,大批量的容器都需要挂载相同的多个数据卷时,可以采用数卷容器进行统一管理

7. 构建本地yum源

7.1 安装vsftpd服务

[root@wldev08 ~]# yum -y install vsftpd
[root@wldev08 ~]# rpm -qa |grep vsftpd
vsftpd-3.0.2-25.el7.x86_64
[root@wldev08 ~]# systemctl enable vsftpd
Created symlink from /etc/systemd/system/multi-user.target.wants/vsftpd.service to /usr/lib/systemd/system/vsftpd.service.
[root@wldev08 ~]# systemctl start vsftpd
[root@wldev08 ~]# ps -ef |grep vsftpd
root     28778     1  0 11:14 ?        00:00:00 /usr/sbin/vsftpd /etc/vsftpd/vsftpd.conf
root     28780 28190  0 11:14 pts/0    00:00:00 grep --color=auto vsftpd
[root@wldev08 ~]#

7.2 配置Yum仓库

[root@wldev08 ~]# mkdir -p /var/ftp/centos7.3
[root@wldev08 ~]# mkdir -p /var/ftp/centos6.8
[root@wldev08 ~]# cat >/etc/yum
yum/         yum.conf     yum.repos.d/ 
[root@wldev08 ~]# cat >/etc/yum.repos.d/ftp_6.repo < [ftp]
> name=ftpbase
> baseurl=ftp://172.17.0.1/centos6.8
> enable=1
> gpgcheck=0
> EOF
[root@wldev08 ~]# 
[root@wldev08 ~]# cat >/etc/yum.repos.d/ftp_7.repo <

7.3 ssh登录容器

[root@wldev08 ~]# docker attach ce66cc9aebda
[root@ce66cc9aebda /]# yum clean all
[root@ce66cc9aebda /]# yum -y install openssh*
[root@ce66cc9aebda /]# service sshd start
Generating SSH2 RSA host key:                              [  OK  ]
Generating SSH1 RSA host key:                              [  OK  ]
Generating SSH2 DSA host key:                              [  OK  ]
Starting sshd:                                             [  OK  ]

设置密码后,即可使用ssh登录容器

8. 镜像制作

  • 基础镜像容器启动
[root@wldev08 ~]# docker container ls -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                   PORTS                  NAMES
3895eac17824        nginx               "nginx -g 'daemon of…"   20 hours ago        Exited (0) 2 hours ago                          nginx_8086
8b38eef11715        nginx               "nginx -g 'daemon of…"   20 hours ago        Up 20 hours              0.0.0.0:8085->80/tcp   nginx_8085
ce66cc9aebda        centos:6.9          "/bin/bash"              21 hours ago        Up 21 hours                                     nginx_volumes
[root@wldev08 ~]# docker run -it --name="centos_v1" centos:6.9
[root@d92900143bdb /]# 
  • 安装所需软件包
mv /etc/yum.repos.d/*.repo /tmp
echo -e "[ftp]\nname=ftp\nbaseurl=ftp://172.17.0.1/centos6.9\ngpgcheck=0">/etc/yum.repos.d/ftp.repo
yum makecache fast && yum install openssh-server -y
/etc/init.d/sshd start     ----->重要:ssh第一次启动时,需要生成秘钥,生成pam验证配置文件
/etc/init.d/sshd stop
echo "123456" | passwd --stdin 
  • 镜像的制作
[root@wldev08 ~]# docker container ls -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                   PORTS                  NAMES
d92900143bdb        centos:6.9          "/bin/bash"              3 minutes ago       Up 3 minutes                                    centos_v1
3895eac17824        nginx               "nginx -g 'daemon of…"   20 hours ago        Exited (0) 2 hours ago                          nginx_8086
8b38eef11715        nginx               "nginx -g 'daemon of…"   20 hours ago        Up 20 hours              0.0.0.0:8085->80/tcp   nginx_8085
ce66cc9aebda        centos:6.9          "/bin/bash"              21 hours ago        Up 21 hours                                     nginx_volumes
[root@wldev08 ~]# docker commit nginx_volumes nginx/centos6.9_ssh:v1
sha256:535b7d4330f32e90623e642bdb2a8b40777e794832a8dde422eb7d2a30a673b8
[root@wldev08 ~]# 
  • 基于新镜像启动容器实现,centos6.9+sshd的功能
[root@wldev08 ~]# docker image ls
REPOSITORY            TAG                 IMAGE ID            CREATED             SIZE
nginx/centos6.9_ssh   v1                  535b7d4330f3        2 minutes ago       456MB
nginx                 latest              540a289bab6c        9 days ago          126MB
nginx                 v2                  540a289bab6c        9 days ago          126MB
nginx                 1.14                295c7be07902        7 months ago        109MB
centos                6.9                 2199b8eb8390        7 months ago        195MB
centos                7.5.1804            cf49811e3cdb        7 months ago        200MB
[root@wldev08 ~]# docker container run -d --name=sshd_222 -p 222:22 535b7d4330f3 /usr/sbin/sshd -D
bc293805b8e2ce8196f81680803caf138c6053b8b6c9995776b2ce7af31c53c1
[root@wldev08 ~]# 
[root@wldev08 ~]# docker container ls -a
CONTAINER ID        IMAGE               COMMAND               CREATED              STATUS              PORTS                 NAMES
bc293805b8e2        535b7d4330f3        "/usr/sbin/sshd -D"   About a minute ago   Up About a minute   0.0.0.0:222->22/tcp   sshd_222

[root@wldev08 ~]# ssh 172.17.0.2
[email protected]'s password: 
Last login: Fri Nov  1 08:09:46 2019 from 172.17.0.1
[root@bc293805b8e2 ~]# ifconfig


9. 构建LAMP镜像

  • 创建数据卷
[root@wldev08 ~]# mkdir -p /opt/vol/mysql /opt/vol/html
[root@wldev08 ~]# docker run -it --name="centos_lamp" -v /opt/vol/mysql:/var/lib/mysql -v /opt/vol/html:/var/www/html centos:6.9

  • 基础镜像
[root@wldev08 ~]# docker run -it --name="centos_lamp" centos:6.9
[root@c6de65f40047 /]# 
  • 优化yum源,并安装相关软件
[root@c6de65f40047 /]# cd /etc/yum.repos.d/
[root@c6de65f40047 yum.repos.d]# ls
CentOS-Base.repo  CentOS-Debuginfo.repo  CentOS-Media.repo  CentOS-Vault.repo  CentOS-fasttrack.repo
[root@c6de65f40047 yum.repos.d]# ls      
CentOS-Base.repo  CentOS-Debuginfo.repo  CentOS-Media.repo  CentOS-Vault.repo  CentOS-fasttrack.repo
[root@c6de65f40047 yum.repos.d]# mv *.repo /tmp/
[root@c6de65f40047 yum.repos.d]# ls
[root@c6de65f40047 yum.repos.d]# echo -e "[ftp]\nname=ftp\nbaseurl=ftp://172.17.0.1/centos6.8\ngpgcheck=0">/etc/yum.repos.d/ftp.repo
[root@c6de65f40047 yum.repos.d]# yum makecache fast
[root@55e135461eb5 yum.repos.d]# yum -y install vim
[root@55e135461eb5 ~]# yum -y install openssh-server httpd mysql-server php php-mysql
[root@55e135461eb5 ~]# /etc/init.d/sshd start
Generating SSH2 RSA host key:                              [  OK  ]
Generating SSH1 RSA host key:                              [  OK  ]
Generating SSH2 DSA host key:                              [  OK  ]
Starting sshd:                                             [  OK  ]
[root@55e135461eb5 ~]#
[root@55e135461eb5 ~]# echo "123456" |passwd root --stdin
Changing password for user root.
passwd: all authentication tokens updated successfully.
[root@55e135461eb5 ~]# 
[root@55e135461eb5 ~]# /etc/init.d/mysqld start
Initializing MySQL database:  Installing MySQL system tables...
OK
Filling help tables...
OK

To start mysqld at boot time you have to copy
support-files/mysql.server to the right place for your system

PLEASE REMEMBER TO SET A PASSWORD FOR THE MySQL root USER !
To do so, start the server, then issue the following commands:

/usr/bin/mysqladmin -u root password 'new-password'
/usr/bin/mysqladmin -u root -h 55e135461eb5 password 'new-password'

Alternatively you can run:
/usr/bin/mysql_secure_installation

which will also give you the option of removing the test
databases and anonymous user created by default.  This is
strongly recommended for production servers.

See the manual for more instructions.

You can start the MySQL daemon with:
cd /usr ; /usr/bin/mysqld_safe &

You can test the MySQL daemon with mysql-test-run.pl
cd /usr/mysql-test ; perl mysql-test-run.pl

Please report any problems with the /usr/bin/mysqlbug script!

                                                           [  OK  ]
Starting mysqld:                                           [  OK  ]
[root@55e135461eb5 ~]#

宿主机数据

[root@wldev08 ftp]# cd /opt/vol/mysql/
[root@wldev08 mysql]# ls
ibdata1  ib_logfile0  ib_logfile1  mysql  mysql.sock  test
[root@wldev08 mysql]# 
mysql> grant all on *.* to  root@'%' identified by '123456';
Query OK, 0 rows affected (0.00 sec)
//授权远程用户登录
mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

mysql> grant all on *.* to discuz@'%' identified by '123456';
Query OK, 0 rows affected (0.00 sec)

mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

mysql> create database discuz charset utf8;
Query OK, 1 row affected (0.00 sec)

mysql> 

[root@55e135461eb5 opt]# /etc/init.d/httpd start
Starting httpd: httpd: Could not reliably determine the server's fully qualified domain name, using 172.17.0.2 for ServerName
                                                           [  OK  ]
[root@55e135461eb5 opt]#

9.1 基于(Centos6.9)LAMP制作基础镜像

[root@wldev08 ~]# docker commit 55e135461eb5 centos_lamp:v1
sha256:24b3fcc3f0b0eb2082c757991f5f7724746f602383dd9b5cbbe783cbfa1763ee
[root@wldev08 ~]# 
  • 根据第一版,重新启动新容器并暴露端口
[root@wldev08 ~]# docker run -it --name="centos_lamp_v2" -v /opt/vol/mysql:/var/lib/mysql -v /opt/vol/html:/var/www/html -p 8080:80 24b3fcc3f0b0
[root@f39d28141011 /]#
[root@f39d28141011 /]# /etc/init.d/mysqld start
Starting mysqld:                                           [  OK  ]
[root@f39d28141011 /]# /etc/init.d/httpd start
Starting httpd: httpd: Could not reliably determine the server's fully qualified domain name, using 172.17.0.2 for ServerName
                                                           [  OK  ]
[root@f39d28141011 /]#

若无故障,lamp环境搭建完成,下载discuz安装

  • 设置启动脚本
[root@wldev08 html]# vim start_http.sh
[root@wldev08 html]# chmod +x start_http.sh 
[root@wldev08 html]# cat start_http.sh 
#!/bin/bash
/etc/init.d/mysqld  start
/etc/init.d/httpd   start
/usr/sbin/sshd -D
[root@wldev08 html]# 
// 使进程夯在后台
[root@wldev08 html]# docker container run -d --name="yun_centos6.9_lamp" -v /opt/vol/mysql:/var/lib/mysql -v /opt/vol/html:/var/www/html -p 2222:22 -p 8881:80 -p 3306:3306 24b3fcc3f0b0  /var/www/html/start_http.sh
42f4c32dda1bf64f0b6b0a075d76fcdc635e127019d019cdf35dd2e66b68ddc4
[root@wldev08 html]# 

10. 镜像制作dockerfile

10.1 dockerfile常用指令

FROM: 基础镜像
	Syntax:
	FROM	centos:6.9
	FROM 	centos@2199b8eb8390
		
RUN:  构建镜像过程中运行的命令
	Syntax:
	RUN	 mv /etc/yum.repos.d/*.repo /tmp && echo -e "[ftp]\nname=ftp\nbaseurl=ftp://172.17.0.1/centos6.9\ngpgcheck
=0">/etc/yum.repos.d/ftp.repo && yum makecache fast && yum install openssh-server -y
	RUN	["mysqld","--initialize-insecure","--user=mysql"  ,"--basedir=/usr/local/mysql","--datadir=/data/mysql/data"] 

EXPOSE: 向外暴露的端口,多个写多行即可 
	Syntax:
		EXPOSE  22	
CMD    使用镜像启动容器时运行的命令
	Syntax:
	CMD	["/usr/sbin/sshd","-D"]

10.2 dockerfile基本制作

[root@wldev08 ~]# mkdir -p /opt/dockfile/centos6.9_ssh
[root@wldev08 ~]# cat /opt/dockfile/centos6.9_ssh/dokerfile 
#Centos:
#	6.9-ssh:v1.0
#Author:
#	admin
FROM centos:6.9
RUN  mv /etc/yum.repos.d/*.repo /tmp && echo -e "[ftp]\nname=ftp\nbaseurl=ftp://172.17.0.1/centos6.9\ngpgcheck
=0">/etc/yum.repos.d/ftp.repo && yum makecache fast && yum install openssh-server -y
RUN  /etc/init.d/sshd start && /etc/init.d/sshd stop && echo "123456" | passwd root --stdin
EXPOSE 22
CMD ["/usr/sbin/sshd","-D"]
[root@wldev08 ~]#
[root@wldev08 centos6.9_ssh]# docker image build -t "centos6.9-ssh:v1" ./
Sending build context to Docker daemon  2.048kB
Step 1/5 : FROM centos:6.9
 ---> 2199b8eb8390
Step 2/5 : RUN  mv /etc/yum.repos.d/*.repo /tmp && echo -e "[ftp]\nname=ftp\nbaseurl=ftp://172.17.0.1/centos6.9\ngpgcheck=0">/etc/yum.repos.d/ftp.repo && yum makecache fast && yum install openssh-server -y
 ---> Running in 84ecfcb00882
Loaded plugins: fastestmirror, ovl
Metadata Cache Created
Loaded plugins: fastestmirror, ovl
...................................................
 ---> Running in 16dec8e29257
Generating SSH2 RSA host key: [  OK  ]
Generating SSH1 RSA host key: [  OK  ]
Generating SSH2 DSA host key: [  OK  ]
Starting sshd: [  OK  ]
Stopping sshd: [  OK  ]
Changing password for user root.
passwd: all authentication tokens updated successfully.
Removing intermediate container 16dec8e29257
 ---> 31622833c3bf
Step 4/5 : EXPOSE 22
 ---> Running in eaa76293e54a  // 临时容器id
Removing intermediate container eaa76293e54a
 ---> 31b08282d3cc
Step 5/5 : CMD ["/usr/sbin/sshd","-D"]
 ---> Running in 4db2625c9f41
Removing intermediate container 4db2625c9f41
 ---> e26c206c8210
Successfully built e26c206c8210
Successfully tagged centos6.9-ssh:v1
[root@wldev08 centos6.9_ssh]#
[root@wldev08 centos6.9_ssh]# docker image ls -a
REPOSITORY            TAG                 IMAGE ID            CREATED             SIZE
centos6.9-ssh         v1                  e26c206c8210        6 minutes ago       331MB
                              31b08282d3cc        6 minutes ago       331MB
                              31622833c3bf        6 minutes ago       331MB
                              dd1e0d898f3c        6 minutes ago       331MB
centos_lamp           v1                  24b3fcc3f0b0        4 days ago          389MB
nginx/centos6.9_ssh   v1                  535b7d4330f3        7 days ago          456MB
nginx                 latest              540a289bab6c        2 weeks ago         126MB
nginx                 v2                  540a289bab6c        2 weeks ago         126MB
nginx                 1.14                295c7be07902        7 months ago        109MB
centos                6.9                 2199b8eb8390        7 months ago        195MB
centos                7.5.1804            cf49811e3cdb        7 months ago        200MB
[root@wldev08 centos6.9_ssh]#
[root@wldev08 centos6.9_ssh]# docker container run -d e26c206c8210
4f7e6a52a370f302916b776760d9150d55cca6e54070ee065d7f396e3dca4721
[root@wldev08 centos6.9_ssh]# 
[root@wldev08 centos6.9_ssh]# docker container ls -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                  PORTS                                                                NAMES
4f7e6a52a370        e26c206c8210        "/usr/sbin/sshd -D"      59 seconds ago      Up 58 seconds           22/tcp                                                               eloquent_newton
8600ebab2d07        24b3fcc3f0b0        "/var/www/html/start…"   4 days ago          Up 4 days               0.0.0.0:3306->3306/tcp, 0.0.0.0:2222->22/tcp, 0.0.0.0:8881->80/tcp   yun_centos6.9_lamp
f39d28141011        24b3fcc3f0b0        "/bin/bash"              4 days ago          Exited (0) 4 days ago                                                                        centos_lamp_v2
55e135461eb5        centos:6.9          "/bin/bash"              4 days ago          Exited (0) 4 days ago                                                                        centos_lamp
[root@wldev08 centos6.9_ssh]# docker container inspect 4f7e6a52a370
[
    {
        "Id": "4f7e6a52a370f302916b776760d9150d55cca6e54070ee065d7f396e3dca4721",
        "Created": "2019-11-08T09:38:09.433485111Z",
        "Path": "/usr/sbin/sshd",
        "Args": [
            "-D"
        ],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 8234,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2019-11-08T09:38:09.73984047Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:e26c206c82107526f697c7eb4983d94b85847cf8cd7eff7eed04cfe1d835bcfa",
        "ResolvConfPath": "/var/lib/docker/containers/4f7e6a52a370f302916b776760d9150d55cca6e54070ee065d7f396e3dca4721/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/4f7e6a52a370f302916b776760d9150d55cca6e54070ee065d7f396e3dca4721/hostname",
        "HostsPath": "/var/lib/docker/containers/4f7e6a52a370f302916b776760d9150d55cca6e54070ee065d7f396e3dca4721/hosts",
        "LogPath": "/var/lib/docker/containers/4f7e6a52a370f302916b776760d9150d55cca6e54070ee065d7f396e3dca4721/4f7e6a52a370f302916b776760d9150d55cca6e54070ee065d7f396e3dca4721-json.log",
        "Name": "/eloquent_newton",
        "RestartCount": 0,
        "Driver": "overlay2",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "",
        "ExecIDs": null,
        "HostConfig": {
            "Binds": null,
            "ContainerIDFile": "",
            "LogConfig": {
                "Type": "json-file",
                "Config": {}
            },
            "NetworkMode": "default",
            "PortBindings": {},
            "RestartPolicy": {
                "Name": "no",
                "MaximumRetryCount": 0
            },
            "AutoRemove": false,
            "VolumeDriver": "",
            "VolumesFrom": null,
            "CapAdd": null,
            "CapDrop": null,
            "Capabilities": null,
            "Dns": [],
            "DnsOptions": [],
            "DnsSearch": [],
            "ExtraHosts": null,
            "GroupAdd": null,
            "IpcMode": "private",
            "Cgroup": "",
            "Links": null,
            "OomScoreAdj": 0,
            "PidMode": "",
            "Privileged": false,
            "PublishAllPorts": false,
            "ReadonlyRootfs": false,
            "SecurityOpt": null,
            "UTSMode": "",
            "UsernsMode": "",
            "ShmSize": 67108864,
            "Runtime": "runc",
            "ConsoleSize": [
                0,
                0
            ],
            "Isolation": "",
            "CpuShares": 0,
            "Memory": 0,
            "NanoCpus": 0,
            "CgroupParent": "",
            "BlkioWeight": 0,
            "BlkioWeightDevice": [],
            "BlkioDeviceReadBps": null,
            "BlkioDeviceWriteBps": null,
            "BlkioDeviceReadIOps": null,
            "BlkioDeviceWriteIOps": null,
            "CpuPeriod": 0,
            "CpuQuota": 0,
            "CpuRealtimePeriod": 0,
            "CpuRealtimeRuntime": 0,
            "CpusetCpus": "",
            "CpusetMems": "",
            "Devices": [],
            "DeviceCgroupRules": null,
            "DeviceRequests": null,
            "KernelMemory": 0,
            "KernelMemoryTCP": 0,
            "MemoryReservation": 0,
            "MemorySwap": 0,
            "MemorySwappiness": null,
            "OomKillDisable": false,
            "PidsLimit": null,
            "Ulimits": null,
            "CpuCount": 0,
            "CpuPercent": 0,
            "IOMaximumIOps": 0,
            "IOMaximumBandwidth": 0,
            "MaskedPaths": [
                "/proc/asound",
                "/proc/acpi",
                "/proc/kcore",
                "/proc/keys",
                "/proc/latency_stats",
                "/proc/timer_list",
                "/proc/timer_stats",
                "/proc/sched_debug",
                "/proc/scsi",
                "/sys/firmware"
            ],
            "ReadonlyPaths": [
                "/proc/bus",
                "/proc/fs",
                "/proc/irq",
                "/proc/sys",
                "/proc/sysrq-trigger"
            ]
        },
        "GraphDriver": {
            "Data": {
                "LowerDir": "/var/lib/docker/overlay2/262582bc27a759d95da942142eb2804eec64c63fd1c23a6e37fee5f2d19c31e4-init/diff:/var/lib/docker/overlay2/952d7ddd5fca27dd4ff41dcd59e964860688b53612e484797165083a030608a1/diff:/var/lib/docker/overlay2/2e846fb0146eef559a1336b1755b06de7dd0fc4bf18c106fdcfad84b14eece9e/diff:/var/lib/docker/overlay2/c363a2d7ff9fed401a2d33fd59471b6d33279b8f49a0c7196eeec8b83fccea87/diff",
                "MergedDir": "/var/lib/docker/overlay2/262582bc27a759d95da942142eb2804eec64c63fd1c23a6e37fee5f2d19c31e4/merged",
                "UpperDir": "/var/lib/docker/overlay2/262582bc27a759d95da942142eb2804eec64c63fd1c23a6e37fee5f2d19c31e4/diff",
                "WorkDir": "/var/lib/docker/overlay2/262582bc27a759d95da942142eb2804eec64c63fd1c23a6e37fee5f2d19c31e4/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "4f7e6a52a370",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "ExposedPorts": {
                "22/tcp": {}
            },
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
            ],
            "Cmd": [
                "/usr/sbin/sshd",
                "-D"
            ],
            "Image": "e26c206c8210",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": {
                "build-date": "20170406",
                "license": "GPLv2",
                "name": "CentOS Base Image",
                "vendor": "CentOS"
            }
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "736f85e15b1af55e65c9b52e5b76a1edc23534a02b50c136e645156deca3c1df",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {
                "22/tcp": null
            },
            "SandboxKey": "/var/run/docker/netns/736f85e15b1a",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "267e102234c2bc9403a688a844db33a1821a85fb14bd28f033943a6502d54595",
            "Gateway": "172.17.0.1",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "172.17.0.3",
            "IPPrefixLen": 16,
            "IPv6Gateway": "",
            "MacAddress": "02:42:ac:11:00:03",
            "Networks": {
                "bridge": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "NetworkID": "d40ea7b05147cabc7e33af3ea166e8b21b2167037c69fda86fa9e62cd0e3adc1",
                    "EndpointID": "267e102234c2bc9403a688a844db33a1821a85fb14bd28f033943a6502d54595",
                    "Gateway": "172.17.0.1",
                    "IPAddress": "172.17.0.3",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:ac:11:00:03",
                    "DriverOpts": null
                }
            }
        }
    }
]
[root@wldev08 centos6.9_ssh]# ssh 172.17.0.3
The authenticity of host '172.17.0.3 (172.17.0.3)' can't be established.
RSA key fingerprint is f4:c0:8f:d6:6d:06:8b:11:f8:6b:76:b1:36:07:25:60.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '172.17.0.3' (RSA) to the list of known hosts.
[email protected]'s password: 
[root@4f7e6a52a370 ~]# 

10.3 dockerfile 构建LAMP基础环境镜像

[root@wldev08 ~]# mkdir -p /opt/dockerfile/lamp
[root@wldev08 lamp]# cat dockerfile 
#Centos6.9_ssh_Lamp
FROM centos:6.9
RUN mv /etc/yum.repos.d/*.repo /tmp && echo -e "[ftp]\nname=ftp\nbaseurl=ftp://172.17.0.1/centos6.9\ngpgcheck=0">/etc/yum.repos.d/ftp.repo && yum makecache fast && yum install openssh-server httpd mysql mysql-server php php-mysql -y
RUN /etc/init.d/sshd start && echo "123456" |passwd root --stdin --stdin && /etc/init.d/mysqld start && /etc/init.d/httpd startRUN mysql -e "grant all on *.* to root@'%' identified by "123";grant all on *.* to discuz@'%' identified by "123";create database discuz charset utf8;"
COPY index.php /var/www/html/ init.sh /
ADD bbs.tar.gz /var/www/html/
##ADD对压缩文件有更好的支持,自动解压。.zip的则解压不了,只能是tar相关的
EXPOSE 22
EXPOSE 80
EXPOSE 3306
CMD ["/bin/bash","init.sh"]
[root@wldev08 lamp]# cat index.php 

[root@wldev08 lamp]# cat start_http.sh 
#!/bin/bash
/etc/init.d/mysqld start
/etc/init.d/httpd  start
/usr/sbin/sshd -D
[root@wldev08 lamp]#
[root@wldev08 lamp]# ll
总用量 407536
-rw-r--r-- 1 root root 417304064 11月 11 10:59 bbs.tar.gz
-rw-r--r-- 1 root root       773 11月 11 11:25 dockerfile
-rw-r--r-- 1 root root        20 11月 11 10:42 index.php
-rwxr-xr-x 1 root root        80 11月 11 11:24 start_http.sh
[root@wldev08 lamp]# docker build -t "centos6.9_ssh_lamp_dicuz" ./
Complete!
Removing intermediate container 5c9387985f50
 ---> ce3602115a7e
Step 3/9 : RUN /etc/init.d/sshd start && echo "123456" | passwd root --stdin /etc/init.d/mysqld start && /etc/init.d/httpd startRUN mysql -e "grant all on *.* to root@'%' identified by "123";grant all on *.* to discuz@'%' identified by "123";create database discuz charset utf8;"
 ---> Running in d319ce8d9426
Generating SSH2 RSA host key: [  OK  ]
Generating SSH1 RSA host key: [  OK  ]
Generating SSH2 DSA host key: [  OK  ]
Starting sshd: [  OK  ]
passwd: Only one user name may be specified.
The command '/bin/sh -c /etc/init.d/sshd start && echo "123456" | passwd root --stdin && /etc/init.d/mysqld start && /etc/init.d/httpd startRUN mysql -e "grant all on *.* to root@'%' identified by "123";grant all on *.* to discuz@'%' identified by "123";create database discuz charset utf8;"' returned a non-zero code: 253
[root@wldev08 lamp]#
故障调试,进入到上一步临时容器ID
[root@wldev08 lamp]# docker run -it --rm ce3602115a7e /bin/bash
[root@ffbb468f0b27 /]# 
[root@ffbb468f0b27 /]# echo "123456" |passwd root --stdin
Changing password for user root.
passwd: all authentication tokens updated successfully.
[root@ffbb468f0b27 /]# 
因为是脚本找不到,所以更改下脚本
[root@wldev08 lamp]# mv start_http.sh init.sh
Starting mysqld:  [  OK  ]
Starting httpd: httpd: Could not reliably determine the server's fully qualified domain name, using 172.17.0.3 for ServerName
[  OK  ]
Removing intermediate container 7ff4ddc1f57f
 ---> cef19e22729b
Step 4/10 : RUN mysql -e "grant all on *.* to root@'%' identified by "123";grant all on *.* to discuz@'%' identified by "123";create database discuz charset utf8;"
 ---> Running in b5157be59851
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
The command '/bin/sh -c mysql -e "grant all on *.* to root@'%' identified by "123";grant all on *.* to discuz@'%' identified by "123";create database discuz charset utf8;"' returned a non-zero code: 1
继续排错,将mysql在执行之前操作
[root@wldev08 lamp]# cat init.sh 
#!/bin/bash
/etc/init.d/mysqld start
mysql -e "grant all on *.* to root@'%' identified by "123";grant all on *.* to discuz@'%' identified by "123";create database discuz charset utf8;"
/etc/init.d/httpd  start
/usr/sbin/sshd -D
[root@wldev08 lamp]# docker build -t "centos6.9_ssh_lamp_dicuz" ./
Sending build context to Docker daemon  417.3MB
Step 1/10 : FROM centos:6.9
 ---> 2199b8eb8390
Step 2/10 : RUN mv /etc/yum.repos.d/*.repo /tmp && echo -e "[ftp]\nname=ftp\nbaseurl=ftp://172.17.0.1/centos6.9\ngpgcheck=0">/etc/yum.repos.d/ftp.repo && yum makecache fast && yum install openssh-server httpd mysql mysql-server php php-mysql -y
 ---> Using cache
 ---> ce3602115a7e
Step 3/10 : RUN /etc/init.d/sshd start && echo "123456" |passwd root --stdin && /etc/init.d/mysqld start && /etc/init.d/httpd start
 ---> Using cache
 ---> cef19e22729b
Step 4/10 : COPY index.php /var/www/html/
 ---> 4efd0c6130d3
Step 5/10 : COPY init.sh /
 ---> 17ae4339750a
Step 6/10 : ADD bbs.tar.gz /var/www/html/
 ---> 2112feca8964
Step 7/10 : EXPOSE 22
 ---> Running in 174ea84fa7de
Removing intermediate container 174ea84fa7de
 ---> 118e5dc2f6de
Step 8/10 : EXPOSE 80
 ---> Running in 7d2b6e53ab60
Removing intermediate container 7d2b6e53ab60
 ---> 03b3267f96f3
Step 9/10 : EXPOSE 3306
 ---> Running in b7a9c96880ca
Removing intermediate container b7a9c96880ca
 ---> d14cfb820018
Step 10/10 : CMD ["/bin/bash","init.sh"]
 ---> Running in 3f17db9c1d0a
Removing intermediate container 3f17db9c1d0a
 ---> 87baa0818181
Successfully built 87baa0818181
Successfully tagged centos6.9_ssh_lamp_dicuz:latest
[root@wldev08 lamp]# 
[root@wldev08 lamp]# docker image ls -a
REPOSITORY                 TAG                 IMAGE ID            CREATED             SIZE
centos6.9_ssh_lamp_dicuz   latest              87baa0818181        2 minutes ago       854MB
[root@wldev08 lamp]# docker container run -d -p 80 -p 22 -p 3306 87baa0818181
67fc09e82dddbc43f8db7ff9df8d3e674444e5d363d980639577652ffc0c79d4
[root@wldev08 lamp]# docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                         PORTS                                                                   NAMES
67fc09e82ddd        87baa0818181        "/bin/bash init.sh"      10 seconds ago      Up 8 seconds                   0.0.0.0:32770->22/tcp, 0.0.0.0:32769->80/tcp, 0.0.0.0:32768->3306/tcp   bold_engelbart

10.4 copy命令和add命令解释

COPY命令: 

Syntax:
	  ...   
	  
		从dockerfile所在目录,拷贝目标文件到容器的制定目录下。
		可以支持统配符,如果拷贝的是目录,只拷贝目录下的子文件子目录。
		cp oldguo/* 		
ADD    	
Syntax:
	  ...   
	  url        

	  比COPY命令多的功能是,可以自动解压.tar*的软件包到目标目录下
	  可以指定源文件为URL地

VOLUME [""]
    ...  
    /home/data  /home/data
    使容器中的一个目录具有持久化存储数据的功能,该目录可以被容器本身使用,也可以共享给其他容器使用

WORKDIR 

ENV  设定变量 
ENV CODEDIR /var/www/html/
ENV DATADIR /data/mysql/data
ADD bbs.tar.gz ${CODEDIR}
VOLUME ["${CODEDIR}","${DATADIR}"]


ENTRYPOINT

#CMD ["/bin/bash","/init.sh"]
ENTRYPOINT ["/bin/bash","/init.sh"]

说明: 
ENTRYPOINT 可以方式,在启动容器时,第一进程被手工输入的命令替换掉,防止容器秒起秒关

11. 构建私有registry

registry是一个服务

  • 方法一
[root@wldev08 lamp]# docker run -d -p 5000:5000 --restart=always --name registry -v /opt/registry:/var/lib/registry registry

always:docker重启后,容器跟着启动

[root@wldev08 lamp]# docker run -d -p 8000:80 --restart=always --name="nginx_v1" nginx
Unable to find image 'nginx:latest' locally
latest: Pulling from library/nginx
8d691f585fa8: Pull complete 
5b07f4e08ad0: Pull complete 
abc291867bca: Pull complete 
Digest: sha256:922c815aa4df050d4df476e92daed4231f466acc8ee90e0e774951b0fd7195a4
Status: Downloaded newer image for nginx:latest
6eb16a28fd91270054b005f0348a573b07b2ae4de9984575bc9f4e94a5e06198
[root@wldev08 lamp]# docker container ls -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                     PORTS                  NAMES
6eb16a28fd91        nginx               "nginx -g 'daemon of…"   55 seconds ago      Up 55 seconds              0.0.0.0:8000->80/tcp   nginx_v1
cba155a26869        3c541955981e        "/bin/bash init.sh"      4 hours ago         Exited (137) 3 hours ago                          busy_hugle
8600ebab2d07        24b3fcc3f0b0        "/var/www/html/start…"   7 days ago          Exited (137) 3 hours ago                          yun_centos6.9_lamp
[root@wldev08 lamp]# systemctl restart docker
[root@wldev08 lamp]# docker container ls -a
CONTAINER ID        IMAGE               COMMAND                  CREATED              STATUS                     PORTS                  NAMES
6eb16a28fd91        nginx               "nginx -g 'daemon of…"   About a minute ago   Up 2 seconds               0.0.0.0:8000->80/tcp   nginx_v1
cba155a26869        3c541955981e        "/bin/bash init.sh"      4 hours ago          Exited (137) 3 hours ago                          busy_hugle
8600ebab2d07        24b3fcc3f0b0        "/var/www/html/start…"   7 days ago           Exited (137) 3 hours ago                          yun_centos6.9_lamp
[root@wldev08 lamp]#
。。。。。。。。。。。。。。

  • 方法二
[root@wldev08 lamp]# docker run -d -p 5000:5000 --restart=always --name registry -v /opt/registry:/var/lib/registry registry
Unable to find image 'registry:latest' locally
latest: Pulling from library/registry
c87736221ed0: Pull complete 
1cc8e0bb44df: Pull complete 
54d33bcb37f5: Pull complete 
e8afc091c171: Pull complete 
b4541f6d3db6: Pull complete 
Digest: sha256:8004747f1e8cd820a148fb7499d71a76d45ff66bac6a29129bfdbfdc0154d146
Status: Downloaded newer image for registry:latest
850655fd73a2cba62a211754c79a6aa8f06696636f00d55e154f8c01b3661639
[root@wldev08 lamp]# docker container ls 
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                    NAMES
850655fd73a2        registry            "/entrypoint.sh /etc…"   54 seconds ago      Up 53 seconds       0.0.0.0:5000->5000/tcp   registry
[root@wldev08 lamp]# 
[root@wldev08 lamp]# cat /etc/docker/daemon.json 
{
  "registry-mirrors": ["https://b3z80jv9.mirror.aliyuncs.com"],
  "insecure-registries": ["100.39.3.49:5000"] 
}
[root@wldev08 lamp]# 

打标签
[root@wldev08 lamp]# docker tag nginx:latest 100.39.3.49:5000/project/nginx:v1
[root@wldev08 lamp]# 
nginx:latest  源镜像名称  
100.39.3.49仓库地址
project 项目名称
nginx:v1  新tag名称
[root@wldev08 lamp]# docker image ls
REPOSITORY                       TAG                 IMAGE ID            CREATED             SIZE
centos_lamp                      v1                  15bfd3eb90e3        2 hours ago         854MB
100.39.3.49:5000/project/nginx   v1                  540a289bab6c        2 weeks ago         126MB
nginx                            latest              540a289bab6c        2 weeks ago         126MB
centos                           6.9                 2199b8eb8390        8 months ago        195MB
registry                         latest              f32a97de94e1        8 months ago        25.8MB
[root@wldev08 lamp]# 

向仓库推镜像
[root@wldev08 lamp]# docker push 100.39.3.49:5000/project/nginx:v1
The push refers to repository [100.39.3.49:5000/project/nginx]
a89b8f05da3a: Pushed 
6eaad811af02: Pushed 
b67d19e65ef6: Pushed 
v1: digest: sha256:f56b43e9913cef097f246d65119df4eda1d61670f7f2ab720831a01f66f6ff9c size: 948
[root@wldev08 lamp]#
[root@wldev08 lamp]# curl localhost:5000/v2/_catalog
{"repositories":["project/nginx"]}
[root@wldev08 lamp]#

12. docker registry验证

[root@wldev08 ~]# docker container ls -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                    NAMES
850655fd73a2        registry            "/entrypoint.sh /etc…"   2 days ago          Up 3 hours          0.0.0.0:5000->5000/tcp   registry
[root@wldev08 ~]#

[root@wldev07 ~]# cat /etc/docker/daemon.json 
{
  "registry-mirrors": ["https://b3z80jv9.mirror.aliyuncs.com"],
  "insecure-registries": ["100.39.3.49:5000"]  
}
[root@wldev07 ~]# systemctl restart docker
[root@wldev07 ~]# docker image ls -a
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
[root@wldev07 ~]# docker container ls -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
[root@wldev07 ~]# 
[root@wldev07 ~]# docker pull 100.39.3.49:5000/project/nginx:v1
v1: Pulling from project/nginx
8d691f585fa8: Pull complete 
5b07f4e08ad0: Pull complete 
abc291867bca: Pull complete 
Digest: sha256:f56b43e9913cef097f246d65119df4eda1d61670f7f2ab720831a01f66f6ff9c
Status: Downloaded newer image for 100.39.3.49:5000/project/nginx:v1
100.39.3.49:5000/project/nginx:v1
[root@wldev07 ~]# docker image ls
REPOSITORY                       TAG                 IMAGE ID            CREATED             SIZE
100.39.3.49:5000/project/nginx   v1                  540a289bab6c        3 weeks ago         126MB
[root@wldev07 ~]#

12.1 registry加密验证

  • 配置验证身份
[root@wldev08 ~]# yum -y install httpd-tools
[root@wldev08 ~]# mkdir /opt/registry-auth -p
[root@wldev08 ~]# htpasswd -Bbn test 123456 >/opt/registry-auth/htpasswd
  • 启动一个带有秘钥的容器
// 启动前先停掉不带秘钥的容器
[root@wldev08 ~]# docker run -d -p 5000:5000 -v /opt/registry-auth/:/auth/ -v /opt/registry:/var/lib/registry --name register-auth -e "REGISTRY_AUTH=htpasswd" -e "REGISTRY_AUTH_HTPASSWD_REALM=Registry Realm" -e "REGISTRY_AUTH_HTPASSWD_PATH=/auth/htpasswd" registry 
32c5118507f92121359e6703bd54e8a28905a0e2d6b630ba44738966a62c7bb9
[root@wldev08 ~]# 
[root@wldev08 ~]# docker tag centos_lamp:v1 100.39.3.49:5000/project/centos_6.9_lamp:v1
[root@wldev08 ~]# docker image ls
REPOSITORY                                 TAG                 IMAGE ID            CREATED             SIZE
100.39.3.49:5000/project/centos_6.9_lamp   v1                  15bfd3eb90e3        3 days ago          854MB
centos_lamp                                v1                  15bfd3eb90e3        3 days ago          854MB
100.39.3.49:5000/project/nginx             v1                  540a289bab6c        3 weeks ago         126MB
nginx                                      latest              540a289bab6c        3 weeks ago         126MB
centos                                     6.9                 2199b8eb8390        8 months ago        195MB
registry                                   latest              f32a97de94e1        8 months ago        25.8MB
[root@wldev08 ~]#
// 登录后push镜像
[root@wldev08 ~]# docker login 100.39.3.49:5000
Username: test
Password: 
WARNING! Your password will be stored unencrypted in /root/.docker/config.json.
Configure a credential helper to remove this warning. See
https://docs.docker.com/engine/reference/commandline/login/#credentials-store

Login Succeeded
[root@wldev08 ~]# 
[root@wldev08 ~]# docker push 100.39.3.49:5000/project/centos_6.9_lamp:v1
The push refers to repository [100.39.3.49:5000/project/centos_6.9_lamp]
c6b133b877fa: Pushed 
af5f403820ae: Pushed 
b387341e38de: Pushed 
e15e17c0a372: Pushed 
ee15c8d95567: Pushed 
aaa5621d7c01: Pushed 
v1: digest: sha256:f784cdfeb8e3e8dd7c709b95970a98a09ceedbf468694824b16c1d2d32b118e3 size: 1578
[root@wldev08 ~]# 

  • 客户端拉取镜像
[root@wldev07 ~]# docker pull 100.39.3.49:5000/project/centos_6.9_lamp:v1
Error response from daemon: Get http://100.39.3.49:5000/v2/project/centos_6.9_lamp/manifests/v1: no basic auth credentials
[root@wldev07 ~]#
// 需要验证
[root@wldev07 ~]# docker login 100.39.3.49:5000
Username: test
Password: 
WARNING! Your password will be stored unencrypted in /root/.docker/config.json.
Configure a credential helper to remove this warning. See
https://docs.docker.com/engine/reference/commandline/login/#credentials-store

Login Succeeded
[root@wldev07 ~]# docker pull 100.39.3.49:5000/project/centos_6.9_lamp:v1
v1: Pulling from project/centos_6.9_lamp
831490506c47: Pull complete 
562532f241f3: Pull complete 
8ef3b8496366: Pull complete 
51813eebb982: Pull complete 
07b6ac5bc824: Pull complete 
b213027a511f: Pull complete 
Digest: sha256:f784cdfeb8e3e8dd7c709b95970a98a09ceedbf468694824b16c1d2d32b118e3
Status: Downloaded newer image for 100.39.3.49:5000/project/centos_6.9_lamp:v1
100.39.3.49:5000/project/centos_6.9_lamp:v1
[root@wldev07 ~]# 
[root@wldev08 ~]# cat /etc/docker/daemon.json 
{
  "registry-mirrors": ["https://b3z80jv9.mirror.aliyuncs.com"],
  "insecure-registries": ["100.39.3.49:5000","100.39.3.100"],
  "live-restore":true 
}

13. harbor安装

[root@wldev08 harbor]# curl -L "https://github.com/docker/compose/releases/download/1.23.1/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compos
[root@wldev08 ~]# chmod +x /usr/local/bin/docker-compose 
[root@wldev08 ~]# do
do              docker-compose  docker-init     domainname      
docker          dockerd         docker-proxy    done            
[root@wldev08 ~]# docker-compose version
docker-compose version 1.23.1, build b02f1306
docker-py version: 3.5.0
CPython version: 3.6.7
OpenSSL version: OpenSSL 1.1.0f  25 May 2017
[root@wldev08 ~]#
[root@wldev08 ~]# wget -c https://storage.googleapis.com/harbor-releases/release-1.8.0/harbor-offline-installer-v1.8.2-rc1.tgz
[root@wldev08 ~]# tar -zxvf harbor-offline-installer-v1.8.2-rc1.tgz 
harbor/harbor.v1.8.2.tar.gz
harbor/prepare
harbor/LICENSE
harbor/install.sh
harbor/harbor.yml
[root@wldev08 ~]#
[root@wldev08 harbor]# ls
harbor.v1.8.2.tar.gz  harbor.yml  install.sh  LICENSE  prepare
[root@wldev08 harbor]# vim harbor.yml
hostname: #IP地址或域名
http:
	port: 80
https:
	port: 443
	certificate: xxx
	private_key: xxx
harbor_admin_password: xxxxx #  Web端admin用户密码
database:
	password: xxxx
data_volumn: /data
docker默认使用的是https连接,harbor默认使用http连接,我们需要修改docker配置insecure registry
vim /usr/lib/systemd/system/docker.service
ExecStart=/usr/bin/dockerd --insecure-registry=100.39.3.49
[root@wldev08 harbor]# ./install.sh 

[Step 0]: checking installation environment ...

Note: docker version: 19.03.4

Note: docker-compose version: 1.23.1

[Step 1]: loading Harbor images ...
Loaded image: goharbor/harbor-portal:v1.8.2
Loaded image: goharbor/harbor-jobservice:v1.8.2
Loaded image: goharbor/harbor-registryctl:v1.8.2
Loaded image: goharbor/harbor-migrator:v1.8.2
Loaded image: goharbor/harbor-log:v1.8.2
Loaded image: goharbor/nginx-photon:v1.8.2
Loaded image: goharbor/notary-server-photon:v0.6.1-v1.8.2
Loaded image: goharbor/clair-photon:v2.0.8-v1.8.2
Loaded image: goharbor/registry-photon:v2.7.1-patch-2819-v1.8.2
Loaded image: goharbor/notary-signer-photon:v0.6.1-v1.8.2
Loaded image: goharbor/prepare:v1.8.2
Loaded image: goharbor/harbor-core:v1.8.2
Loaded image: goharbor/harbor-db:v1.8.2
Loaded image: goharbor/redis-photon:v1.8.2
Loaded image: goharbor/chartmuseum-photon:v0.9.0-v1.8.2


[Step 2]: preparing environment ...
prepare base dir is set to /root/harbor
Clearing the configuration file: /config/log/logrotate.conf
Clearing the configuration file: /config/nginx/nginx.conf
Clearing the configuration file: /config/core/env
Clearing the configuration file: /config/core/app.conf
Clearing the configuration file: /config/registry/config.yml
[Errno 16] Device or resource busy: '/config/registry/root.crt'
Clearing the configuration file: /config/registryctl/env
Clearing the configuration file: /config/registryctl/config.yml
Clearing the configuration file: /config/db/env
Clearing the configuration file: /config/jobservice/env
Clearing the configuration file: /config/jobservice/config.yml
Generated configuration file: /config/log/logrotate.conf
Generated configuration file: /config/nginx/nginx.conf
Generated configuration file: /config/core/env
Generated configuration file: /config/core/app.conf
Generated configuration file: /config/registry/config.yml
Generated configuration file: /config/registryctl/env
Generated configuration file: /config/db/env
Generated configuration file: /config/jobservice/env
Generated configuration file: /config/jobservice/config.yml
loaded secret from file: /secret/keys/secretkey
Generated configuration file: /compose_location/docker-compose.yml
Clean up the input dir


Note: stopping existing Harbor instance ...
Stopping harbor-jobservice ... done
Stopping harbor-portal     ... done
Stopping harbor-core       ... done
Stopping registry          ... done
Stopping redis             ... done
Stopping registryctl       ... done
Stopping harbor-db         ... done
Stopping harbor-log        ... done
Removing nginx             ... done
Removing harbor-jobservice ... done
Removing harbor-portal     ... done
Removing harbor-core       ... done
Removing registry          ... done
Removing redis             ... done
Removing registryctl       ... done
Removing harbor-db         ... done
Removing harbor-log        ... done
Removing network harbor_harbor


[Step 3]: starting Harbor ...
Creating network "harbor_harbor" with the default driver
Creating harbor-log ... done
Creating registry    ... done
Creating registryctl ... done
Creating harbor-db   ... done
Creating redis       ... done
Creating harbor-core ... done
Creating harbor-portal     ... done
Creating harbor-jobservice ... done
Creating nginx             ... done

✔ ----Harbor has been installed and started successfully.----

Now you should be able to visit the admin portal at http://100.39.3.49. 
For more details, please visit https://github.com/goharbor/harbor .

[root@wldev08 harbor]#

图形:http://IP:端口,默认用户名admin/Harbor12345 密码在harbor.yml即可查看
[root@wldev08 harbor]# docker ps
CONTAINER ID        IMAGE                                               COMMAND                  CREATED             STATUS                       PORTS                       NAMES
545be5edb6f3        goharbor/nginx-photon:v1.8.2                        "nginx -g 'daemon of…"   About an hour ago   Up About an hour (healthy)   0.0.0.0:8880->80/tcp        nginx
786fa2694c3d        goharbor/harbor-jobservice:v1.8.2                   "/harbor/start.sh"       About an hour ago   Up About an hour                                         harbor-jobservice
b66726bbc5c2        goharbor/harbor-portal:v1.8.2                       "nginx -g 'daemon of…"   About an hour ago   Up About an hour (healthy)   80/tcp                      harbor-portal
2787172e2358        goharbor/harbor-core:v1.8.2                         "/harbor/start.sh"       About an hour ago   Up About an hour (healthy)                               harbor-core
7050fa9e8ecf        goharbor/harbor-db:v1.8.2                           "/entrypoint.sh post…"   About an hour ago   Up About an hour (healthy)   5432/tcp                    harbor-db
c28fa404afe3        goharbor/harbor-registryctl:v1.8.2                  "/harbor/start.sh"       About an hour ago   Up About an hour (healthy)                               registryctl
53a3fea9f53a        goharbor/registry-photon:v2.7.1-patch-2819-v1.8.2   "/entrypoint.sh /etc…"   About an hour ago   Up About an hour (healthy)   5000/tcp                    registry
34e7266de279        goharbor/redis-photon:v1.8.2                        "docker-entrypoint.s…"   About an hour ago   Up About an hour             6379/tcp                    redis
5edeae199418        goharbor/harbor-log:v1.8.2                          "/bin/sh -c /usr/loc…"   About an hour ago   Up About an hour (healthy)   127.0.0.1:1514->10514/tcp   harbor-log
32c5118507f9        registry                                            "/entrypoint.sh /etc…"   3 days ago          Up 3 days                    0.0.0.0:5000->5000/tcp      register-auth
[root@wldev08 harbor]#

13.1 habor实现图形化镜像仓库

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-nNJlKJy4-1623251226119)(https://note.youdao.com/yws/public/resource/1aff0313a4d0185689e99f785e8a723c/xmlnote/4174E42AC50F467CB2C0B3696413EB44/25581)]

创建项目
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-YjRr79ES-1623251226122)(https://note.youdao.com/yws/public/resource/1aff0313a4d0185689e99f785e8a723c/xmlnote/WEBRESOURCE1523cfdbeb977370b382e151b4ac3818/25591)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-BJsDKSjV-1623251226124)(https://note.youdao.com/yws/public/resource/1aff0313a4d0185689e99f785e8a723c/xmlnote/WEBRESOURCEb4e769a2654111d78956b5141cbda519/25597)]
修改配置文件,新增内容

[root@wldev08 ~]# cat /etc/docker/daemon.json 
{
  "registry-mirrors": ["https://b3z80jv9.mirror.aliyuncs.com"],
  "insecure-registries": ["100.39.3.49:5000","100.39.3.49"],
  "live-restore":true  // docker重启了,也跟着重启
}
[root@wldev08 ~]# systemctl restart docker

上传镜像前,先打tag,在推送镜像
[root@wldev08 ~]# docker tag centos:6.9 100.39.3.49/project/centos:v1
[root@wldev08 ~]# docker login 100.39.3.49
Username: admin
Password: 
WARNING! Your password will be stored unencrypted in /root/.docker/config.json.
Configure a credential helper to remove this warning. See
https://docs.docker.com/engine/reference/commandline/login/#credentials-store

Login Succeeded
[root@wldev08 ~]# docker push 100.39.3.49/project/centos:v1
The push refers to repository [100.39.3.49/project/centos]
aaa5621d7c01: Preparing 
denied: requested access to the resource is denied
[root@wldev08 ~]# docker push 100.39.3.49/project/centos:v1
The push refers to repository [100.39.3.49/project/centos]
aaa5621d7c01: Pushed 
v1: digest: sha256:7e172600dff1903f186061ce5f5295664ec9942ca120e4e5b427ddf01bb2b35b size: 529
[root@wldev08 ~]#

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ohbdcHGs-1623251226129)(https://note.youdao.com/yws/public/resource/1aff0313a4d0185689e99f785e8a723c/xmlnote/WEBRESOURCEae6dfe224e3b072dd1f2e345fbaab1ea/25615)]

14. docker网络类型

14.1 本地网络

查看网络类型

[root@wldev08 ~]# docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
eb698aabeb0f        bridge              bridge              local
b60f042633a2        harbor_harbor       bridge              local
558622dd382e        host                host                local
ebd1e0a76f59        none                null                local
[root@wldev08 ~]# 

None:不为容器配置任何网络功能(无网络模式),--net=none

Container:与另一个运行中的容器共享Network
Namespace,--net=container:containerID(K8S)

Host:与宿主机共享Network Namespace,--net=host

Bridge:默认模式,相当于NAT网络模型

14.2 网络类型

  • None
无网络模式

[root@wldev08 ~]# docker run -it --name="centos6.9_none" --network=none centos:6.9 /bin/bash
[root@a401c0b9b8bb /]# ifconfig
lo        Link encap:Local Loopback  
          inet addr:127.0.0.1  Mask:255.0.0.0
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:0 (0.0 b)  TX bytes:0 (0.0 b)

[root@a401c0b9b8bb /]# 
  • Container
[root@wldev08 ~]# docker ps -a
CONTAINER ID        IMAGE                                               COMMAND                  CREATED             STATUS                      PORTS                       NAMES
a401c0b9b8bb        centos:6.9                                          "/bin/bash"              3 minutes ago       Up About a minute                                       centos6.9_none
60c0f279bd11        centos:6.9                                          "/bin/bash"              15 minutes ago      Exited (0) 9 minutes ago                                centos6.9_host
a6bc0e0df1e1        centos:6.9                                          "/bin/bash"              23 minutes ago      Up 12 minutes                                           centos6.9_bridge
d95f55816e00        2199b8eb8390             
[root@wldev08 ~]# docker run -it --network container:a401c0b9b8bb --name="centos6.9_container"  centos:6.9 /bin/bash
[root@a401c0b9b8bb /]# ifconfig
lo        Link encap:Local Loopback  
          inet addr:127.0.0.1  Mask:255.0.0.0
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:0 (0.0 b)  TX bytes:0 (0.0 b)

[root@a401c0b9b8bb /]# 
共用了主机名的ip地址,要注意的是这种公用container类型的端口是谁先用某个端口,谁就占了,后来的没法使用这个端口
[root@wldev08 ~]# docker inspect 183eb3995e79 |grep -i network
            "NetworkMode": "container:a401c0b9b8bb5ce537b735b9a869ac2e287f21d8287072729b3177db804db53e",
        "NetworkSettings": {
            "Networks": {}
[root@wldev08 ~]#
  • Host
[root@wldev08 ~]# docker run -it --name="centos6.9_host" --network=host centos:6.9 /bin/bash
[root@wldev08 /]# 
[root@wldev08 ~]# docker attach 60c0f279bd11
[root@wldev08 /]# ifconfig
br-b60f042633a2 Link encap:Ethernet  HWaddr 02:42:69:57:7D:FB  
          inet addr:172.18.0.1  Bcast:172.18.255.255  Mask:255.255.0.0
          inet6 addr: fe80::42:69ff:fe57:7dfb/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:11733 errors:0 dropped:0 overruns:0 frame:0
          TX packets:27510 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:1557617 (1.4 MiB)  TX bytes:72397063 (69.0 MiB)

docker0   Link encap:Ethernet  HWaddr 02:42:52:62:75:66  
          inet addr:172.17.0.1  Bcast:172.17.255.255  Mask:255.255.0.0
  • Bridge
[root@wldev08 ~]# docker run -it --name="centos6.9_bridge" --network=bridge centos:6.9 /bin/bash
[root@a6bc0e0df1e1 /]# ifconfig -a
eth0      Link encap:Ethernet  HWaddr 02:42:AC:11:00:02  
          inet addr:172.17.0.2  Bcast:172.17.255.255  Mask:255.255.0.0

14.3 跨主机网络访问-macvlan实现

// centos需先开启混杂模式
[root@wldev08 ~]# ip link set enp0s3 promisc on
[root@wldev08 ~]# ip link show enp0s3
2: enp0s3:  mtu 1500 qdisc pfifo_fast state UP mode DEFAULT group default qlen 1000
    link/ether 08:00:27:bb:0c:9e brd ff:ff:ff:ff:ff:ff
[root@wldev08 ~]# docker network create --driver macvlan --subnet=192.168.10.0/24 --gateway=192.168.10.254 -o parent=enp0s3 macvlan_1
26914483843bacb1b9906e71b3ef7532d252d272f1a1d0fac8f1485afd9caa3a
[root@wldev08 ~]# 
[root@wldev08 ~]# docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
eb698aabeb0f        bridge              bridge              local
c0f82c69296c        harbor_harbor       bridge              local
558622dd382e        host                host                local
26914483843b        macvlan_1           macvlan             local
ebd1e0a76f59        none                null                local
[root@wldev08 ~]#
[root@wldev08 ~]# docker image ls
REPOSITORY                                 TAG                        IMAGE ID            CREATED             SIZE
100.39.3.49:5000/project/centos_6.9_lamp   v1                         15bfd3eb90e3        8 days ago          854MB
centos_lamp                                v1                         15bfd3eb90e3        8 days ago          854MB
100.39.3.49:5000/project/nginx             v1                         540a289bab6c        4 weeks ago         126MB
nginx                                      latest                     540a289bab6c        4 weeks ago         126MB
goharbor/chartmuseum-photon                v0.9.0-v1.8.2              20aaceb90ff1        4 months ago        130MB
goharbor/harbor-migrator                   v1.8.2                     e85c76d837c3        4 months ago        361MB
goharbor/redis-photon                      v1.8.2                     4d6fc41412c8        4 months ago        106MB
goharbor/clair-photon                      v2.0.8-v1.8.2              bccf5643d210        4 months ago        164MB
goharbor/notary-server-photon              v0.6.1-v1.8.2              fb4c25c2f361        4 months ago        135MB
goharbor/notary-signer-photon              v0.6.1-v1.8.2              01d19ad49522        4 months ago        132MB
goharbor/harbor-registryctl                v1.8.2                     cc242b8b0bbd        4 months ago        96.4MB
goharbor/registry-photon                   v2.7.1-patch-2819-v1.8.2   83cec7e1a467        4 months ago        81.5MB
goharbor/nginx-photon                      v1.8.2                     3c240070b06a        4 months ago        36.2MB
goharbor/harbor-log                        v1.8.2                     4ba150498fac        4 months ago        81.7MB
goharbor/harbor-jobservice                 v1.8.2                     6cd242a9b225        4 months ago        119MB
goharbor/harbor-core                       v1.8.2                     6751bfc5ad31        4 months ago        135MB
goharbor/harbor-portal                     v1.8.2                     b8e738ba7ea0        4 months ago        43.1MB
goharbor/harbor-db                         v1.8.2                     3a6d510d2c83        4 months ago        144MB
goharbor/prepare                           v1.8.2                     e10c48756908        4 months ago        142MB
100.39.3.49/project/centos                 v1                         2199b8eb8390        8 months ago        195MB
centos                                     6.9                        2199b8eb8390        8 months ago        195MB
registry                                   latest                     f32a97de94e1        8 months ago        25.8MB
[root@wldev08 ~]# docker run -it --name=centos6.9_macvlan --network=macvlan_1  2199b8eb8390 /bin/bash
[root@e427b78b5d10 /]# 
[root@e427b78b5d10 /]# ifconfig eth0
eth0      Link encap:Ethernet  HWaddr 02:42:C0:A8:0A:01  
          inet addr:192.168.10.1  Bcast:192.168.10.255  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:18 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:1080 (1.0 KiB)  TX bytes:0 (0.0 b)

[root@e427b78b5d10 /]#

[root@wldev07 ~]# ip link set enp0s3 promisc on

[root@wldev07 ~]# ip link show enp0s3 
2: enp0s3:  mtu 1500 qdisc pfifo_fast state UP mode DEFAULT group default qlen 1000
    link/ether 08:00:27:62:5e:97 brd ff:ff:ff:ff:ff:ff
[root@wldev07 ~]#
[root@wldev07 ~]# docker network create --driver macvlan --subnet=192.168.10.0/24 --gateway=192.168.10.254 -o parent=enp0s3 macvlan_1
f55c8057e41f2016a569c31416a8f3b91f8c83e51678e6370dc49c59833af5c0
[root@wldev07 ~]# docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
4e076053de70        bridge              bridge              local
fbe23ecac39b        host                host                local
f55c8057e41f        macvlan_1           macvlan             local
e6860e70e3f6        none                null                local
[root@wldev07 ~]# 
[root@wldev07 ~]# docker image ls
REPOSITORY                                 TAG                 IMAGE ID            CREATED             SIZE
100.39.3.49:5000/project/centos_6.9_lamp   v1                  15bfd3eb90e3        8 days ago          854MB
100.39.3.49:5000/project/nginx             v1                  540a289bab6c        4 weeks ago         126MB
centos                                     6.9                 2199b8eb8390        8 months ago        195MB
[root@wldev07 ~]# docker run -it --name=centos6.9_macvlan --network=macvlan_1  2199b8eb8390 /bin/bash
[root@33f282bb50b6 /]# ifconfig eth0
eth0      Link encap:Ethernet  HWaddr 02:42:C0:A8:0A:02  
          inet addr:192.168.10.2  Bcast:192.168.10.255  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:18 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:1273 (1.2 KiB)  TX bytes:0 (0.0 b)

[root@33f282bb50b6 /]#

增加ip
[root@wldev07 ~]# docker run -it --name "centos6.9_macvlan1" --network=macvlan_1  --ip=192.168.10.2 2199b8eb8390 /bin/bash

// 删除退出状态容器
docker rm $(docker ps -q -f status=exited)

14.4 docker 跨主机访问-overlay实现

overlay网络利用隧道技术,将数据包封装到UDP中进行传输。因为涉及数据包的封装解封,存在额外的cpu和网络开销

overlay较underlay可以支持更多的二层网络,更好的利用已有网络,以及有效的避免物理交换机MAC表耗尽等优势

  • 启动 consul 服务,实现网络的统一配置管理
[root@wldev08 ~]# docker run -d -p 8500:8500 -h consul --name consul progrium/consul -server -bootstrap
Unable to find image 'progrium/consul:latest' locally
latest: Pulling from progrium/consul
Image docker.io/progrium/consul:latest uses outdated schema1 manifest format. Please upgrade to a schema2 image for better future compatibility. More information at https://docs.docker.com/registry/spec/deprecated-schema-v1/
c862d82a67a2: Pull complete 
0e7f3c08384e: Pull complete 
0e221e32327a: Pull complete 
09a952464e47: Pull complete 
60a1b927414d: Pull complete 
4c9f46b5ccce: Pull complete 
417d86672aa4: Pull complete 
b0d47ad24447: Pull complete 
fd5300bd53f0: Pull complete 
a3ed95caeb02: Pull complete 
d023b445076e: Pull complete 
ba8851f89e33: Pull complete 
5d1cefca2a28: Pull complete 
Digest: sha256:8cc8023462905929df9a79ff67ee435a36848ce7a10f18d6d0faba9306b97274
Status: Downloaded newer image for progrium/consul:latest
d8eaf6975784ede1fa8da0954549a485da7967cf3b697aed89074798e6713534
[root@wldev08 ~]#

节点配置,节点都需要增加第二段配置,之后重启dokcer
[root@wldev08 ~]# cat /etc/docker/daemon.json 
{
  "registry-mirrors": ["https://uoggbpok.mirror.aliyuncs.com"],
  "insecure-registries": ["100.39.3.49:5000","100.39.3.49"],
  "live-restore":true,
  "hosts":["tcp://0.0.0.0:2376","unix:///var/run/docker.sock"],
  "cluster-store": "consul://100.39.3.49:8500",
  "cluster-advertise": "100.39.3.49:2376"
}
[root@wldev08 ~]#
[root@wldev08 ~]# systemctl daemon-reload
[root@wldev08 ~]# systemctl start docker
// 更改完配置docker需进行重启
[root@wldev08 ~]# docker ps -a |grep progrium/consul
d8eaf6975784        progrium/consul                                     "/bin/start -server …"   49 minutes ago      Up 49 minutes               53/tcp, 53/udp, 8300-8302/tcp, 8400/tcp, 8301-8302/udp, 0.0.0.0:8500->8500/tcp   consul
[root@wldev08 ~]#

  • 创建overlay网络(通道)
[root@wldev08 ~]# docker network create -d overlay --subnet 172.16.0.0/24 --gateway 172.16.0.254  overlay_only
cfa71bf6df710013b637fb053f76091856add9ed0c6e5b53ea8bd8e0ea359f7d
[root@wldev08 ~]# docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
eb698aabeb0f        bridge              bridge              local
c0f82c69296c        harbor_harbor       bridge              local
558622dd382e        host                host                local
26914483843b        macvlan_1           macvlan             local
ebd1e0a76f59        none                null                local
cfa71bf6df71        overlay_only        overlay             global
[root@wldev08 ~]#
[root@wldev07 ~]# docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
cf1fe17298ad        bridge              bridge              local
fbe23ecac39b        host                host                local
f55c8057e41f        macvlan_1           macvlan             local
e6860e70e3f6        none                null                local
cfa71bf6df71        overlay_only        overlay             global
[root@wldev07 ~]#
  • 启动启动容器测试
[root@wldev08 ~]# docker run -it --network overlay_only busybox /bin/sh
Unable to find image 'busybox:latest' locally
latest: Pulling from library/busybox
0f8c40e1270f: Pull complete 
Digest: sha256:1303dbf110c57f3edf68d9f5a16c082ec06c4cf7604831669faf2c712260b5a0
Status: Downloaded newer image for busybox:latest
/ # ifconfig
eth0      Link encap:Ethernet  HWaddr 02:42:AC:10:00:01  
          inet addr:172.16.0.1  Bcast:172.16.0.255  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1450  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

eth1      Link encap:Ethernet  HWaddr 02:42:AC:13:00:02  
          inet addr:172.19.0.2  Bcast:172.19.255.255  Mask:255.255.0.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:13 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:1046 (1.0 KiB)  TX bytes:0 (0.0 B)

lo        Link encap:Local Loopback  
          inet addr:127.0.0.1  Mask:255.0.0.0
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

/ # ping www.baidu.com
PING www.baidu.com (61.135.169.125): 56 data bytes
64 bytes from 61.135.169.125: seq=1 ttl=55 time=11.182 ms
64 bytes from 61.135.169.125: seq=2 ttl=55 time=16.102 ms
^C
--- www.baidu.com ping statistics ---
3 packets transmitted, 2 packets received, 33% packet loss
round-trip min/avg/max = 11.182/13.642/16.102 ms
/ # 

[root@wldev07 ~]# docker run -it --network overlay_only busybox /bin/sh
Unable to find image 'busybox:latest' locally
latest: Pulling from library/busybox
0f8c40e1270f: Pull complete 
Digest: sha256:1303dbf110c57f3edf68d9f5a16c082ec06c4cf7604831669faf2c712260b5a0
Status: Downloaded newer image for busybox:latest
/ # ifconfig
eth0      Link encap:Ethernet  HWaddr 02:42:AC:10:00:02  
          inet addr:172.16.0.2  Bcast:172.16.0.255  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1450  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

eth1      Link encap:Ethernet  HWaddr 02:42:AC:12:00:02  
          inet addr:172.18.0.2  Bcast:172.18.255.255  Mask:255.255.0.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:16 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:1312 (1.2 KiB)  TX bytes:0 (0.0 B)

lo        Link encap:Local Loopback  
          inet addr:127.0.0.1  Mask:255.0.0.0
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

/ #
每个容器有两块网卡,eth0实现容器间的通讯,eth1实现容器访问外网
  • 测试
[root@wldev08 ~]# docker network create -d overlay over_only1
0770e9c9e2aab1656f01cde15fd6672af859fee71c579d606ee93f1817c4cb1e
[root@wldev08 ~]# docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
36e9d7284e52        bridge              bridge              local
c0f82c69296c        harbor_harbor       bridge              local
558622dd382e        host                host                local
26914483843b        macvlan_1           macvlan             local
ebd1e0a76f59        none                null                local
0770e9c9e2aa        over_only1          overlay             global
[root@wldev08 ~]# docker network inspect over_only1
[
    {
        "Name": "over_only1",
        "Id": "0770e9c9e2aab1656f01cde15fd6672af859fee71c579d606ee93f1817c4cb1e",
        "Created": "2019-11-21T11:27:20.241436858+08:00",
        "Scope": "global",
        "Driver": "overlay",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": {},
            "Config": [
                {
                    "Subnet": "10.0.0.0/24",
                    "Gateway": "10.0.0.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": false,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {},
        "Options": {},
        "Labels": {}
    }
]
[root@wldev08 ~]# 
[root@wldev08 ~]# docker run -itd --name busybox1 --network over_only1 busybox
7aa3b16179b6cf14b61bc46881935aa210255904de40bf49470abd51072ff9b4
[root@wldev08 ~]#
[root@wldev08 ~]# docker exec -it busybox1 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
97: eth0@if98:  mtu 1450 qdisc noqueue 
    link/ether 02:42:0a:00:00:02 brd ff:ff:ff:ff:ff:ff
    inet 10.0.0.2/24 brd 10.0.0.255 scope global eth0
       valid_lft forever preferred_lft forever
100: eth1@if101:  mtu 1500 qdisc noqueue 
    link/ether 02:42:ac:13:00:02 brd ff:ff:ff:ff:ff:ff
    inet 172.19.0.2/16 brd 172.19.255.255 scope global eth1
       valid_lft forever preferred_lft forever
[root@wldev08 ~]# 
 // 测试连通性
[root@wldev08 ~]# docker exec busybox1 ping 10.0.0.3 -c 5
PING 10.0.0.3 (10.0.0.3): 56 data bytes
64 bytes from 10.0.0.3: seq=0 ttl=64 time=18.609 ms
64 bytes from 10.0.0.3: seq=1 ttl=64 time=9.919 ms
64 bytes from 10.0.0.3: seq=2 ttl=64 time=19.921 ms
64 bytes from 10.0.0.3: seq=3 ttl=64 time=20.044 ms
64 bytes from 10.0.0.3: seq=4 ttl=64 time=19.920 ms

--- 10.0.0.3 ping statistics ---
5 packets transmitted, 5 packets received, 0% packet loss
round-trip min/avg/max = 9.919/17.682/20.044 ms
[root@wldev08 ~]#

[root@wldev07 ~]# docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
33054e02283a        bridge              bridge              local
fbe23ecac39b        host                host                local
f55c8057e41f        macvlan_1           macvlan             local
e6860e70e3f6        none                null                local
0770e9c9e2aa        over_only1          overlay             global
[root@wldev07 ~]# docker network inspect over_only1
[
    {
        "Name": "over_only1",
        "Id": "0770e9c9e2aab1656f01cde15fd6672af859fee71c579d606ee93f1817c4cb1e",
        "Created": "2019-11-21T11:27:20.241436858+08:00",
        "Scope": "global",
        "Driver": "overlay",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": {},
            "Config": [
                {
                    "Subnet": "10.0.0.0/24",
                    "Gateway": "10.0.0.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": false,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {},
        "Options": {},
        "Labels": {}
    }
]
[root@wldev07 ~]# docker run -itd --name busybox2 --network over_only1 busybox
ff31826cda908b1fba0565f4c40618bd0d2358d7d39b93e33d8579794291d475
[root@wldev07 ~]#
[root@wldev07 ~]# docker exec -it busybox2 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
23: eth0@if24:  mtu 1450 qdisc noqueue 
    link/ether 02:42:0a:00:00:03 brd ff:ff:ff:ff:ff:ff
    inet 10.0.0.3/24 brd 10.0.0.255 scope global eth0
       valid_lft forever preferred_lft forever
26: eth1@if27:  mtu 1500 qdisc noqueue 
    link/ether 02:42:ac:12:00:02 brd ff:ff:ff:ff:ff:ff
    inet 172.18.0.2/16 brd 172.18.255.255 scope global eth1
       valid_lft forever preferred_lft forever
[root@wldev07 ~]#

你可能感兴趣的:(Docker,docker)