docker常用命令及镜像的制作与上传

安装docker

docker安装

docker加速

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

docker的加速有多种方式:

docker cn

systemctl start docker

cat > /etc/docker/daemon.json <<EOF
{
    "registry-mirrors": ["https://registry.docker-cn.com"]
}
EOF

systemctl restart docker

docker version
docker info

中国科技大学加速器

阿里云加速器(需要通过阿里云开发者平台注册帐号,免费使用个人私有的加速器)

sudo mkdir -p /etc/docker
sudo tee /etc/docker/daemon.json <<-'EOF'
{
  "registry-mirrors": ["https://ex1lszu3.mirror.aliyuncs.com"]
}
EOF
sudo systemctl daemon-reload
sudo systemctl restart docker

docker常用操作

docker search
查找镜像

[root@localhost ~]# docker search nginx
NAME                               DESCRIPTION                                     STARS               OFFICIAL            AUTOMATED
nginx                              Official build of Nginx.                        13666               [OK]                
jwilder/nginx-proxy                Automated Nginx reverse proxy for docker con…   1866                                    [OK]
richarvey/nginx-php-fpm            Container running Nginx + PHP-FPM capable of…   782                                     [OK]
linuxserver/nginx                  An Nginx container, brought to you by LinuxS…   127                                     
bitnami/nginx                      Bitnami nginx Docker Image                      89                                      [OK]
tiangolo/nginx-rtmp                Docker image with Nginx using the nginx-rtmp…   88                                      [OK]
jc21/nginx-proxy-manager           Docker container for managing Nginx proxy ho…   82                                      
alfg/nginx-rtmp                    NGINX, nginx-rtmp-module and FFmpeg from sou…   75                                      [OK]
nginxdemos/hello                   NGINX webserver that serves a simple page co…   59                                      [OK]
jlesage/nginx-proxy-manager        Docker container for Nginx Proxy Manager        53                                      [OK]
nginx/nginx-ingress                NGINX Ingress Controller for Kubernetes         40                                      
privatebin/nginx-fpm-alpine        PrivateBin running on an Nginx, php-fpm & Al…   32                                      [OK]
schmunk42/nginx-redirect           A very simple container to redirect HTTP tra…   19                                      [OK]
nginxinc/nginx-unprivileged        Unprivileged NGINX Dockerfiles                  17                                      
nginx/nginx-prometheus-exporter    NGINX Prometheus Exporter                       15                                      
centos/nginx-112-centos7           Platform for running nginx 1.12 or building …   14                                      
raulr/nginx-wordpress              Nginx front-end for the official wordpress:f…   13                                      [OK]
centos/nginx-18-centos7            Platform for running nginx 1.8 or building n…   13                                      
mailu/nginx                        Mailu nginx frontend                            7                                       [OK]
sophos/nginx-vts-exporter          Simple server that scrapes Nginx vts stats a…   7                                       [OK]
bitwarden/nginx                    The Bitwarden nginx web server acting as a r…   7                                       
navidonskis/nginx-php5.6           Docker nginx + php5.6 on Ubuntu                 7                                       [OK]
bitnami/nginx-ingress-controller   Bitnami Docker Image for NGINX Ingress Contr…   6                                       [OK]
wodby/nginx                        Generic nginx                                   1                                       [OK]
ansibleplaybookbundle/nginx-apb    An APB to deploy NGINX                          1                                       [OK]

docker pull
将镜像拉出来

[root@localhost ~]# docker pull nginx
Using default tag: latest
latest: Pulling from library/nginx
bf5952930446: Pull complete 
cb9a6de05e5a: Pull complete 
9513ea0afb93: Pull complete 
b49ea07d2e93: Pull complete 
a5e4a503d449: Pull complete 
Digest: sha256:b0ad43f7ee5edbc0effbc14645ae7055e21bc1973aee5150745632a24a752661
Status: Downloaded newer image for nginx:latest
docker.io/library/nginx:latest

docker images
查看拉出来的镜像

[root@localhost ~]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
nginx               latest              4bb46517cac3        2 weeks ago         133MB

docker create
创建一个容器,并将容器命名为nginx0

