专注于 JetBrains IDEA 全家桶,永久激活,教程
持续更新 PyCharm,IDEA,WebStorm,PhpStorm,DataGrip,RubyMine,CLion,AppCode 永久激活教程

Docker实战Docker常用命令之容器篇

容器命令

docker run

启动一个容器

  • 帮助
[root@t32 docker]# 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) (default [])
  -a, --attach list                           Attach to STDIN, STDOUT or STDERR (default [])
      --blkio-weight uint16                   Block IO (relative weight), between 10 and 1000, or 0 to disable (default 0)
      --blkio-weight-device weighted-device   Block IO weight (relative device weight) (default [])
      --cap-add list                          Add Linux capabilities (default [])
      --cap-drop list                         Drop Linux capabilities (default [])
      --cgroup-parent string                  Optional parent cgroup for the container
      --cidfile string                        Write the container ID to the file
      --cpu-count int                         CPU count (Windows only)
      --cpu-percent int                       CPU percent (Windows only)
      --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 (default 0.000)
      --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)
      --credentialspec string                 Credential spec for managed service account (Windows only)
  -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 (default [])
      --device-read-bps throttled-device      Limit read rate (bytes per second) from a device (default [])
      --device-read-iops throttled-device     Limit read rate (IO per second) from a device (default [])
      --device-write-bps throttled-device     Limit write rate (bytes per second) to a device (default [])
      --device-write-iops throttled-device    Limit write rate (IO per second) to a device (default [])
      --disable-content-trust                 Skip image verification (default true)
      --dns list                              Set custom DNS servers (default [])
      --dns-option list                       Set DNS options (default [])
      --dns-search list                       Set custom DNS search domains (default [])
      --entrypoint string                     Overwrite the default ENTRYPOINT of the image
  -e, --env list                              Set environment variables (default [])
      --env-file list                         Read in a file of environment variables (default [])
      --expose list                           Expose a port or a range of ports (default [])
      --group-add list                        Add additional groups to join (default [])
      --health-cmd string                     Command to run to check health
      --health-interval duration              Time between running the check (ns|us|ms|s|m|h) (default 0s)
      --health-retries int                    Consecutive failures needed to report unhealthy
      --health-timeout duration               Maximum time to allow one check to run (ns|us|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
      --init-path string                      Path to the docker-init binary
  -i, --interactive                           Keep STDIN open even if not attached
      --io-maxbandwidth string                Maximum IO bandwidth limit for the system drive (Windows only)
      --io-maxiops uint                       Maximum IOps limit for the system drive (Windows only)
      --ip string                             Container IPv4 address (e.g. 172.30.100.104)
      --ip6 string                            Container IPv6 address (e.g. 2001:db8::33)
      --ipc string                            IPC namespace to use
      --isolation string                      Container isolation technology
      --kernel-memory string                  Kernel memory limit
  -l, --label list                            Set meta data on a container (default [])
      --label-file list                       Read in a line delimited file of labels (default [])
      --link list                             Add link to another container (default [])
      --link-local-ip list                    Container IPv4/IPv6 link-local addresses (default [])
      --log-driver string                     Logging driver for the container
      --log-opt list                          Log driver options (default [])
      --mac-address string                    Container MAC address (e.g. 92:d0:c6:0a:29:33)
  -m, --memory string                         Memory limit
      --memory-reservation string             Memory soft limit
      --memory-swap string                    Swap limit equal to memory plus swap: '-1' to enable unlimited swap
      --memory-swappiness int                 Tune container memory swappiness (0 to 100) (default -1)
      --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 (default [])
      --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 (default [])
  -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 (default [])
      --shm-size string                       Size of /dev/shm, default value is 64MB
      --sig-proxy                             Proxy received signals to the process (default true)
      --stop-signal string                    Signal to stop a container, SIGTERM by default (default "SIGTERM")
      --stop-timeout int                      Timeout (in seconds) to stop a container
      --storage-opt list                      Storage driver options for the container (default [])
      --sysctl map                            Sysctl options (default map[])
      --tmpfs list                            Mount a tmpfs directory (default [])
  -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 (default [])
      --volume-driver string                  Optional volume driver for the container
      --volumes-from list                     Mount volumes from the specified container(s) (default [])
  -w, --workdir string                        Working directory inside the container

  • 常用参数详解

鉴于docker run 命令参数较多,下面将针对比较常用的几种进行介绍,其他参数可以参见官方文档

1、 -d:后台运行,不能与–rm一起使用
2、 --rm:容器运行结束,删除容器
3、 -i:使用交互模式
4、 -t:分配tty,不能与nohup命令一起使用
5、 --restart: 容器的重启策略,不能与–rm一起使用

 *  no:退出时不要自动重启容器。这是默认值。
 *  on-failure\[:max-retries\]:仅当容器以非零退出状态退出时,才重新启动。(可选)限制Docker守护程序尝试重新启动的重试次数。
 *  unless-stopped:除非显式停止容器或Docker本身已停止或重新启动,否则请重新启动容器。
 *  always:无论退出状态如何,请始终重新启动容器。当您始终指定时,Docker守护程序将尝试无限期重启容器。无论容器的当前状态如何,该容器还将始终在守护程序启动时启动。

6、 -v:[-v hostpath:containerPath]:将本地目录挂载到容器中
7、 -p:[-p hostport:containerPort,eg -p 8000:80]:将容器内的80端口和物理机的8000端口相映射
8、 --privileged:给容器扩展权限,使用该参数能够使容器具有root权限
9、 --network:指定网络模式

 *  bridge:桥接式网络模式(默认)
 *  host:开放式网络模式,容器使用和host主机一样的网络
 *  container(join):联合挂载式网络模式,是host网络模式的延伸
 *  none(Close):封闭式网络模式,容器中只有lookloop

10、 -w:[-w containerPath]进入容器,切换到对用的目录下
11、 -l: 设置容器的label,便于docker ps 显示
12、 --hostname:指定容器的名称
13、 -e:[-e test=111]:指定容器中的环境变量

  • 以上是经常使用的参数,有关cpu和memory的参数也是比较重要的。

docker exec

在容器中执行一个命令

  • 帮助
[root@t32 docker]# docker exec --help

Usage:  docker exec [OPTIONS] CONTAINER COMMAND [ARG...]

Run a command in a running container

Options:
  -d, --detach               Detached mode: run command in the background
      --detach-keys string   Override the key sequence for detaching a container
  -e, --env list             Set environment variables (default [])
      --help                 Print usage
  -i, --interactive          Keep STDIN open even if not attached
      --privileged           Give extended privileges to the command
  -t, --tty                  Allocate a pseudo-TTY
  -u, --user string          Username or UID (format: <name|uid>[:<group|gid>])

  • 例子
[root@t32 docker]# docker run -d --hostname centos -l type=centos --restart=on-failure:3 470671670cac /usr/sbin/init  
7df430b9674c6b041ed2bebd804f4712526bc81bb15d5909a173a15e10d8b162
[root@t32 docker]# docker exec -it 7df430b9674c6b0 uname -a 
Linux centos 3.10.0-862.el7.x86_64 #1 SMP Fri Apr 20 16:44:24 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux
[root@t32 docker]# 

docker ps

显示所有容器的状况,包括运行,退出,暂停等状态的容器

  • 帮助
[root@t32 docker]# docker ps --help

Usage:  docker ps [OPTIONS]

List containers

Options:
  -a, --all             Show all containers (default shows just running)
  -f, --filter filter   Filter output based on conditions provided
      --format string   Pretty-print containers using a Go template
      --help            Print usage
  -n, --last int        Show n last created containers (includes all states) (default -1)
  -l, --latest          Show the latest created container (includes all states)
      --no-trunc        Don't truncate output
  -q, --quiet           Only display numeric IDs
  -s, --size            Display total file sizes

  • 参数详解

1、 --filter: 过滤器

 *  id:容器编号
 *  name:容器名称
 *  label:表示键或键值对的任意字符串。表示为或=
 *  exited:表示容器的退出代码的整数,仅对--all有用。
 *  status:容器状态,有created,restarting,running,removing,paused,exited,或者dead
 *  ancestor:筛选共享给定image作为祖先的容器。为\[:\], ![80\_1.png][80_1.png]或[image@digest][image_digest]
 *  before/since:过滤在给定容器ID或名称之前或之后创建的容器
 *  volume:过滤运行已安装给定卷或绑定安装的容器。
 *  network:筛选正在运行的连接到给定网络的容器。
 *  publish/expose:筛选或公开给定端口的容器。表示为\[/\]或/\[\]
 *  health:根据健康检查状态过滤容器。有starting,healthy,unhealthy或none。
 *  isolation 仅Windows守护程序。其中一个default,process或hyperv。(没怎么用过)
 *  is-task 筛选作为服务“任务”的容器。布尔选项(true或false)(没怎么用过)

2、 -l:显示最新创建并运行的容器

  • 例子
[root@t32 docker]# docker ps -a --filter label=type=centos --filter status=running  --format "{{json .}}" |jq
{
  "Command": "\"/usr/sbin/init\"",
  "CreatedAt": "2020-03-04 17:11:52 +0800 CST",
  "ID": "7df430b9674c",
  "Image": "470671670cac",
  "Labels": "org.label-schema.license=GPLv2,org.label-schema.schema-version=1.0,org.label-schema.vendor=CentOS,org.opencontainers.image.created=2020-01-14 00:00:00-08:00,org.opencontainers.image.licenses=GPL-2.0-only,org.opencontainers.image.title=CentOS Base Image,org.label-schema.build-date=20200114,org.opencontainers.image.vendor=CentOS,type=centos,org.label-schema.name=CentOS Base Image",
  "LocalVolumes": "0",
  "Mounts": "",
  "Names": "sharp_shannon",
  "Networks": "bridge",
  "Ports": "",
  "RunningFor": "14 minutes",
  "Size": "0 B",
  "Status": "Up 14 minutes"
}

docker logs

查看容器日志,运维必备方法

  • 帮助
[root@t32 docker]# 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
      --help           Print usage
      --since string   Show logs since timestamp
      --tail string    Number of lines to show from the end of the logs (default "all")
  -t, --timestamps     Show timestamps

  • 常用参数解析

1、 -f/–follow:持续显示日志信息
2、 --tail n:显示最后n行日志

docker rm

删除容器

  • 批量删除exited的容器
[root@t32 docker]# docker rm -f $(docker ps -qa --filter status=exited)
3b5f7c6b7d1c
f81106e0dc30
2bf591c0df07
065b1b373eed
a9a621a1716b
a21ea52dfb8f
53ed37053a98
7da020882835

docker create

创建容器,但是不能启动。需要使用docker start启动容器

docker top

显示容器中的进程

  • 例子
[root@t32 docker]# docker top 6742d27d8142
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                12179               12159               0                   17:44               ?                   00:00:00            agent

docker cp

在容器和物理机之间拷贝数据

  • 帮助
[root@t32 docker]# docker cp --help

Usage:  docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH|-
    docker cp [OPTIONS] SRC_PATH|- CONTAINER:DEST_PATH

Copy files/folders between a container and the local filesystem

Options:
  -a, --archive       Archive mode (copy all uid/gid information)
  -L, --follow-link   Always follow symbol link in SRC_PATH
      --help          Print usage

  • 例子
[root@t32 docker]# cat >> test.txt <<EOF
> test1
> test2
> test3
> EOF
[root@t32 docker]# docker cp test.txt  54ceca890fc23:/root/
[root@t32 docker]# docker exec -it 54ceca890fc23 ls /root/
anaconda-ks.cfg  anaconda-post.log  original-ks.cfg  test.txt
[root@t32 docker]# docker exec -it 54ceca890fc23 cat  /root/test.txt
test1
test2
test3

docker start

启动一个或多个容器

docker stop

暂停一个或多个容器

docker restar

重启一个或多个容器

docker pause/docker unpause

暂停/继续 一个或多个容器

docker kill

杀死一个或多个容器

  • 根据以上命令举例
[root@t32 docker]# docker create 470671670cac /usr/sbin/init
dd58836920c2da0f9c4760fcfa98ed360f9a347a30e3cf1a61d152d33fd38c79
[root@t32 docker]# docker ps -a -l
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
dd58836920c2        470671670cac        "/usr/sbin/init"    3 seconds ago       Created                                 musing_boyd
You have mail in /var/spool/mail/root
[root@t32 docker]# docker start dd58836920c2
dd58836920c2
[root@t32 docker]# docker ps -a -l
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
dd58836920c2        470671670cac        "/usr/sbin/init"    17 seconds ago      Up 1 second                             musing_boyd
[root@t32 docker]# docker stop dd58836920c2
dd58836920c2
[root@t32 docker]# docker ps -a -l
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                       PORTS               NAMES
dd58836920c2        470671670cac        "/usr/sbin/init"    40 seconds ago      Exited (137) 3 seconds ago                       musing_boyd
[root@t32 docker]# docker restart dd58836920c2
dd58836920c2
[root@t32 docker]# docker ps -a -l
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
dd58836920c2        470671670cac        "/usr/sbin/init"    58 seconds ago      Up 2 seconds                            musing_boyd
[root@t32 docker]# docker pause dd58836920c2
dd58836920c2
[root@t32 docker]# docker ps -a -l
CONTAINER ID        IMAGE               COMMAND             CREATED              STATUS                   PORTS               NAMES
dd58836920c2        470671670cac        "/usr/sbin/init"    About a minute ago   Up 18 seconds (Paused)                       musing_boyd
[root@t32 docker]# docker unpause dd58836920c2
dd58836920c2
[root@t32 docker]# docker ps -a -l
CONTAINER ID        IMAGE               COMMAND             CREATED              STATUS              PORTS               NAMES
dd58836920c2        470671670cac        "/usr/sbin/init"    About a minute ago   Up 30 seconds                           musing_boyd
[root@t32 docker]# docker kill dd58836920c2
dd58836920c2
[root@t32 docker]# docker ps -a -l
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                      PORTS               NAMES
dd58836920c2        470671670cac        "/usr/sbin/init"    2 minutes ago       Exited (137) 1 second ago                       musing_boyd

文章永久链接:https://tech.souyunku.com/44233

未经允许不得转载:搜云库技术团队 » Docker实战Docker常用命令之容器篇

JetBrains 全家桶,激活、破解、教程

提供 JetBrains 全家桶激活码、注册码、破解补丁下载及详细激活教程,支持 IntelliJ IDEA、PyCharm、WebStorm 等工具的永久激活。无论是破解教程,还是最新激活码,均可免费获得,帮助开发者解决常见激活问题,确保轻松破解并快速使用 JetBrains 软件。获取免费的破解补丁和激活码,快速解决激活难题,全面覆盖 2024/2025 版本!

联系我们联系我们