docker 创建容器与管理容器

创建容器的选项

[root@mast ~]# docker container run --help

Usage:	docker container 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
      --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
      --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
      --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 string                 Connect a container to a network (default "default")
      --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)
      --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
      --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

  启动一个容器并在前台运行

[root@localhost ~]# docker run -it centos /bin/bash
[root@4279c14287c1 /]# 

  后台创建一个容器

[root@localhost ~]# docker run -d centos 
53dfa07e6f2c1f514cfe04c7943790692dd385e920ba56561c5b82160089fb33
[root@localhost ~]# docker ps -l
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                     PORTS               NAMES
53dfa07e6f2c        centos              "/bin/bash"         3 seconds ago       Exited (0) 2 seconds ago                       unruffled_pare

  创建容器并设置端口映射-p 将容器端口映射成指定端口

[root@localhost ~]# docker run --name web -d -e test=123 -p 88:80  -h web  nginx  
d2394de6c3a11151bfc1697493a8012a132763b2bfa045b55d7f657704e47f6f
[root@localhost ~]# docker ps -l
CONTAINER ID        IMAGE               COMMAND                  CREATED           
  STATUS              PORTS                NAMESd2394de6c3a1        nginx               "nginx -g 'daemon of…"   15 seconds ago   
   Up 11 seconds       0.0.0.0:88->80/tcp   web[root@localhost ~]# ss -lntp
State       Recv-Q Send-Q                                                  Local Address:Port                                                                 Peer Address:Port              
LISTEN      0      128                                                                 *:22                                                                              *:*                   
users:(("sshd",pid=921,fd=3))LISTEN      0      100                                                         127.0.0.1:25                                                                              *:*                   
users:(("master",pid=1310,fd=13))LISTEN      0      128                                                                :::22                                                                             :::*                   
users:(("sshd",pid=921,fd=4))LISTEN      0      128                                                                :::88                                                                             :::*                   
users:(("docker-proxy",pid=19507,fd=4))LISTEN      0      100                                                               ::1:25                                                                             :::*                   
users:(("master",pid=1310,fd=14))

  进入后台运行的容器 

[root@localhost ~]# docker exec -it web bash
root@web:/# 

  将容器端口映射成随机的端口 -P

[root@localhost ~]# docker run -d --name web-1 -e test=chenxi -P -h cx nginx
a3bdc2062cd738acc717da093c5de736c2170d88a9fd310e0c0de0c20fdb855f
[root@localhost ~]# ss -lntp
State       Recv-Q Send-Q                                                  Local Address:Port                                                                 Peer Address:Port              
LISTEN      0      128                                                                 *:22                                                                              *:*                   
users:(("sshd",pid=921,fd=3))LISTEN      0      100                                                         127.0.0.1:25                                                                              *:*                   
users:(("master",pid=1310,fd=13))LISTEN      0      128                                                                :::32768                                                                          :::*                   
users:(("docker-proxy",pid=19781,fd=4))LISTEN      0      128                                                                :::22                                                                             :::*                   
users:(("sshd",pid=921,fd=4))LISTEN      0      128                                                                :::88                                                                             :::*                   
users:(("docker-proxy",pid=19507,fd=4))LISTEN      0      100                                                               ::1:25                                                                             :::*                   
users:(("master",pid=1310,fd=14))

  创建容器设置容器允许使用500m内存,允许使用600m的swap分区,并禁用oom-kill  

[root@localhost ~]# docker run --name web-9 --memory="500m" --memory-swap="600m" --oom-kill-disable -d -P nginx
[root@localhost ~]# docker ps -l
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                   NAMES
25aff37e7dd0        nginx               "nginx -g 'daemon of…"   7 minutes ago       Up 7 minutes        0.0.0.0:32769->80/tcp   web-9

   创建容器时设置容器最大使用一个半的cpu资源

[root@localhost ~]# docker run -d --name web-cx --cpus="1.5" -P nginx 
0771848dd42e79499e6c43e28cecea79f03b80bae56daf7e1aa2c140304c2789
[root@localhost ~]# docker ps -l
CONTAINER ID        IMAGE               COMMAND                  CREATED           
  STATUS              PORTS                   NAMES0771848dd42e        nginx               "nginx -g 'daemon of…"   15 seconds ago   
   Up 12 seconds       0.0.0.0:32770->80/tcp   web-cx

  创建容器时设置容器最多使用半个cpu