[root@localhost ~]# docker create --name nginx0 nginx
c3ed5d5b1b6df8afccb8fa6f1fa243935571cdfb3d3f8275ab14069b3f9de208
[root@localhost ~]# docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                   NAMES
c3ed5d5b1b6d        nginx               "/docker-entrypoint.…"   9 seconds ago       Created                                     nginx0
3f346ef93702        nginx               "/docker-entrypoint.…"   23 minutes ago      Up 23 minutes       0.0.0.0:32768->80/tcp   xenodochial_buck
ac3814f95190        nginx               "/docker-entrypoint.…"   27 minutes ago      Up 27 minutes       80/tcp                  mynginx

docker run

-a stdin: 指定标准输入输出内容类型,可选 STDIN/STDOUT/STDERR 三项;
-i: 以交互模式运行容器,通常与 -t 同时使用;
-t: 为容器重新分配一个伪输入终端,通常与 -i 同时使用;
-d: 后台运行容器,并返回容器 ID;
-P: 映射一个随机的端口到内部容器开放的网络端口
-p: 指定端口映射,格式为:主机 (宿主) 端口:容器端口
-m : 设置容器使用内存最大值;
–name=“nginx-lb”: 为容器指定一个名称;
-h “mars”: 指定容器的 hostname;
–env-file=[]: 从指定文件读入环境变量;
–cpuset=“0-2” or --cpuset=“0,1,2”: 绑定容器到指定 CPU 运行;
–net=“bridge”: 指定容器的网络连接类型,支持 bridge/host/none/container: 四种类型;
–link=[]: 添加链接到另一个容器
–expose=[]: 开放一个端口或一组端口;
–volume , -v 绑定一个卷
–dns 8.8.8.8: 指定容器使用的 DNS 服务器,默认和宿主一致

#启动一个容器,并将容器命名为mynginx
[root@localhost ~]# docker run --name mynginx -d nginx
ac3814f951908314ec0200e6cd555afb817696deae75fb4c778e99fec38e08cb
[root@localhost ~]# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS               NAMES
ac3814f95190        nginx               "/docker-entrypoint.…"   2 minutes ago       Up About a minute   80/tcp              mynginx
#启动一个容器,并将容器的 80 端口映射到主机随机端口。本机IP:32768即可访问容器的80
[root@localhost ~]# docker run -P -d nginx
3f346ef937021d354d10dccd8b69531c6cd4b782c0b3dae7e010afc84f705a4d
[root@localhost ~]# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                   NAMES
3f346ef93702        nginx               "/docker-entrypoint.…"   6 seconds ago       Up 5 seconds        0.0.0.0:32768->80/tcp   xenodochial_buck
#启动一个容器,将容器的 80 端口映射到主机的 80 端口,主机的目录 /data 映射到容器的 /data
[root@localhost ~]# docker run -p 80:80 -v /data:/data -d nginx
b50b4f20049970b0a58359354ed08f7cabd00d6122d1b07b51c746351d1fc001
[root@localhost ~]# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                   NAMES
b50b4f200499        nginx               "/docker-entrypoint.…"   11 seconds ago      Up 10 seconds       0.0.0.0:80->80/tcp      focused_faraday
[root@localhost ~]# ss -antl
State      Recv-Q Send-Q                   Local Address:Port                                  Peer Address:Port              
LISTEN     0      128                                  *:111                                              *:*                  
LISTEN     0      5                        192.168.122.1:53                                               *:*                  
LISTEN     0      128                                  *:22                                               *:*                  
LISTEN     0      128                          127.0.0.1:631                                              *:*                  
LISTEN     0      100                          127.0.0.1:25                                               *:*                  
LISTEN     0      128                          127.0.0.1:6010                                             *:*                  
LISTEN     0      128                                 :::32768                                           :::*                  
LISTEN     0      128                                 :::111                                             :::*                  
LISTEN     0      128                                 :::80                                              :::*                  
LISTEN     0      128                                 :::22                                              :::*                  
LISTEN     0      128                                ::1:631                                             :::*                  
LISTEN     0      100                                ::1:25                                              :::*                  
LISTEN     0      128                                ::1:6010                                            :::* 

