docker的学习笔记

1. docker的介绍

2. docker的安装

1. 卸载旧版本的docker

sudo apt-get remove docker docker-engine docker.io containerd runc

2. 更新apt数据包

sudo apt-get update

3. 安装docker

一般是推荐使用官网文档来进行下载的,但是我这服务器不满足环境,就不能下载,从其他网站找到的方法可以使用下面命令即可下载
apt-get install docker.io

4. 启动docker服务

systemctl start dokcer

5. 查看是否安装成功

root@Junzhiyuechuan:~# docker version
Client:
	Version:           20.10.12
	API version:       1.41
Go version:        go1.16.2
	Git commit:        20.10.12-0ubuntu2~20.04.1
	Built:             Wed Apr  6 02:14:38 2022
OS/Arch:           linux/amd64
	Context:           default
	Experimental:      true

Server:
	Engine:
 	Version:          20.10.12
 	API version:      1.41 (minimum version 1.12)
 	Go version:       go1.16.2
 	Git commit:       20.10.12-0ubuntu2~20.04.1
 	Built:            Thu Feb 10 15:03:35 2022
 	OS/Arch:          linux/amd64
 	Experimental:     false
	containerd:
 	Version:          1.5.9-0ubuntu1~20.04.4
 	GitCommit:        
	runc:
 	Version:          1.1.0-0ubuntu1~20.04.1
 	GitCommit:        
	docker-init:
 	Version:          0.19.0
 	GitCommit:        

6. 运行hello-world镜像

root@Junzhiyuechuan:~# docker run hello-world
Unable to find image 'hello-world:latest' locally # 没有找到镜像
latest: Pulling from library/hello-world # 从仓库中进行镜像的拉取
2db29710123e: Pull complete 
Digest: sha256:7d246653d0511db2a6b2e0436cfd0e52ac8c066000264b3ce63331ac66dca625
Status: Downloaded newer image for hello-world:latest

Hello from Docker!
This message shows that your installation appears to be working correctly.

To generate this message, Docker took the following steps:
 1. The Docker client contacted the Docker daemon.
 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
    (amd64)
 3. The Docker daemon created a new container from that image which runs the
    executable that produces the output you are currently reading.
 4. The Docker daemon streamed that output to the Docker client, which sent it
    to your terminal.

To try something more ambitious, you can run an Ubuntu container with:
 $ docker run -it ubuntu bash

Share images, automate workflows, and more with a free Docker ID:
 https://hub.docker.com/

7. 查看hello-world镜像的相关信息

root@Junzhiyuechuan:~# docker images
REPOSITORY    TAG       IMAGE ID       CREATED         SIZE
hello-world   latest    feb5d9fea6a5   11 months ago   13.3kB

8. 卸载docker

apt-get remove docker.io # 卸载软件
rm -rf /var/lib/docker # 删除文件

3. docker的常用命令

1. 帮助命令

docker version
docker info
docker 命令 --help

2. 镜像命令

docker images

用于显示镜像的相关信息

root@Junzhiyuechuan:~# docker images --help

Usage:  docker images [OPTIONS] [REPOSITORY[:TAG]]

List images

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

docker search

从docker hub中进行镜像的查询
也可以自行去浏览器搜索docker和命令行运行指令是一致的

root@Junzhiyuechuan:~# docker search --help

Usage:  docker search [OPTIONS] TERM

Search the Docker Hub for images

Options:
  -f, --filter filter   Filter output based on conditions provided
      --format string   Pretty-print search using a Go template
      --limit int       Max number of search results (default 25)
      --no-trunc        Don't truncate output

root@Junzhiyuechuan:~# docker search mysql
NAME                            DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
mysql                           MySQL is a widely used, open-source relation…   13161     [OK]       
mariadb                         MariaDB Server is a high performing open sou…   5029      [OK]       
phpmyadmin                      phpMyAdmin - A web interface for MySQL and M…   624       [OK]       
percona                         Percona Server is a fork of the MySQL relati…   584       [OK]       
bitnami/mysql                   Bitnami MySQL Docker Image                      76                   [OK]
databack/mysql-backup           Back up mysql databases to... anywhere!         68                   
linuxserver/mysql-workbench                                                     43                   
linuxserver/mysql               A Mysql container, brought to you by LinuxSe…   37                   
ubuntu/mysql                    MySQL open source fast, stable, multi-thread…   36                   
circleci/mysql                  MySQL is a widely used, open-source relation…   27                   
google/mysql                    MySQL server for Google Compute Engine          21                   [OK]
rapidfort/mysql                 RapidFort optimized, hardened image for MySQL   13                   
bitnami/mysqld-exporter                                                         3                    
ibmcom/mysql-s390x              Docker image for mysql-s390x                    2                    
vitess/mysqlctld                vitess/mysqlctld                                1                    [OK]