[root@localhost ~]# docker run -d --name web-cx1 --cpus=".5" -P nginx 
7638633dc06af3e335179e49b81a08959ec83e50362cb80f71188d652a86e37f
[root@localhost ~]# docker ps -l
CONTAINER ID        IMAGE               COMMAND                  CREATED           
  STATUS              PORTS                   NAMES7638633dc06a        nginx               "nginx -g 'daemon of…"   4 seconds ago    
   Up 2 seconds        0.0.0.0:32771->80/tcp   web-cx1

  动态查看容器的资源限制

[root@localhost ~]# docker stats web-cx

  

查看最后创建的一个容器

[root@localhost ~]# docker ps -l
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                   NAMES
7638633dc06a        nginx               "nginx -g 'daemon of…"   16 minutes ago      Up 16 minutes       0.0.0.0:32771->80/tcp   web-cx1

 查看当前系统所有容器

[root@localhost ~]# docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                         PORTS                   NAMES
7638633dc06a        nginx               "nginx -g 'daemon of…"   17 minutes ago      Up 17 minutes                  0.0.0.0:32771->80/tcp   web-cx1
0771848dd42e        nginx               "nginx -g 'daemon of…"   20 minutes ago      Up 20 minutes                  0.0.0.0:32770->80/tcp   web-cx
25aff37e7dd0        nginx               "nginx -g 'daemon of…"   About an hour ago   Up About an hour               0.0.0.0:32769->80/tcp   web-9
ab4b909c4e68        nginx               "nginx -g 'daemon of…"   About an hour ago   Exited (0) About an hour ago                           cx
a3bdc2062cd7        nginx               "nginx -g 'daemon of…"   2 hours ago         Up 2 hours                     0.0.0.0:32768->80/tcp   web-1
d2394de6c3a1        nginx               "nginx -g 'daemon of…"   2 hours ago         Up 2 hours                     0.0.0.0:88->80/tcp      web
53dfa07e6f2c        centos              "/bin/bash"              2 hours ago         Exited (0) 2 hours ago                                 unruffled_pare
4279c14287c1        centos              "/bin/bash"              2 hours ago         Exited (127) 2 hours ago                               determined_chatterjee
dc2a611dae83        centos              "/bin/bash"              2 hours ago         Created                                                reverent_elion

  查看当前运行的容器

[root@localhost ~]# docker ps 
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                   NAMES
7638633dc06a        nginx               "nginx -g 'daemon of…"   19 minutes ago      Up 19 minutes       0.0.0.0:32771->80/tcp   web-cx1
0771848dd42e        nginx               "nginx -g 'daemon of…"   21 minutes ago      Up 21 minutes       0.0.0.0:32770->80/tcp   web-cx
25aff37e7dd0        nginx               "nginx -g 'daemon of…"   About an hour ago   Up About an hour    0.0.0.0:32769->80/tcp   web-9
a3bdc2062cd7        nginx               "nginx -g 'daemon of…"   2 hours ago         Up 2 hours          0.0.0.0:32768->80/tcp   web-1
d2394de6c3a1        nginx               "nginx -g 'daemon of…"   2 hours ago         Up 2 hours          0.0.0.0:88->80/tcp      web

  查看容器详细信息