docker stop
停掉一个容器

[root@localhost ~]# docker stop b50b4f200499
b50b4f200499

docker start
启动一个停掉的容器

[root@localhost ~]# docker start b50b4f200499
b50b4f200499

docker restart
重启一个容器

[root@localhost ~]# docker restart b50b4f200499
b50b4f200499

docker kill
杀掉一个正在运行的容器

[root@localhost ~]# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                   NAMES
b50b4f200499        nginx               "/docker-entrypoint.…"   6 minutes ago       Up About a minute   0.0.0.0:80->80/tcp      focused_faraday
3f346ef93702        nginx               "/docker-entrypoint.…"   10 minutes ago      Up 10 minutes       0.0.0.0:32768->80/tcp   xenodochial_buck
ac3814f95190        nginx               "/docker-entrypoint.…"   14 minutes ago      Up 14 minutes       80/tcp                  mynginx
[root@localhost ~]# docker kill b50b4f200499
b50b4f200499
[root@localhost ~]# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                   NAMES
3f346ef93702        nginx               "/docker-entrypoint.…"   10 minutes ago      Up 10 minutes       0.0.0.0:32768->80/tcp   xenodochial_buck
ac3814f95190        nginx               "/docker-entrypoint.…"   14 minutes ago      Up 14 minutes       80/tcp                  mynginx

docker rm
删掉一个或多个停止的容器,加 -f 可以强制删除正在运行的

[root@localhost ~]# docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                       PORTS                   NAMES
b50b4f200499        nginx               "/docker-entrypoint.…"   9 minutes ago       Exited (137) 2 minutes ago                           focused_faraday
3f346ef93702        nginx               "/docker-entrypoint.…"   12 minutes ago      Up 12 minutes                0.0.0.0:32768->80/tcp   xenodochial_buck
ac3814f95190        nginx               "/docker-entrypoint.…"   16 minutes ago      Up 16 minutes                80/tcp                  mynginx
[root@localhost ~]# docker rm b50b4f200499
b50b4f200499
[root@localhost ~]# docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                   NAMES
3f346ef93702        nginx               "/docker-entrypoint.…"   13 minutes ago      Up 13 minutes       0.0.0.0:32768->80/tcp   xenodochial_buck
ac3814f95190        nginx               "/docker-entrypoint.…"   18 minutes ago      Up 18 minutes       80/tcp                  mynginx

#加-q 仅显示容器ID,可以通过这种来删除所有

```bash
[root@localhost ~]# docker ps -a -q
3f346ef93702
ac3814f95190
[root@localhost ~]# docker rm $(docker ps -a -q)

**docker pause**
暂停容器中所有的进程

```bash
[root@localhost ~]# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                   NAMES
3f346ef93702        nginx               "/docker-entrypoint.…"   19 minutes ago      Up 19 minutes       0.0.0.0:32768->80/tcp   xenodochial_buck
ac3814f95190        nginx               "/docker-entrypoint.…"   23 minutes ago      Up 23 minutes       80/tcp                  mynginx
[root@localhost ~]# docker pause 3f346ef93702
3f346ef93702
[root@localhost ~]# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                   PORTS                   NAMES
3f346ef93702        nginx               "/docker-entrypoint.…"   19 minutes ago      Up 19 minutes (Paused)   0.0.0.0:32768->80/tcp   xenodochial_buck
ac3814f95190        nginx               "/docker-entrypoint.…"   23 minutes ago      Up 23 minutes            80/tcp                  mynginx

**docker unpause **
恢复容器中所有的进程

[root@localhost ~]# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                   PORTS                   NAMES
3f346ef93702        nginx               "/docker-entrypoint.…"   19 minutes ago      Up 19 minutes (Paused)   0.0.0.0:32768->80/tcp   xenodochial_buck
ac3814f95190        nginx               "/docker-entrypoint.…"   23 minutes ago      Up 23 minutes            80/tcp                  mynginx
[root@localhost ~]# docker unpause 3f346ef93702
3f346ef93702
[root@localhost ~]# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                   NAMES
3f346ef93702        nginx               "/docker-entrypoint.…"   20 minutes ago      Up 20 minutes       0.0.0.0:32768->80/tcp   xenodochial_buck
ac3814f95190        nginx               "/docker-entrypoint.…"   24 minutes ago      Up 24 minutes       80/tcp                  mynginx