在这里插入图片描述

root@Junzhiyuechuan:~# docker search mysql -f=STARS=5000
NAME      DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
mysql     MySQL is a widely used, open-source relation…   13161     [OK]       
mariadb   MariaDB Server is a high performing open sou…   5029      [OK] 
# -f --filter过滤器
过滤STARS大于等于5000的镜像   

docker pull

root@Junzhiyuechuan:~# docker pull --help

Usage:  docker pull [OPTIONS] NAME[:TAG|@DIGEST]

Pull an image or a repository from a registry

Options:
  -a, --all-tags                Download all tagged images in the repository
      --disable-content-trust   Skip image verification (default true)
      --platform string         Set platform if server is multi-platform capable
  -q, --quiet                   Suppress verbose output

docker pull 镜像名称:版本号

root@Junzhiyuechuan:~# docker pull mysql:8.0
8.0: Pulling from library/mysql # 不加:版本号,默认下载latest版本
492d84e496ea: Pull complete # 分层下载,作用:当别的镜像需要下载同一个组件时,不需要再次下载
bbe20050901c: Pull complete 
e3a5e171c2f8: Pull complete 
c2cedd8aa061: Pull complete 
d6a485af4cc9: Pull complete 
ee16a57baf60: Pull complete 
64bab9180d2a: Pull complete 
c3aceb7e4f48: Pull complete 
269002e5cf58: Pull complete 
d5abeb1bd18e: Pull complete 
cbd79da5fab6: Pull complete 
Digest: sha256:cdf3b62d78d1bbb1d2bd6716895a84014e00716177cbb7e90f6c6a37a21dc796# 签名
Status: Downloaded newer image for mysql:8.0
docker.io/library/mysql:8.0 # 真实地址

在这里插入图片描述

dokcer rmi

root@Junzhiyuechuan:~# docker rmi --help

Usage:  docker rmi [OPTIONS] IMAGE [IMAGE...]

Remove one or more images

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

  1. 可以根据镜像的id来对其进行删除
    docker rmi -f 镜像id在这里插入图片描述 记住id并不一定是唯一的,对于同一个镜像的不同版本其id是一致的
  2. 可以通过$()来继续条件查询,将查询到的结果作为参数传给删除
    docker rmi -f $()
root@Junzhiyuechuan:~# docker rmi -f $(docker images -aq) # $()就是查询所有镜像的id
Untagged: mysql:8.0
Untagged: mysql:latest
Untagged: mysql@sha256:cdf3b62d78d1bbb1d2bd6716895a84014e00716177cbb7e90f6c6a37a21dc796
Deleted: sha256:ff3b5098b416cc4294d8d5c43c2f0f8251e91711347318e73cb290ffe2783bcb
Deleted: sha256:905d309cb1263e8e4d25e6da210fb74fe83499efc9add5e6609126e7491fa678
Deleted: sha256:e1b431304265185fa56b11948a66872cc51dca13c846103826a87bb388db697f

3. 容器命令

有了镜像才能创建容器,一个镜像可以创建多个容器,容器删除了,镜像还存在

latest: Pulling from library/centos
a1d0c7532777: Pull complete 
Digest: sha256:a27fd8080b517143cbbbab9dfb7c8571c40d67d534bbdee55bd6c473f432b177
Status: Downloaded newer image for centos:latest
docker.io/library/centos:latest
root@Junzhiyuechuan:~# docker images
REPOSITORY   TAG       IMAGE ID       CREATED         SIZE
centos       latest    5d0da3dc9764   11 months ago   231MB

dokcer run

root@Junzhiyuechuan:~# docker run --help

Usage:  docker run [OPTIONS] IMAGE [COMMAND] [ARG...]

Run a command in a new container