[root@localhost ~]# docker inspect web
[
    {
        "Id": "d2394de6c3a11151bfc1697493a8012a132763b2bfa045b55d7f657704e47f6f",
        "Created": "2019-02-22T02:09:09.984595885Z",
        "Path": "nginx",
        "Args": [
            "-g",
            "daemon off;"
        ],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 19532,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2019-02-22T02:09:12.789486607Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:f09fe80eb0e75e97b04b9dfb065ac3fda37a8fac0161f42fca1e6fe4d0977c80",
        "ResolvConfPath": "/var/lib/docker/containers/d2394de6c3a11151bfc1697493a8012a132763b2bfa045b55d7f657704e47f6f/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/d2394de6c3a11151bfc1697493a8012a132763b2bfa045b55d7f657704e47f6f/hostname",
        "HostsPath": "/var/lib/docker/containers/d2394de6c3a11151bfc1697493a8012a132763b2bfa045b55d7f657704e47f6f/hosts",
        "LogPath": "/var/lib/docker/containers/d2394de6c3a11151bfc1697493a8012a132763b2bfa045b55d7f657704e47f6f/d2394de6c3a11151bfc1697493a8012a132763b2bfa045b55d7f657704e47f6f-json.log",
        "Name": "/web",
        "RestartCount": 0,
        "Driver": "overlay2",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "",
        "ExecIDs": [
            "cad7ed32fa3444fb65f4dcf7007ce4af807b57554cb20325c57e38bc0ca4601c"
        ],
        "HostConfig": {
            "Binds": null,
            "ContainerIDFile": "",
            "LogConfig": {
                "Type": "json-file",
                "Config": {}
            },
            "NetworkMode": "default",
            "PortBindings": {
                "80/tcp": [
                    {
                        "HostIp": "",
                        "HostPort": "88"
                    }
                ]
            },
            "RestartPolicy": {
                "Name": "no",
                "MaximumRetryCount": 0
            },
            "AutoRemove": false,
            "VolumeDriver": "",
            "VolumesFrom": null,
            "CapAdd": null,
            "CapDrop": null,
            "Dns": [],
            "DnsOptions": [],
            "DnsSearch": [],
            "ExtraHosts": null,
            "GroupAdd": null,
            "IpcMode": "shareable",
            "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,
            "DiskQuota": 0,
            "KernelMemory": 0,
            "MemoryReservation": 0,
            "MemorySwap": 0,
            "MemorySwappiness": null,
            "OomKillDisable": false,
            "PidsLimit": 0,
            "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/036314137e1525f686243ae5d6fd2861ab91e41d7bad36ac8a416aadb50e5302-init/diff:/var/lib/docker/overlay2/1491a86a89f7d4721b73639455d75fb153bc1
2c6cdaee687039d2e9317215741/diff:/var/lib/docker/overlay2/808c5a465c27497cb57ea709b083e855b6e11e2efa70887b1e3d6f2ece944ab3/diff:/var/lib/docker/overlay2/97f2bebcc1413f092415377b6d7e31dec473bd074f23afcde2d2394c65feed65/diff",                "MergedDir": "/var/lib/docker/overlay2/036314137e1525f686243ae5d6fd2861ab91e41d7bad36ac8a416aadb50e5302/merged",
                "UpperDir": "/var/lib/docker/overlay2/036314137e1525f686243ae5d6fd2861ab91e41d7bad36ac8a416aadb50e5302/diff",
                "WorkDir": "/var/lib/docker/overlay2/036314137e1525f686243ae5d6fd2861ab91e41d7bad36ac8a416aadb50e5302/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "web",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "ExposedPorts": {
                "80/tcp": {}
            },
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "test=123",
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                "NGINX_VERSION=1.15.8-1~stretch",
                "NJS_VERSION=1.15.8.0.2.7-1~stretch"
            ],
            "Cmd": [
                "nginx",
                "-g",
                "daemon off;"
            ],
            "ArgsEscaped": true,
            "Image": "nginx",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": {
                "maintainer": "NGINX Docker Maintainers <docker-maint@nginx.com>"
            },
            "StopSignal": "SIGTERM"
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "fe9ee0aed5e4eb0b9813211dc2d5fb27ee4bf03ea613b50e9c67d2e6d2204beb",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {
                "80/tcp": [
                    {
                        "HostIp": "0.0.0.0",
                        "HostPort": "88"
                    }
                ]
            },
            "SandboxKey": "/var/run/docker/netns/fe9ee0aed5e4",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "1ebbb49fc6565721fdb915fc659f4c5c5cb62c4b7b2190ad9a9aac3b3dbb2f0d",
            "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": "3b2c8016eb022a0e3a9896ff22b7aee66d3034fef8b301b91dc791ff184eef13",
                    "EndpointID": "1ebbb49fc6565721fdb915fc659f4c5c5cb62c4b7b2190ad9a9aac3b3dbb2f0d",
                    "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
                }
            }
        }
    }
]

  交互式进入容器

[root@localhost ~]# docker exec -it web bash
root@web:/# 

  利用容器创建镜像

[root@localhost ~]# docker commit web nginx:web4
sha256:58f1e3f2b46e047322fb302ca87d4c3748f02ba3609bac222ec7122937b0b030
[root@localhost ~]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
nginx               web4                58f1e3f2b46e        28 seconds ago      109MB
nginx               latest              f09fe80eb0e7        2 weeks ago         109MB
centos              latest              1e1148e4cc2c        2 months ago        202MB

  从宿主机往容器里复制文件

[root@localhost ~]# docker cp nginx-1.15.8.tar.gz web:/
[root@localhost ~]# docker  exec -it  web ls /
1    bin   etc	 lib64	nginx-1.15.8.tar.gz  root  srv	usr
12   boot  home  media	opt		     run   sys	var
123  dev   lib	 mnt	proc		     sbin  tmp

  查看指定容器里的进程

[root@localhost ~]# docker top web
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                19532               19514               0                   10:09               ?                   00:00:00            nginx: master process nginx -g daemon off;
101                 19565               19532               0                   10:09               ?                   00:00:00            nginx: worker process
root                19734               19514               0                   10:11               pts/0               00:00:00            bash

  

草都可以从石头缝隙中长出来更可况你呢
原文地址:https://www.cnblogs.com/rdchenxi/p/10417680.html