docker exec
在一个容器中运行新的命令
在容器mynginx中以交互模式执行容器内 /root/runoob.sh 脚本:

docker exec -it mynginx /bin/sh /root/runoob.sh

docker ps
查看容器

-a : 显示所有的容器,包括未运行的。
-f : 根据条件过滤显示的内容。
–format : 指定返回值的模板文件。
-l : 显示最近创建的容器。
-n : 列出最近创建的 n 个容器。
–no-trunc : 不截断输出。
-q : 静默模式,只显示容器编号。
-s : 显示总的文件大小。

docker info
查看系统的信息

[root@localhost ~]# docker info
Client:
 Debug Mode: false

Server:
 Containers: 3
  Running: 2
  Paused: 0
  Stopped: 1
 Images: 1
 Server Version: 19.03.12
 Storage Driver: overlay2
  Backing Filesystem: xfs
  Supports d_type: true
  Native Overlay Diff: true
 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: 7ad184331fa3e55e52b890ea95e65ba581ae3429
 runc version: dc9208a3303feef5b3839f4323d9beb36df0a9dd
 init version: fec3683
 Security Options:
  seccomp
   Profile: default
 Kernel Version: 3.10.0-862.el7.x86_64
 Operating System: CentOS Linux 7 (Core)
 OSType: linux
 Architecture: x86_64
 CPUs: 1
 Total Memory: 974.6MiB
 Name: localhost.localdomain
 ID: SHR6:5QHD:IW3I:JONK:RQCO:2H3A:5T2M:DSXT:RV2R:WUVP:H6LH:77N2
 Docker Root Dir: /var/lib/docker
 Debug Mode: false
 Registry: https://index.docker.io/v1/
 Labels:
 Experimental: false
 Insecure Registries:
  127.0.0.0/8
 Registry Mirrors:
  https://ex1lszu3.mirror.aliyuncs.com/
 Live Restore Enabled: false

docker inspect
查看容器的详细信息

-f : 指定返回值的模板文件。
-s : 显示总的文件大小。
–type : 为指定类型返回 JSON