Options:
      --add-host list                  Add a custom host-to-IP mapping (host:ip)
  -a, --attach list                    Attach to STDIN, STDOUT or STDERR
      --blkio-weight uint16            Block IO (relative weight), between 10 and 1000, or 0 to disable (default 0)
      --blkio-weight-device list       Block IO weight (relative device weight) (default [])
      --cap-add list                   Add Linux capabilities
      --cap-drop list                  Drop Linux capabilities
      --cgroup-parent string           Optional parent cgroup for the container
      --cgroupns string                Cgroup namespace to use (host|private)
                                       'host':    Run the container in the Docker host's cgroup namespace
                                       'private': Run the container in its own private cgroup namespace
                                       '':        Use the cgroup namespace as configured by the
                                                  default-cgroupns-mode option on the daemon (default)
      --cidfile string                 Write the container ID to the file
      --cpu-period int                 Limit CPU CFS (Completely Fair Scheduler) period
      --cpu-quota int                  Limit CPU CFS (Completely Fair Scheduler) quota
      --cpu-rt-period int              Limit CPU real-time period in microseconds
      --cpu-rt-runtime int             Limit CPU real-time runtime in microseconds
  -c, --cpu-shares int                 CPU shares (relative weight)
      --cpus decimal                   Number of CPUs
      --cpuset-cpus string             CPUs in which to allow execution (0-3, 0,1)
      --cpuset-mems string             MEMs in which to allow execution (0-3, 0,1)
  -d, --detach                         Run container in background and print container ID
      --detach-keys string             Override the key sequence for detaching a container
      --device list                    Add a host device to the container
      --device-cgroup-rule list        Add a rule to the cgroup allowed devices list
      --device-read-bps list           Limit read rate (bytes per second) from a device (default [])
      --device-read-iops list          Limit read rate (IO per second) from a device (default [])
      --device-write-bps list          Limit write rate (bytes per second) to a device (default [])
      --device-write-iops list         Limit write rate (IO per second) to a device (default [])
      --disable-content-trust          Skip image verification (default true)
      --dns list                       Set custom DNS servers
      --dns-option list                Set DNS options
      --dns-search list                Set custom DNS search domains
      --domainname string              Container NIS domain name
      --entrypoint string              Overwrite the default ENTRYPOINT of the image
  -e, --env list                       Set environment variables
      --env-file list                  Read in a file of environment variables
      --expose list                    Expose a port or a range of ports
      --gpus gpu-request               GPU devices to add to the container ('all' to pass all GPUs)
      --group-add list                 Add additional groups to join
      --health-cmd string              Command to run to check health
      --health-interval duration       Time between running the check (ms|s|m|h) (default 0s)
      --health-retries int             Consecutive failures needed to report unhealthy
      --health-start-period duration   Start period for the container to initialize before starting health-retries countdown (ms|s|m|h) (default 0s)
      --health-timeout duration        Maximum time to allow one check to run (ms|s|m|h) (default 0s)
      --help                           Print usage
  -h, --hostname string                Container host name
      --init                           Run an init inside the container that forwards signals and reaps processes
  -i, --interactive                    Keep STDIN open even if not attached
      --ip string                      IPv4 address (e.g., 172.30.100.104)
      --ip6 string                     IPv6 address (e.g., 2001:db8::33)
      --ipc string                     IPC mode to use
      --isolation string               Container isolation technology
      --kernel-memory bytes            Kernel memory limit
  -l, --label list                     Set meta data on a container
      --label-file list                Read in a line delimited file of labels
      --link list                      Add link to another container
      --link-local-ip list             Container IPv4/IPv6 link-local addresses
      --log-driver string              Logging driver for the container
      --log-opt list                   Log driver options
      --mac-address string             Container MAC address (e.g., 92:d0:c6:0a:29:33)
  -m, --memory bytes                   Memory limit
      --memory-reservation bytes       Memory soft limit
      --memory-swap bytes              Swap limit equal to memory plus swap: '-1' to enable unlimited swap
      --memory-swappiness int          Tune container memory swappiness (0 to 100) (default -1)
      --mount mount                    Attach a filesystem mount to the container
      --name string                    Assign a name to the container
      --network network                Connect a container to a network
      --network-alias list             Add network-scoped alias for the container
      --no-healthcheck                 Disable any container-specified HEALTHCHECK
      --oom-kill-disable               Disable OOM Killer
      --oom-score-adj int              Tune host's OOM preferences (-1000 to 1000)
      --pid string                     PID namespace to use
      --pids-limit int                 Tune container pids limit (set -1 for unlimited)
      --platform string                Set platform if server is multi-platform capable
      --privileged                     Give extended privileges to this container
  -p, --publish list                   Publish a container's port(s) to the host
  -P, --publish-all                    Publish all exposed ports to random ports
      --pull string                    Pull image before running ("always"|"missing"|"never") (default "missing")
      --read-only                      Mount the container's root filesystem as read only
      --restart string                 Restart policy to apply when a container exits (default "no")
      --rm                             Automatically remove the container when it exits
      --runtime string                 Runtime to use for this container
      --security-opt list              Security Options
      --shm-size bytes                 Size of /dev/shm
      --sig-proxy                      Proxy received signals to the process (default true)
      --stop-signal string             Signal to stop a container (default "SIGTERM")
      --stop-timeout int               Timeout (in seconds) to stop a container
      --storage-opt list               Storage driver options for the container
      --sysctl map                     Sysctl options (default map[])
      --tmpfs list                     Mount a tmpfs directory
  -t, --tty                            Allocate a pseudo-TTY
      --ulimit ulimit                  Ulimit options (default [])
  -u, --user string                    Username or UID (format: <name|uid>[:<group|gid>])
      --userns string                  User namespace to use
      --uts string                     UTS namespace to use
  -v, --volume list                    Bind mount a volume
      --volume-driver string           Optional volume driver for the container
      --volumes-from list              Mount volumes from the specified container(s)
  -w, --workdir string                 Working directory inside the container

