docker容器命令

  • 4.1 运行镜像生成容器docker run
  • 4.2 查看本地容器
  • 4.3 退出容器
  • 4.4 启动已停止运行的容器
  • 4.5 重启容器
  • 4.6 停止容器
  • 4.7 强制停止容器
  • 4.8 删除已停止的容器
  • 4.9 后台守护模式
  • 4.10 查看容器日志
  • 4.11 查看容器内运行的进程
  • 4.12 查看容器内部细节
  • 4.13进入正在运行的容器并以命令行交互
  • 4.14 复制(容器到主机)
  • 4.15导入与导出容器


4.1 运行镜像生成容器docker run

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
      --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
OPTIONS说明(常用):有些是个减号,有些是两个减号
	--name="容器新名字"			为容器指定一个名称;
	-d:后台运行容器并返回容器ID,也即启动守护式容器(后台运行);

	-i:以交互模式运行容器,通常与-t同时使用;
	-t:为容器重新分配一个伪输入终端,通常与-i同时使用;也即启动交互式容器(前台有伪终端,等待交互);

	-P:随机端口映射,大写P
	-p:指定端口映射,小写p参数说明
		
		-p hostPort:containerPort 端口映射 -p 8080:80
		-p ip:hostPort:containerPort 配置监听地址 -p10.0.0.100:8080:80
		-p ip:containerPort 随机分配端口 -p 10.0.0.100:80
		-p hostPort:containerPort:udp指定协议-p 8080:80:tcp
		-p 81:80 -p 443:443    指定多个

交互式启动

docker run -it ubuntu /bin/bash

等价

docker run -it ubuntu:latest /bin/bash

指定容器名称

docker run -it --name=“myubuntu_01” ubuntu /bin/bash

4.2 查看本地容器

## 语法
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
  -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
OPTIONS说明(常用):
	-a:列出当前所有正在运行的容器+历史上运行过的
	-1:显示最近创建的容器。
	-n:显示最近n个创建的容器。
	-q:静默模式,只显示容器编号。

docker ps -n 2

4.3 退出容器

两种退出方式

exit: run进去容器,exit退出,容器停止

ctrl+p+q: run进去容器,ctrl+p+q退出,容器不停止

4.4 启动已停止运行的容器

docker start 容器ID或者容器名

4.5 重启容器

docker restart 容器ID或者容器名

4.6 停止容器

docker stop 容器ID或者容器名

4.7 强制停止容器

docker kill 容器ID或容器名

4.8 删除已停止的容器

docker rm 容器ID

一次删除多个容器器实例

docker rm -f $(docker ps -a -q)

docker ps -a -q | xargs docker rm

4.9 后台守护模式

很重要的要说明的一点:Docker容器后台运行,就必须有一个前台进程。
容器运行的命令如果不是那些一直挂起的命令(比如运行top,tail),就是会自动退出。
这个是docker的机制问题,比如web容器,以nginx为例,正常情况下,我们配置启动服务只需要启动响应的service即可。例如service nginx start但是,这样做,nginx为后台进程模式运行,就导致docker前台没有运行的应用,这样的容器后台启动后,会立即停止,因为没事可做了。
所以,最佳的解决方案是,将要运行的程序以前台进程的形式运行,常见就是命令行模式,表示还有交互操作

docker run -d redis:6.2.7

容器内可以写shell吗 容器命令_容器

4.10 查看容器日志

docker logs 容器ID

4.11 查看容器内运行的进程

docker top 容器ID

4.12 查看容器内部细节

docker inspect 容器ID

4.13进入正在运行的容器并以命令行交互

docker exec -it 容器ID bashShell
docker attach 容器ID

上述两个区别

attach直接进入容器启动命令的终端,不会启动新的进程用exit退出,会导致容器的停止。

exec是在容器中打开新的终端,并且可以启动新的进程,用exit退出,不会导致容器的停止。

4.14 复制(容器到主机)

docker cp 容器lD:容器内路径 目的主机路径

4.15导入与导出容器

export导出容器的内容流作为一个tar归档文件[对应import命令]

docker export 容器lD > 文件名.tar

import 从tar包中的内容创建一个新的文件系统再导入为镜像[对应export]

cat 文件名.tar | docker import -镜像用户/镜像名:镜像版本号