[root@localhost ~]# docker inspect mynginx
[
    {
        "Id": "ac3814f951908314ec0200e6cd555afb817696deae75fb4c778e99fec38e08cb",
        "Created": "2020-08-28T03:25:47.602665171Z",
        "Path": "/docker-entrypoint.sh",
        "Args": [
            "nginx",
            "-g",
            "daemon off;"
        ],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 6493,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2020-08-28T03:25:48.495001069Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:4bb46517cac397bdb0bab6eba09b0e1f8e90ddd17cf99662997c3253531136f8",
        "ResolvConfPath": "/var/lib/docker/containers/ac3814f951908314ec0200e6cd555afb817696deae75fb4c778e99fec38e08cb/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/ac3814f951908314ec0200e6cd555afb817696deae75fb4c778e99fec38e08cb/hostname",
        "HostsPath": "/var/lib/docker/containers/ac3814f951908314ec0200e6cd555afb817696deae75fb4c778e99fec38e08cb/hosts",
        "LogPath": "/var/lib/docker/containers/ac3814f951908314ec0200e6cd555afb817696deae75fb4c778e99fec38e08cb/ac3814f951908314ec0200e6cd555afb817696deae75fb4c778e99fec38e08cb-json.log",
        "Name": "/mynginx",
        "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/fcc197029392d2b185cc3b0fe090bdbc7dd1e1b69e71cadff20b782de8598b78-init/diff:/var/lib/docker/overlay2/817e10f3c52220fb1cf7572f47d475f9b736cd1e363eb850c16b412c7dd90684/diff:/var/lib/docker/overlay2/b159f86de5b5c10633397dd716b17c376e90911fc5e559652680eb687a671dd5/diff:/var/lib/docker/overlay2/1f5b8fce11c74c0f5105f5836db8ef6e916913464050ac89950cbd7eedf4823e/diff:/var/lib/docker/overlay2/89c80c1722c78da74e74f5ca4845903a4ae9729f222b0d55f7e87cf5151496dd/diff:/var/lib/docker/overlay2/99154bc25940ed346e8b3c7e4d8ee3163053624c41e546b01c052a40bbbe2d06/diff",
                "MergedDir": "/var/lib/docker/overlay2/fcc197029392d2b185cc3b0fe090bdbc7dd1e1b69e71cadff20b782de8598b78/merged",
                "UpperDir": "/var/lib/docker/overlay2/fcc197029392d2b185cc3b0fe090bdbc7dd1e1b69e71cadff20b782de8598b78/diff",
                "WorkDir": "/var/lib/docker/overlay2/fcc197029392d2b185cc3b0fe090bdbc7dd1e1b69e71cadff20b782de8598b78/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "ac3814f95190",
            "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.19.2",
                "NJS_VERSION=0.4.3",
                "PKG_RELEASE=1~buster"
            ],
            "Cmd": [
                "nginx",
                "-g",
                "daemon off;"
            ],
            "Image": "nginx",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": [
                "/docker-entrypoint.sh"
            ],
            "OnBuild": null,
            "Labels": {
                "maintainer": "NGINX Docker Maintainers <docker-maint@nginx.com>"
            },
            "StopSignal": "SIGTERM"
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "728830f025e21baff937d301c8c758a4626138ea6b885b81469542121e483a08",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {
                "80/tcp": null
            },
            "SandboxKey": "/var/run/docker/netns/728830f025e2",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "a89ac3c1bb6d6f80b1846efaa16e00b93bcfb7a7cb7abdbbd4e3bfde368c709e",
            "Gateway": "172.17.0.1",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "172.17.0.2",
            "IPPrefixLen": 16,
            "IPv6Gateway": "",
            "MacAddress": "02:42:ac:11:00:02",
            "Networks": {
                "bridge": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "NetworkID": "9ee185db7964b3443516a1d4d0c50ccad1b4ded0c7c4849ea6e08d64633567c8",
                    "EndpointID": "a89ac3c1bb6d6f80b1846efaa16e00b93bcfb7a7cb7abdbbd4e3bfde368c709e",
                    "Gateway": "172.17.0.1",
                    "IPAddress": "172.17.0.2",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:ac:11:00:02",
                    "DriverOpts": null
                }
            }
        }
    }
]

docker top
查看容器中运行的进程信息,支持 ps 命令参数。只有在运行中的容器才能使用这个命令

[root@localhost ~]# docker top mynginx
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                6493                6476                0                   20:25               ?                   00:00:00            nginx: master process nginx -g daemon off;
101                 6541                6493                0                   20:25               ?                   00:00:00            nginx: worker process

docker attach
连接到正在运行中的容器

[root@localhost ~]# docker attach nginx001

docker logs
获取容器运行的日志

**-f : ** 跟踪日志输出
–since : 显示某个开始时间的所有日志
**-t : ** 显示时间戳
–tail : 仅列出最新 N 条容器日志

[root@localhost ~]# docker logs mynginx
/docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
/docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
/docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
10-listen-on-ipv6-by-default.sh: Getting the checksum of /etc/nginx/conf.d/default.conf
10-listen-on-ipv6-by-default.sh: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf
/docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
/docker-entrypoint.sh: Configuration complete; ready for start up

docker wait
:阻塞运行直到容器停止,然后打印出它的退出代码

[root@localhost ~]# docker wait mynginx
0

docker镜像的制作

多数情况下,我们做镜像是基于别人已存在的某个基础镜像来实现的,我们把它称为base image。比如一个纯净版的最小化的centos、ubuntu或debian。

那么这个最小化的centos镜像从何而来呢?其实这个基础镜像一般是由Docker Hub的相关维护人员,也就是Docker官方手动制作的。这个基础镜像的制作对于Docker官方的专业人员来说是非常容易的,但对于终端用户来说就不是那么容易制作的了。

Docker Hub