常用的参数

--name="NAME"	容器的名称,如tomacat01, tomacat02 用于区分容器
-d				后台方式运行
-it 			以交互的方式运行,进入容器查看内容
-p 				指定容器端口

docker run -d --name=Name -p 外部端口:内部端口 镜像名称

# 									  容器名称 默认的命令行
root@Junzhiyuechuan:~# docker run -it centos /bin/bash  
[root@778ab3cc308d /]# ls # 容器内部和外部不连通,基础版本
bin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
# 退出命令
[root@778ab3cc308d /]# exit 
exit
root@Junzhiyuechuan:~# ls

docker ps

查看所有正在运行中的容器
docker ps

root@Junzhiyuechuan:~# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES

查看曾经运行的容器
docker ps -a

root@Junzhiyuechuan:~# docker ps -a
CONTAINER ID   IMAGE          COMMAND       CREATED             STATUS                          PORTS     NAMES
778ab3cc308d   centos         "/bin/bash"   3 minutes ago       Exited (0) About a minute ago             dazzling_wing
c296451a01c0   feb5d9fea6a5   "/hello"      About an hour ago   Exited (0) About an hour ago              gifted_gould
-aq			只显示id
-n=?		显示指定个数

不关闭容器退出
Ctrl + P + Q

root@Junzhiyuechuan:~# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
root@Junzhiyuechuan:~# docker run -it centos /bin/bash
[root@ef1f56dbabbc /]# root@Junzhiyuechuan:~# docker ps
CONTAINER ID   IMAGE     COMMAND       CREATED         STATUS         PORTS     NAMES
ef1f56dbabbc   centos    "/bin/bash"   9 seconds ago   Up 9 seconds             determined_raman

docker rm

容器的删除

docker rm 容器id # 不能强制删除,当容器正在运行时,不能删除,但是在前面加上参数-f就能强制删除
docker rm -f 容器id

也可以使用分布查询
docker rm -f $()

root@Junzhiyuechuan:~# docker rm -f $(docker ps -aq)
ef1f56dbabbc
b914ab7b0415
778ab3cc308d
c296451a01c0
root@Junzhiyuechuan:~# docker ps -a
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES

也可以使用管道指令

docker ps -aq|xargs docker rm -f

root@Junzhiyuechuan:~# docker run -it centos /bin/bash
[root@abe39337f63d /]# root@Junzhiyuechuan:~# docker ps
CONTAINER ID   IMAGE     COMMAND       CREATED         STATUS         PORTS     NAMES
abe39337f63d   centos    "/bin/bash"   9 seconds ago   Up 9 seconds             strange_brown
root@Junzhiyuechuan:~# docker ps -aq| xargs docker rm -f
abe39337f63d
root@Junzhiyuechuan:~# docker ps -aq

start restart stop kill

开始,重启,停止,杀死

docker start 容器id
docker restart 容器id
docker stop 容器id
docker kull 容器id

docker run 相当于 create + start

4. 其他命令

docker logs

查看容器运行日志

root@Junzhiyuechuan:~# docker logs --help

Usage:  docker logs [OPTIONS] CONTAINER

Fetch the logs of a container

Options:
      --details        Show extra details provided to logs
  -f, --follow         Follow log output
      --since string   Show logs since timestamp (e.g. 2013-01-02T13:23:37Z) or relative (e.g. 42m for 42 minutes)
  -n, --tail string    Number of lines to show from the end of the logs (default "all")
  -t, --timestamps     Show timestamps
      --until string   Show logs before a timestamp (e.g. 2013-01-02T13:23:37Z) or relative (e.g. 42m for 42 minutes)

先写一个脚本,让容器运行

