Like Share Discussion Bookmark Smile

J.J. Huang   2019-03-24   Docker   瀏覽次數:次   DMCA.com Protection Status

Docker - 第二章 | 基本指令

在開始之前建議大家還是先把 第一章 - Docker 簡介 做個初步的了解,而且對於「Docker 名詞的基本觀念」要特別注意其觀念。

然而Docker可以產生VM(OS Level),所以指令非常的多,在這邊只把初學者常用到的命令列出來,進階的就用到再去官方查詢即可或使用docker help指令。

Docker Help

  • Docker提供了查看所有的指令的指令,只需要輸入下方指令即可
1
docker help

指令清單

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
sage:	docker COMMAND

A self-sufficient runtime for containers

Options:
--config string Location of client config files (default "/Users/morose/.docker")
-D, --debug Enable debug mode
--help Print usage
-H, --host list Daemon socket(s) to connect to
-l, --log-level string Set the logging level ("debug"|"info"|"warn"|"error"|"fatal") (default "info")
--tls Use TLS; implied by --tlsverify
--tlscacert string Trust certs signed only by this CA (default "/Users/morose/.docker/ca.pem")
--tlscert string Path to TLS certificate file (default "/Users/morose/.docker/cert.pem")
--tlskey string Path to TLS key file (default "/Users/morose/.docker/key.pem")
--tlsverify Use TLS and verify the remote
-v, --version Print version information and quit

Management Commands:
container Manage containers
image Manage images
network Manage networks
node Manage Swarm nodes
plugin Manage plugins
secret Manage Docker secrets
service Manage services
stack Manage Docker stacks
swarm Manage Swarm
system Manage Docker
volume Manage volumes

Commands:
attach Attach local standard input, output, and error streams to a running container
build Build an image from a Dockerfile
commit Create a new image from a container's changes
cp Copy files/folders between a container and the local filesystem
create Create a new container
diff Inspect changes to files or directories on a container's filesystem
events Get real time events from the server
exec Run a command in a running container
export Export a container's filesystem as a tar archive
history Show the history of an image
images List images
import Import the contents from a tarball to create a filesystem image
info Display system-wide information
inspect Return low-level information on Docker objects
kill Kill one or more running containers
load Load an image from a tar archive or STDIN
login Log in to a Docker registry
logout Log out from a Docker registry
logs Fetch the logs of a container
pause Pause all processes within one or more containers
port List port mappings or a specific mapping for the container
ps List containers
pull Pull an image or a repository from a registry
push Push an image or a repository to a registry
rename Rename a container
restart Restart one or more containers
rm Remove one or more containers
rmi Remove one or more images
run Run a command in a new container
save Save one or more images to a tar archive (streamed to STDOUT by default)
search Search the Docker Hub for images
start Start one or more stopped containers
stats Display a live stream of container(s) resource usage statistics
stop Stop one or more running containers
tag Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE
top Display the running processes of a container
unpause Unpause all processes within one or more containers
update Update configuration of one or more containers
version Show the Docker version information
wait Block until one or more containers stop, then print their exit codes

Run 'docker COMMAND --help' for more information on a command.
  • 如需查看每個指令的詳細參數,如針對run查詳細參數的指令
1
docker run --help