Docker Hub is a cloud-based registry service which allows you to link to code repositories, build your images and test them, stores manually pushed images, and links to Docker Cloud so you can deploy images to your hosts.

It provides a centralized resource for container image discovery, distribution and change management, user and team collaboration, and workflow automation throughout the development pipeline.
在这里插入图片描述
Docker Hub provides the following major features:

Image Repositories
Find and pull images from community and official libraries, and manage, push to, and pull from private images libraries to which you have access.
Automated Builds
Automatically create new images when you make changes to a source code repository.
Webhooks
A feature of Automated Builds, Webhooks let you trigger actions after a successful push to a - repository.
Organizations
Create work groups to manage access to image repositories.
GitHub and Bitbucket Integration
Add the Hub and your Docker Images to your current workflows.
docker镜像的获取

To get Docker images from a remote registry(such as your own Docker registry)and add them to your local system, use the docker pull command:

# docker pull <registry>[:<port>]/[<namespace>/]<name>:<tag>

The is a host that provides the docker-distribution service on TCP (default:5000)

Together, and identify a particular image controlled by at the registry

Some registries also support raw ;for those, is optional
When it is included, however, the additional level of hierarchy that provides is usefull to distinguish between images with the same
The additional level of hierarchy of

NamespaceExample(snamespace>/<name)
organizationredhat/kubernetes, google/kubernetes
login(username)Alice/application, bob/application
roledevel/database, test/database, prod/database

镜像的生成
镜像的生成途径:

Dockerfile
基于容器制作
Docker Hub automated builds
在这里插入图片描述
基于容器制作镜像

Create a new image from container’s changes

Usage:

docker commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]
OptionsDefaultDescription
—author, -aAuthor (e.g., “John Hannibal Smith hannibal@a-team.com”)
-c, --change listApply Dockerfile instruction to the created image
-m, --message stringCommit message
-p, --pausetruePause container during commit
[root@localhost ~]# docker pull busybox
Using default tag: latest
latest: Pulling from library/busybox
61c5ed1cbdf8: Pull complete 
Digest: sha256:4f47c01fa91355af2865ac10fef5bf6ec9c7f42ad2321377c21e844427972977
Status: Downloaded newer image for busybox:latest
docker.io/library/busybox:latest
[root@localhost ~]#  docker run -it --name b1 busybox
WARNING: IPv4 forwarding is disabled. Networking will not work.
/ # mkdir /data
/ #  echo 'test page.' > /data/index.html
/ # cat /data/index.html 
test page.
/ # 

在创建镜像时,我们不能关闭容器,必须使其处于运行状态,所以我们必须要另起一个终端,然后执行

[root@localhost ~]# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED              STATUS              PORTS               NAMES
baa7b0201b08        busybox             "sh"                About a minute ago   Up About a minute                       b1
[root@localhost ~]# docker commit -p baa7b0201b08 
sha256:8da607c67a3edf5dca308d3a187d85734db5599d6ade4799efa1c8b90a348b69
[root@localhost ~]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
<none>              <none>              8da607c67a3e        10 seconds ago      1.22MB
httpd               latest              a6ea92c35c43        3 weeks ago         166MB
busybox             latest              018c9d7b792b        4 weeks ago         1.22MB
[root@localhost ~]# docker tag 8da607c67a3e dockerlei123/b1:v0.1
[root@localhost ~]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED              SIZE
dockerlei123/b1     v0.1                8da607c67a3e        About a minute ago   1.22MB
httpd               latest              a6ea92c35c43        3 weeks ago          166MB
busybox             latest              018c9d7b792b        4 weeks ago          1.22MB

此时要注意的是,我们的仓库名叫b1,所以我们要在Docker Hub上创建一个名为b1的仓库,然后再将我们做好的镜像push上去
在这里插入图片描述
在这里插入图片描述
看到上图表示创建成功