root@Junzhiyuechuan:~# docker ps 
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
root@Junzhiyuechuan:~# docker run -d centos /bin/sh -c "while true; do echo hello;sleep 3;done"
f919a6b690c7614bd1b05732eff485462278bbf899762710477a0ae35a312df6
root@Junzhiyuechuan:~# docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED         STATUS         PORTS     NAMES
f919a6b690c7   centos    "/bin/sh -c 'while t…"   3 seconds ago   Up 3 seconds             clever_murdock
root@Junzhiyuechuan:~# docker logs -tf --tail 10 f919a6b690c7 
2022-09-11T01:45:25.402231128Z hello
2022-09-11T01:45:28.403794310Z hello
2022-09-11T01:45:31.405368148Z hello
2022-09-11T01:45:34.407008185Z hello
2022-09-11T01:45:37.408626289Z hello
2022-09-11T01:45:40.410275800Z hello
2022-09-11T01:45:43.411875519Z hello
2022-09-11T01:45:46.413405275Z hello
2022-09-11T01:45:49.415023680Z hello
2022-09-11T01:45:52.416733623Z hello
2022-09-11T01:45:58.420030060Z hello
2022-09-11T01:46:01.422021942Z hello
2022-09-11T01:46:04.423566956Z hello
2022-09-11T01:46:07.425818350Z hello
^C
root@Junzhiyuechuan:~# 

docker top

查看容器中进程信息
docker top 容器id

root@Junzhiyuechuan:~# docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED         STATUS         PORTS     NAMES
849e4f8eb19f   centos    "/bin/sh -c 'while t…"   3 seconds ago   Up 2 seconds             stoic_meitner
root@Junzhiyuechuan:~# docker top 849e4f8eb19f 
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                194031              194003              0                   09:48               ?                   00:00:00            /bin/sh -c while true; do echo hello;sleep 2;done
root                194231              194031              0                   09:49               ?                   00:00:00            /usr/bin/coreutils --coreutils-prog-shebang=sleep /usr/bin/sleep 2
root@Junzhiyuechuan:~# 

docker inspect

查看容器的详细信息
docker inspect 容器id

root@Junzhiyuechuan:~# docker inspect  849e4f8eb19f
[
    {
        "Id": "849e4f8eb19fe90abc850e224683add61c985ed617fad873fd4495bf22638f86",
        "Created": "2022-09-11T01:48:56.206793326Z",
        "Path": "/bin/sh",
        "Args": [
            "-c",
            "while true; do echo hello;sleep 2;done"
        ],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 194031,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2022-09-11T01:48:56.535800403Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:5d0da3dc976460b72c77d94c8a1ad043720b0416bfc16c52c45d4847e53fadb6",
        "ResolvConfPath": "/var/lib/docker/containers/849e4f8eb19fe90abc850e224683add61c985ed617fad873fd4495bf22638f86/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/849e4f8eb19fe90abc850e224683add61c985ed617fad873fd4495bf22638f86/hostname",
        "HostsPath": "/var/lib/docker/containers/849e4f8eb19fe90abc850e224683add61c985ed617fad873fd4495bf22638f86/hosts",
        "LogPath": "/var/lib/docker/containers/849e4f8eb19fe90abc850e224683add61c985ed617fad873fd4495bf22638f86/849e4f8eb19fe90abc850e224683add61c985ed617fad873fd4495bf22638f86-json.log",
        "Name": "/stoic_meitner",
        "RestartCount": 0,
        "Driver": "overlay2",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "docker-default",
        "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,
            "CgroupnsMode": "host",
            "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/ea6eb5764ef93731048607eef975d047dc1c4a95610ffa28cb574c312fc077b8-init/diff:/var/lib/docker/overlay2/397b7439ae8b5cb7a36125f2c653f3fdc51b3cd41eed0f467cf98cb81e68a4ae/diff",
                "MergedDir": "/var/lib/docker/overlay2/ea6eb5764ef93731048607eef975d047dc1c4a95610ffa28cb574c312fc077b8/merged",
                "UpperDir": "/var/lib/docker/overlay2/ea6eb5764ef93731048607eef975d047dc1c4a95610ffa28cb574c312fc077b8/diff",
                "WorkDir": "/var/lib/docker/overlay2/ea6eb5764ef93731048607eef975d047dc1c4a95610ffa28cb574c312fc077b8/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "849e4f8eb19f",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
            ],
            "Cmd": [
                "/bin/sh",
                "-c",
                "while true; do echo hello;sleep 2;done"
            ],
            "Image": "centos",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": {
                "org.label-schema.build-date": "20210915",
                "org.label-schema.license": "GPLv2",
                "org.label-schema.name": "CentOS Base Image",
                "org.label-schema.schema-version": "1.0",
                "org.label-schema.vendor": "CentOS"
            }
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "e000d42938a288321ce4c71126ccf8b7d816f4cbde18365c7c7371c7abb85b9b",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {},
            "SandboxKey": "/var/run/docker/netns/e000d42938a2",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "b14c49a753020217797824e3baba32e6200902a17194d2e9358b95ef25f007c3",
            "Gateway": "172.18.0.1",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "172.18.0.2",
            "IPPrefixLen": 16,
            "IPv6Gateway": "",
            "MacAddress": "02:42:ac:12:00:02",
            "Networks": {
                "bridge": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "NetworkID": "b887a6302a58ea515071d4b48141d3bf7adc8b30ecb275e9104ab26d7e026b55",
                    "EndpointID": "b14c49a753020217797824e3baba32e6200902a17194d2e9358b95ef25f007c3",
                    "Gateway": "172.18.0.1",
                    "IPAddress": "172.18.0.2",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:ac:12:00:02",
                    "DriverOpts": null
                }
            }
        }
    }
]
root@Junzhiyuechuan:~# ^C