參數清單

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
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
--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
--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 (ns|us|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 (ns|us|ms|s|m|h) (default 0s)
--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
-i, --interactive Keep STDIN open even if not attached
--io-maxbandwidth bytes Maximum IO bandwidth limit for the system drive (Windows only)
--io-maxiops uint Maximum IOps limit for the system drive (Windows only)
--ip string IPv4 address (e.g., 172.30.100.104)
--ip6 string IPv6 address (e.g., 2001:db8::33)
--ipc string IPC namespace 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

Docker Image 常用指令

  • Docker 搜尋 Image

    1
    2
    3
    4
    docker search image-name

    docker search debian
    docker search nginx

  • Docker 下載 Image
    兩種方式,第一種直接透過指令來尋找Image,第二種 Docker Hub 中尋找,
    後者網頁上會列出有關於該Image的資訊,例如如何設定、如何下載、如何執行等。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    # 抓所有 ubuntu image 回來, tag 可於後面附加上去
    docker pull ubuntu

    # 只抓取 Ubuntu 16.04 的 Image
    docker pull ubuntu:16.04

    # library/debian - Docker Hub,latest 只會抓最新版 (Debain Docker 官方版)
    docker pull debian:latest

    # library/ubuntu - Docker Hub
    docker pull ubuntu:latest
  • 列出本機 Image

    1
    docker images

  • 複製 Image

    1
    2
    # 如想複製一個image`openjdk:8-jre-alpine`,同時命名為`j.j.huang/openjdk:1`
    docker tag openjdk:8-jre-alpine j.j.huang/openjdk:1

  • 刪除 Image

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    # docker images 可以看到 image-id
    docker rmi image-id

    # 強置刪除
    docker rmi -f image-id

    # 移除所有 docker images
    docker rmi $(docker images -q)

    # 移除所有 docker images
    docker rmi docker images -qa

    # 移除所有沒有 tag 的 image
    docker rmi $(docker images -f "dangling=true" -q)


Docker Container 常用指令

  • 運行 Container
    1
    docker run redis:3.2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
-a stdin: 指定標準輸入輸出內容類型,可選 STDIN/STDOUT/STDERR
-d: 後台運行Container,並返回ContainerID
-i: 以交互模式運行Container,通常與 -t 同時使用
-p: 端口映射,格式為:主機(宿主)端口:Container端口
-t: 為Container重新分配一個偽輸入終端,通常與 -i 同時使用
--name="nginx-lb": 為Container指定一個名稱
--dns 8.8.8.8: 指定Container使用的DNS伺服器,默認和宿主一致
--dns-search example.com: 指定ContainerDNS搜索域名,默認和宿主一致
-h "mars": 指定Container的hostname
-e username="ritchie": 設置環境變量
--env-file=[]: 從指定文件讀入環境變量
--cpuset="0-2" or --cpuset="0,1,2": 綁定Container到指定CPU運行
-m :設置Container使用內存最大值
--net="bridge": 指定Container的網路連接類型,支持 bridge/host/none/container: 四種類型
--link=[]: 添加鏈接到另一個Container
--expose=[]: 開放一個端口或一組端口

例如redis,指定其端口對應16379:6379,後台運行Container,並返回ContainerID

1
docker run -p 16379:6379 -d redis:3.2

  • 列出運行中 Container

    1
    docker ps
  • 列出所有運行/停止 Container

    1
    dokcer ps -a

  • 停止 Container

    1
    2
    # docker stop container id
    docker stop ac3839486d9b

  • 啟動已停止 Container

    1
    2
    # docker start container id
    docker start ac3839486d9b

  • 重新起動 Container

    1
    2
    # docker restart container id
    docker restart ac3839486d9b

  • 強制停止 Container

    1
    2
    # docker kill container id
    docker kill ac3839486d9b

  • 移除 Container

    1
    2
    # docker rm container id
    docker rm ac3839486d9b

    只能刪除已經停止的Container,若需要刪除正在運行的Container,可加入-f參數

  • 進入 Container

    1
    2
    3
    4
    5
    6
    7
    # docker exec -it ContainerID 參數
    docker exec -it 58954298f36e redis-cli

    # 參數說明:
        -d:分離模式: 在後台運行
        -i:即使沒有附加也保持STDIN 打開
        -t:分配一個偽終端

  • 另存 Container

    1
    2
    3
    4
    5
    6
    7
    8
    # docker commit [options] Containerid name:tag
    docker commit 58954298f36e jjhuang.com/redis:1

    # 參數說明:
        -a:提交的image作者
        -c:使用Dockerfile指令來建立image
        -m:提交時的說明文字
        -p:在commit時,將Container暫停

    我們常在運行Container做很多的相關設置或是優化,但是當Container被刪除後,這些修改配置就都會消失;所以此時我們需要的就是將當前Container另外儲存成image。


Docker 其他指令

  • Docker 版本資訊

    1
    2
    docker version
    docker info
  • 本機與Container檔案傳輸

    1
    2
    3
    4
    # docker cp Container名:要拷貝的文件在 Container 裡面的路徑 要拷貝到宿主機的相應路徑
    # docker cp 要拷貝的文件路徑 Container名:要拷貝到 Container 裡面對應的路徑
    docker cp 58954298f36e:/opt/xxx.json /opt
    docker cp /opt/xxx.json 58954298f36e:/opt

以上只是列出比較基本常用的指令,還有很多好用的指令,在後面的文章有用到,會再另外做說明

註:以上參考了
TsungDocker 初學筆記 - 基本指令操作教學 文章。
Dockerdocker docs
RUNOOB.COMDocker 命令大全