[root@localhost ~]# docker login 
Login with your Docker ID to push and pull images from Docker Hub. If you don't have a Docker ID, head over to https://hub.docker.com to create one.
Username: dockerlei123
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@localhost ~]# docker push dockerlei123/b1:v0.1
The push refers to repository [docker.io/dockerlei123/b1]
99cd394fe45a: Pushed 
514c3a3e64d4: Mounted from library/busybox 
v0.1: digest: sha256:c91f817b24f91022c59a5b6f9262a0e5b10e7af662446b6bb9525c3b927253b8 size: 734

在这里插入图片描述
使用新生成的镜像创建容器

[root@localhost ~]# docker run --name t1 -it dockerlei123/b1:v0.1
WARNING: IPv4 forwarding is disabled. Networking will not work.
/ # ls
bin   dev   home  root  tmp   var
data  etc   proc  sys   usr
/ # cat /data/index.html 
test page.

由此可见,新生成的镜像中是包含了新增的内容的,但是此时有一个问题,那就是容器默认要启动的进程是什么?在这里,默认情况下是启动的sh进程,但我们是要启动一个apache站点,所以我们要在创建镜像时将容器默认启动的进程设为httpd,这样一来我们就可以通过新生成的镜像来快速构建一个简单的apache站点了。
使用docker inspect命令查看apache容器启动的默认进程是什么

[root@localhost ~]# docker inspect b1

           ],
            "Cmd": [
                "sh"
            ],
            "Image": "busybox",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": {}
        },

重新生成镜像并上传

[root@localhost ~]# docker commit -p -c 'CMD ["/bin/httpd","-f","-h","/data"]' b1 dockerlei123/b1:v0.2
sha256:67ce2ee1a9da2a6eb99b57c18f7e19407f0ad6d8bba72ae9f0bc67f6f0a277dd
[root@localhost ~]# docker push dockerlei123/b1

使用新生成的镜像创建容器

[root@localhost ~]# docker run --name b2 -d dockerlei123/b1:v0.2
WARNING: IPv4 forwarding is disabled. Networking will not work.
68c9e09a970718bc9f6b8c01da428208ef72966f4e076ba1044fa785fb13393b
[root@localhost ~]#  docker ps
CONTAINER ID        IMAGE                  COMMAND                  CREATED             STATUS              PORTS               NAMES
68c9e09a9707        dockerlei123/b1:v0.2   "/bin/httpd -f -h /d…"   10 seconds ago      Up 9 seconds                            b2
baa7b0201b08        busybox                "sh"                     18 minutes ago      Up 18 minutes 

使用docker inspect命令查看t2容器启动的默认进程是什么,以及其IP地址,然后用curl命令访问该IP,看是否能访问到网页

[root@localhost ~]# docker inspect b2
  "Cmd": [
                "/bin/httpd",
                "-f",
                "-h",
                "/data"
"IPAddress": "172.17.0.3",

[root@localhost ~]# curl 172.17.0.3
test page.

镜像的导入与导出

假如有2台主机,我们在主机1上做了一个镜像,主机2想用这个镜像怎么办呢?

我们可以在主机1上push镜像到镜像仓库中,然后在主机2上pull把镜像拉下来使用,这种方式就显得比较麻烦,假如我只是测试用的,在一台主机上做好镜像后在另一台主机上跑一下就行了,没必要推到仓库上然后又把它拉到本地来。

此时我们可以在已有镜像的基础上把镜像打包成一个压缩文件,然后拷贝到另一台主机上将其导入,这就是镜像的导入和导出功能。

docker中我们使用docker save进行导出,使用docker load进行导入。

在已生成镜像的主机上执行docker save导出镜像

[root@localhost ~]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
dockerlei123/b1     v0.2                67ce2ee1a9da        6 minutes ago       1.22MB
dockerlei123/b1     v0.1                8da607c67a3e        20 minutes ago      1.22MB
httpd               latest              a6ea92c35c43        3 weeks ago         166MB
busybox             latest              018c9d7b792b        4 weeks ago         1.22MB
[root@localhost ~]#  docker save -o httpd dockerlei123/b1
[root@localhost ~]# ls
anaconda-ks.cfg  httpd

执行docker load导入镜像

[root@localhost ~]#  docker load -i /root/httpd
Loaded image: dockerlei123/b1:v0.1
Loaded image: dockerlei123/b1:v0.2

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值