docker exec

进入正在运行的容器
docker exec -it 容器id 默认启动

root@Junzhiyuechuan:~# docker exec -it  849e4f8eb19f /bin/bash
[root@849e4f8eb19f /]# ls
bin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var

docker attach

也是进入正在运行中的容器,但是会进入容器中正在运行中的进程
docker attach 容器id 默认启动

root@Junzhiyuechuan:~# docker attach  849e4f8eb19f 
hello
hello
hello
hello
hello
# 之前写的死循环,无法中断,只能断开连接后,重连,关闭容器

docker cp

拷贝容器文件到系统目录
docker cp 容器id:文件目录 系统目录

# 先进入容器
root@Junzhiyuechuan:~# docker attach a163a01a3b78 
[root@a163a01a3b78 /]# ls
bin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
[root@a163a01a3b78 /]# cd home
[root@a163a01a3b78 home]# ls
# 在容器中的/home文件夹下面创建hello.java文件
[root@a163a01a3b78 home]# touch hello.java
[root@a163a01a3b78 home]# ls
hello.java
# 退出容器
[root@a163a01a3b78 home]# read escape sequence
root@Junzhiyuechuan:~# cd /home
root@Junzhiyuechuan:/home# ls
# 执行cpoy指令,将容器中的文件 拷贝到系统文件夹下面
root@Junzhiyuechuan:/home# docker cp a163a01a3b78:/home/hello.java /home
root@Junzhiyuechuan:/home# ls
hello.java

5. 实战

1. 部署nginx环境

  1. 先到docker hub中搜索 -> docker search nginx
  2. 拉取镜像 -> docker pull nginx
  3. 查看是否安装成功 -> docker images -a
  4. 运行容器 -> docker run -d --name=nginx01 -p 3344:80 nginx
# 1. 先到docker hub中搜索 
root@Junzhiyuechuan:/home# docker search nginx
NAME                                              DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
nginx                                             Official build of Nginx.                        17375     [OK]       
linuxserver/nginx                                 An Nginx container, brought to you by LinuxS…   177                  
bitnami/nginx                                     Bitnami nginx Docker Image                      140                  [OK]
ubuntu/nginx                                      Nginx, a high-performance reverse proxy & we…   58                   
bitnami/nginx-ingress-controller                  Bitnami Docker Image for NGINX Ingress Contr…   19                   [OK]
rancher/nginx-ingress-controller                                                                  11                   
webdevops/nginx                                   Nginx container                                 9                    [OK]
ibmcom/nginx-ingress-controller                   Docker Image for IBM Cloud Private-CE (Commu…   4                    
bitnami/nginx-ldap-auth-daemon                                                                    3                    
rancher/nginx                                                                                     2                    
kasmweb/nginx                                     An Nginx image based off nginx:alpine and in…   2                    
vmware/nginx                                                                                      2                    
rancher/nginx-ingress-controller-defaultbackend                                                   2                    
rapidfort/nginx                                   RapidFort optimized, hardened image for NGINX   2                    
bitnami/nginx-exporter                                                                            2                    
bitnami/nginx-intel                                                                               1                    
wallarm/nginx-ingress-controller                  Kubernetes Ingress Controller with Wallarm e…   1                    
vmware/nginx-photon                                                                               1                    
ibmcom/nginx-ingress-controller-ppc64le           Docker Image for IBM Cloud Private-CE (Commu…   0                    
rancher/nginx-conf                                                                                0                    
rancher/nginx-ssl                                                                                 0                    
rapidfort/nginx-ib                                RapidFort optimized, hardened image for NGIN…   0                    
continuumio/nginx-ingress-ws                                                                      0                    
rancher/nginx-ingress-controller-amd64                                                            0                    
ibmcom/nginx-ppc64le                              Docker image for nginx-ppc64le                  0      
# 2.拉取镜像              
root@Junzhiyuechuan:/home# docker pull nginx
Using default tag: latest
latest: Pulling from library/nginx
7a6db449b51b: Pull complete 
ca1981974b58: Pull complete 
d4019c921e20: Pull complete 
7cb804d746d4: Pull complete 
e7a561826262: Pull complete 
7247f6e5c182: Pull complete 
Digest: sha256:b95a99feebf7797479e0c5eb5ec0bdfa5d9f504bc94da550c2f58e839ea6914f
Status: Downloaded newer image for nginx:latest
docker.io/library/nginx:latest
# 3.查看镜像是否安装成功
root@Junzhiyuechuan:/home# docker images
REPOSITORY   TAG       IMAGE ID       CREATED         SIZE
nginx        latest    2b7d6430f78d   2 weeks ago     142MB
centos       latest    5d0da3dc9764   12 months ago   231MB
# 4. 启动容器
root@Junzhiyuechuan:/home# docker run -d --name nginx01 -p 3344:80 nginx
7583a490d59545a6eb2c576bcf55f002f849efeb8c7aeef85858d6023a394e7c
# 5. 检测是否部署成功
root@Junzhiyuechuan:/home# curl localhost:3344
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
body { width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif; }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>

网页输入ip:3344查看
在这里插入图片描述

2. 部署tomcat环境

  1. 搜索镜像
  2. 拉取镜像
  3. 检查进行
  4. 运行容器
# 搜索镜像
root@Junzhiyuechuan:~# docker search tomcat
NAME                                           DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
tomcat                                         Apache Tomcat is an open source implementati…   3388      [OK]       
tomee                                          Apache TomEE is an all-Apache Java EE certif…   97        [OK]       
bitnami/tomcat                                 Bitnami Tomcat Docker Image                     47                   [OK]
arm32v7/tomcat                                 Apache Tomcat is an open source implementati…   11                   
arm64v8/tomcat                                 Apache Tomcat is an open source implementati…   8                    
rightctrl/tomcat                               CentOS , Oracle Java, tomcat application ssl…   7                    [OK]
amd64/tomcat                                   Apache Tomcat is an open source implementati…   4                    
jelastic/tomcat                                An image of the Tomcat Java application serv…   4                    
tomcat2111/pisignage-server                    PiSignage Server                                3                    [OK]
cfje/tomcat-resource                           Tomcat Concourse Resource                       2                    
oobsri/tomcat8                                 Testing CI Jobs with different names.           2                    
ppc64le/tomcat                                 Apache Tomcat is an open source implementati…   1                    
chenyufeng/tomcat-centos                       tomcat基于centos6的镜像                              1                    [OK]
appsvc/tomcat                                                                                  1                    
wnprcehr/tomcat                                                                                0                    
softwareplant/tomcat                           Tomcat images for jira-cloud testing            0                    [OK]
tomcat0823/auto1                                                                               0                    
tomcat2111/papercut-mf                         PaperCut MF Application Server                  0                    
secoresearch/tomcat-varnish                    Tomcat and Varnish 5.0                          0                    [OK]
s390x/tomcat                                   Apache Tomcat is an open source implementati…   0                    
tomcat2111/phpredisadmin                       This is a Docker image for phpredisadmin        0                    [OK]
misolims/miso-base                             MySQL 5.7 Database and Tomcat 8 Server neede…   0                    
semoss/docker-tomcat                           Tomcat, Java, Maven, and Git on top of debian   0                    [OK]
tomcat2111/bitbucket-pipelines-elasticsearch   Elasticsearch for Bitbucket's Pipelines         0                    
tomcatengineering/pg_backup_rotated            Clone of martianrock/pg_backup_rotated but w…   0   
# 拉取镜像                 
root@Junzhiyuechuan:~# docker pull tomcat
Using default tag: latest
latest: Pulling from library/tomcat
2b55860d4c66: Pull complete 
49a58ffb4a94: Pull complete 
8889343dc9d4: Pull complete 
5c321d92dfdb: Pull complete 
65e12e19b4c9: Pull complete 
31c5670ba66a: Pull complete 
4196dee71f9b: Pull complete 
Digest: sha256:bb81645575fef90e48e6f9fff50e06d5b78d4ac9d2683845401164ba1ddfe199
Status: Downloaded newer image for tomcat:latest
docker.io/library/tomcat:latest
# 查看是否安装成功
root@Junzhiyuechuan:~# docker images -a
REPOSITORY   TAG       IMAGE ID       CREATED         SIZE
tomcat       latest    7a91e6f458bb   9 days ago      475MB
nginx        latest    2b7d6430f78d   2 weeks ago     142MB
centos       latest    5d0da3dc9764   12 months ago   231MB
# 运行容器
root@Junzhiyuechuan:~# docker run -d --name tomcat01 -p 3355:8080 tomcat
62b39bc6e6e1356f3d2512cc160b812e2659d5b2452120ae4c576ea5ada7c5f0

在浏览器输入ip:3355查看
在这里插入图片描述
进入容器查看webapps

root@Junzhiyuechuan:~# docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED         STATUS         PORTS                                       NAMES
62b39bc6e6e1   tomcat    "catalina.sh run"        2 minutes ago   Up 2 minutes   0.0.0.0:3355->8080/tcp, :::3355->8080/tcp   tomcat01
7583a490d595   nginx     "/docker-entrypoint.…"   22 hours ago    Up 22 hours    0.0.0.0:3344->80/tcp, :::3344->80/tcp       nginx01
a163a01a3b78   centos    "/bin/bash"              22 hours ago    Up 22 hours                                                distracted_davinci
root@Junzhiyuechuan:~# docker exec -it 62b39bc6e6e1 /bin/bash
root@62b39bc6e6e1:/usr/local/tomcat# ls
bin  BUILDING.txt  conf  CONTRIBUTING.md  lib  LICENSE  logs  native-jni-lib  NOTICE  README.md  RELEASE-NOTES  RUNNING.txt  temp  webapps  webapps.dist  work
root@62b39bc6e6e1:/usr/local/tomcat# cd webapps
root@62b39bc6e6e1:/usr/local/tomcat/webapps# ls
root@62b39bc6e6e1:/usr/local/tomcat/webapps# cd ..
root@62b39bc6e6e1:/usr/local/tomcat# cd webapps.dist
root@62b39bc6e6e1:/usr/local/tomcat/webapps.dist# ls
docs  examples  host-manager  manager  ROOT
root@62b39bc6e6e1:/usr/local/tomcat/webapps.dist# 

观察到webapps中不含有应用程序,webapps.dist中含有,将其复制到webapps文件夹中即可

root@62b39bc6e6e1:/usr/local/tomcat/webapps.dist# cd ../
root@62b39bc6e6e1:/usr/local/tomcat# cp -r webapps.dist/* webapps
root@62b39bc6e6e1:/usr/local/tomcat# cd webapps
root@62b39bc6e6e1:/usr/local/tomcat/webapps# ls
docs  examples  host-manager  manager  ROOT

再次刷新网页
在这里插入图片描述
显示成功

6. 生成镜像

将容器生成为本地的一个镜像,方便下次直接运行镜像为容器

分层思想

当pull一个镜像的时候,是分层下载的,docker hub上的镜像都是通过容器生成的,最开始的容器就是一层简单的linux内核,然后再上面添加新的层,从而构建不同的镜像
例如:
执行 docker inspect指令可以查看镜像的详细信息,这里看到tomcat镜像就是7层的结构
在这里插入图片描述
当执行run指令时,是再当前镜像的前提下,再上面重新创建一层,用户在创建层中进行修改从而做到自己的镜像。
当pull不同的镜像时,用到了同一层,则第二次就不会再次下载,因为在run镜像的时候,镜像中的其他层是只读状态,用户仅仅在创建层进行修改

docker commit

将容器打包成镜像

root@Junzhiyuechuan:~# docker commit --help

Usage:  docker commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]

Create a new image from a container's changes

Options:
  -a, --author string    Author (e.g., "John Hannibal Smith <hannibal@a-team.com>")
  -c, --change list      Apply Dockerfile instruction to the created image
  -m, --message string   Commit message
  -p, --pause            Pause container during commit (default true)

docker commit -m="提交的信息" -a="作者“ 容器id 镜像别名

root@Junzhiyuechuan:~# docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED        STATUS        PORTS                                       NAMES
62b39bc6e6e1   tomcat    "catalina.sh run"        7 hours ago    Up 7 hours    0.0.0.0:3355->8080/tcp, :::3355->8080/tcp   tomcat01
7583a490d595   nginx     "/docker-entrypoint.…"   29 hours ago   Up 29 hours   0.0.0.0:3344->80/tcp, :::3344->80/tcp       nginx01
a163a01a3b78   centos    "/bin/bash"              29 hours ago   Up 29 hours                                               distracted_davinci
root@Junzhiyuechuan:~# docker commit -m="copy file to webapp" -a="junzhiyuechuan" 62b39bc6e6e1 selftomcat
sha256:7f6d8bb914c935faaec3d1b686dec4bfbcc5ce58dfb12f73eaee3e99d6960614
root@Junzhiyuechuan:~# docker images
REPOSITORY   TAG       IMAGE ID       CREATED         SIZE
selftomcat   latest    7f6d8bb914c9   5 seconds ago   480MB
tomcat       latest    7a91e6f458bb   9 days ago      475MB
nginx        latest    2b7d6430f78d   2 weeks ago     142MB
centos       latest    5d0da3dc9764   12 months ago   231MB

查看一下自己创建的新的容器的层数
在这里插入图片描述
这里就有8层,和上面的7层做下比较,就是因为我在原先的tomcat镜像下面重新拷贝了文件,所以就会新创建一个层用于用户的操作。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值