最後更新: 2019-03-21
介紹
image
An image is a lightweight, stand-alone, executable package that includes everything needed to run a piece of software,
including the code, a runtime, libraries, environment variables, and config files.
container
It is a runtime instance of an image
目錄
- Installation
- ufw_setting
- Check docker is working install
- Folder & File & layout
- 基本設定
- Download a pre-built image
- Try it
- Listing containers status
- Attach to a running container
- docker logs
- Other Useful CLI
Installation
Centos 7
yum install docker
systemctl enable docker
systemctl start docker
Centos 7 Install CE Version
1. Uninstall old versions
yum remove docker \ docker-client \ docker-client-latest \ docker-common \ docker-latest \ docker-latest-logrotate \ docker-logrotate \ docker-engine \ docker-compose
2. Add centos-extras repository
yum install -y yum-utils
yum-config-manager \
--add-repo \
https://download.docker.com/linux/centos/docker-ce.repo
3. Install Docker
yum install docker-ce docker-ce-cli containerd.io
If prompted to accept the GPG key, verify that the fingerprint matches 060A 61C5 1B55 8A7F 742B 77AA C52F EB6B 621E 9F35, and if so, accept it.
# List specific version of Docker Engine
yum list docker-ce --showduplicates | sort -r
4. Test
systemctl start docker
systemctl enable docker
docker run hello-world
5. Auto Start with boot
docker inspect -f '{{json .HostConfig.RestartPolicy}}' CONTAINER
docker update --restart unless-stopped CONTAINER
6. Install compose
curl -L "https://github.com/docker/compose/releases/download/1.25.5/docker-compose-$(uname -s)-$(uname -m)" \
-o /usr/local/bin/docker-compose
chmod +x /usr/local/bin/docker-compose
ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose
docker-compose --version
U12
* Ubuntu Precise 12.04 (LTS) (64-bit)
* Linux kernel 3.8
# Upgrate to kernel 3.8
apt-get install linux-image-generic-lts-raring linux-headers-generic-lts-raring
# APT system can deal with https
apt-get install apt-transport-https
# Docker repository key
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 36A1D7869245C8950F966E92D8576A8BA88D21E9
# Add Docker repository
echo "deb https://get.docker.io/ubuntu docker main" > /etc/apt/sources.list.d/docker.list
# Install
apt-get update
apt-get install lxc-docker
包括了:
- cgroup-lite
- aufs-tools
U16
apt-get install docker.io
Enable memory and swap accounting
# Debian & Ubuntu
/etc/default/grub
GRUB_CMDLINE_LINUX="cgroup_enable=memory swapaccount=1"
修改後執行:
update-grub
reboot
ufw setting
/etc/default/ufw
DEFAULT_FORWARD_POLICY="ACCEPT"
ufw reload
Check docker is working install
docker --version
Docker version 1.12.6, build 78d1802
systemctl status docker
● docker.service - Docker Application Container Engine Loaded: loaded (/lib/systemd/system/docker.service; enabled; vendor preset: enabled) Active: active (running) since Tue 2017-06-20 13:23:13 HKT; 1h 11min ago Docs: https://docs.docker.com Main PID: 24411 (dockerd) CGroup: /system.slice/docker.service ├─24411 /usr/bin/dockerd -H fd:// └─24420 containerd -l unix:///var/run/docker/libcontainerd/docker-containerd.sock ...
docker info # docker 要 Start 起後此 command 才用到
Containers: 0 Running: 0 Paused: 0 Stopped: 0 Images: 0 Server Version: 1.13.1 Storage Driver: overlay2 Backing Filesystem: xfs Supports d_type: true Native Overlay Diff: true Logging Driver: journald Cgroup Driver: systemd Plugins: Volume: local Network: bridge host macvlan null overlay Swarm: inactive Runtimes: docker-runc runc Default Runtime: docker-runc Init Binary: /usr/libexec/docker/docker-init-current containerd version: (expected: aa8187dbd3b7ad67d8e5e3a15115d3eef43a7ed1) runc version: 5eda6f6fd0c2884c2c8e78a6e7119e8d0ecedb77 (expected: 9df8b306d01f59d3a8029be411de015b7304dd8f) init version: fec3683b971d9c3ef73f284f176672c44b448662 (expected: 949e6facb77383876aeff8a6944dde66b3089574) Security Options: seccomp Profile: /etc/docker/seccomp.json Kernel Version: 3.10.0-862.11.6.el7.x86_64 Operating System: CentOS Linux 7 (Core) OSType: linux Architecture: x86_64 Number of Docker Hooks: 3 CPUs: 1 Total Memory: 1.953 GiB Name: MYHOSTNAME ID: ?:?:?:?:?:?:?:?:?:?:?:? Docker Root Dir: /var/lib/docker Debug Mode (client): false Debug Mode (server): false Registry: https://index.docker.io/v1/ Experimental: false Insecure Registries: 127.0.0.0/8 Live Restore Enabled: false Registries: docker.io (secure)
docker run hello-world
Hello from Docker! This message shows that your installation appears to be working correctly. ....
Folder & File & layout
tree -L 2 /var/lib/docker
/var/lib/docker ├── containers │ └── d29c9ca6aba46444a69c54a6ad11aa303a0f1146c77a8a69a6cd2d7cb9658f68 ├── image │ └── overlay2 ├── network │ └── files ├── overlay2 │ ├── 49eb2326916b3480ec926fcbed29b3e53317586190c25faf4f874bbb583d6658 │ ├── 49eb2326916b3480ec926fcbed29b3e53317586190c25faf4f874bbb583d6658-init │ ├── 7bb04f64043c62550b47684392c8d40e19f33ccb32ae3d7d195b35b7be0951fd │ ├── backingFsBlockDev │ └── l ├── plugins │ ├── storage │ └── tmp ├── swarm ├── tmp ├── trust └── volumes └── metadata.db 18 directories, 2 files
基本設定
# Config File
/etc/docker/daemon.json # docker 的 config 係 json 來
# Default 內容 {}
# Daemon default listen on unix socket
# tcp://host:4243 unix:///var/run/docker.sock
# Run docker in daemon mode listen TCP
docker -H 0.0.0.0:5555 -d
Download a pre-built image
# Find Public Images
docker search NAME
i.e.
docker search ubuntu
NAME DESCRIPTION STARS OFFICIAL AUTOMATED ubuntu Ubuntu is a Debian-based Linux operating s... 6148 [OK] rastasheep/ubuntu-sshd Dockerized SSH service, built on top of of... 89 [OK] ubuntu-upstart Upstart is an event-based replacement for ... 74 [OK] ubuntu-debootstrap debootstrap --variant=minbase --components... 30 [OK] ....
# Download image
# docker pull [OPTIONS] NAME[:TAG|@DIGEST]
# Default tag: latest
docker pull docker.io/nginx
docker pull docker.io/nginx:stable
* Docker images can consist of multiple layers
Trying to pull repository docker.io/library/nginx ... stable: Pulling from docker.io/library/nginx a5a6f2f73cd8: Already exists 1a32bfb24a51: Pull complete b30849834152: Pull complete Digest: sha256:.... Status: Downloaded newer image for docker.io/nginx:stable
# List local docker image
docker images nginx
docker.io/nginx stable a7dfe30a82fb 6 days ago 109 MB docker.io/nginx latest 568c4670fa80 2 weeks ago 109 MB
# Get image info.
# Display detailed information on images
docker image inspect httpd
# List all tags for a Docker image on a remote registry
docker info |& grep Registry
Registry: https://index.docker.io/v1/
yum install jq
wget -q https://index.docker.io/v1/repositories/nginx/tags -O - | jq -r .[].name
latest 1 1-alpine 1-alpine-perl 1-perl 1.10 1.10-alpine ...
# Remove images
docker rmi IMAGE
Try it
docker run ubuntu /bin/echo "hello world"
1. It downloaded the base image from the docker index
2. it created a new LXC container
3. It allocated a filesystem for it
4. Mounted a read-write layer
5. Allocated a network interface
6. Setup an IP for it, with network address translation
7. executed a process in contrainer
Running an interactive shell:
-i, --interactive=true # Keep STDIN open even if not attached. The default is false.
-t, --tty=true # Allocate a pseudo-TTY. The default is false.
docker run -i -t ubuntu /bin/bash
* Press Ctrl-D to exit the shell. (代表 kill 了它)
* -i, --interactive
Run a container
docker run -i -t ubuntu top&
Show low-level information on a container
docker inspect <CONTAINER ID>
[ { "Id": "e5ccaa756ec8842f239bd81af737526857ad769a42f21d03d983d92d64c8e506", "Created": "2017-06-20T07:05:50.589668323Z", "Path": "top", "Args": [], "State": { "Status": "running", "Running": true, "Paused": false, "Restarting": false, "OOMKilled": false, "Dead": false, "Pid": 30522, "ExitCode": 0, "Error": "", "StartedAt": "2017-06-20T07:05:51.231501573Z", "FinishedAt": "0001-01-01T00:00:00Z" }, "Image": "sha256:7b9b13f7b9c086adfb6be4d2d264f90f16b4d1d5b3ab9f955caa728c3675c8a2", "ResolvConfPath": "/var/lib/docker/containers/e5cc../resolv.conf", "HostnamePath": "/var/lib/docker/containers/e5cc../hostname", "HostsPath": "/var/lib/docker/containers/e5cc../hosts", "LogPath": "/var/lib/docker/containers/e5cc../e5cc..-json.log", "Name": "/nauseous_davinci", "RestartCount": 0, "Driver": "overlay", "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, "Dns": [], "DnsOptions": [], "DnsSearch": [], "ExtraHosts": null, "GroupAdd": null, "IpcMode": "", "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, "CgroupParent": "", "BlkioWeight": 0, "BlkioWeightDevice": null, "BlkioDeviceReadBps": null, "BlkioDeviceWriteBps": null, "BlkioDeviceReadIOps": null, "BlkioDeviceWriteIOps": null, "CpuPeriod": 0, "CpuQuota": 0, "CpusetCpus": "", "CpusetMems": "", "Devices": [], "DiskQuota": 0, "KernelMemory": 0, "MemoryReservation": 0, "MemorySwap": 0, "MemorySwappiness": -1, "OomKillDisable": false, "PidsLimit": 0, "Ulimits": null, "CpuCount": 0, "CpuPercent": 0, "IOMaximumIOps": 0, "IOMaximumBandwidth": 0 }, "GraphDriver": { "Name": "overlay", "Data": { "LowerDir": "/var/lib/docker/overlay/616.../root", "MergedDir": "/var/lib/docker/overlay/e70a.../merged", "UpperDir": "/var/lib/docker/overlay/e70a.../upper", "WorkDir": "/var/lib/docker/overlay/e70a.../work" } }, "Mounts": [], "Config": { "Hostname": "e5ccaa756ec8", "Domainname": "", "User": "", "AttachStdin": true, "AttachStdout": true, "AttachStderr": true, "Tty": true, "OpenStdin": true, "StdinOnce": true, "Env": [ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" ], "Cmd": [ "top" ], "Image": "ubuntu", "Volumes": null, "WorkingDir": "", "Entrypoint": null, "OnBuild": null, "Labels": {} }, "NetworkSettings": { "Bridge": "", "SandboxID": "edf377e726ae79136d3fffa2ba87402d9d5f1ac4ac97401e1d1bd933605771e3", "HairpinMode": false, "LinkLocalIPv6Address": "", "LinkLocalIPv6PrefixLen": 0, "Ports": {}, "SandboxKey": "/var/run/docker/netns/edf377e726ae", "SecondaryIPAddresses": null, "SecondaryIPv6Addresses": null, "EndpointID": "9f00b5f79f7425abdb307ae3a072f87d9505edd5bf9ecdbb981d1663c62dcd1e", "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": "6ddceb03a59c31e19ac7dfd90d1b187c6266e1498f49aaca38f7dad8bb8d881e", "EndpointID": "9f00b5f79f7425abdb307ae3a072f87d9505edd5bf9ecdbb981d1663c62dcd1e", "Gateway": "172.17.0.1", "IPAddress": "172.17.0.2", "IPPrefixLen": 16, "IPv6Gateway": "", "GlobalIPv6Address": "", "GlobalIPv6PrefixLen": 0, "MacAddress": "02:42:ac:11:00:02" } } } } ]
# Run in background & set name
docker run -tid ubuntu --name=mytry
Listing containers status
# Lists only running containers
docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES e542d7c9ace2 nginx:stable "nginx -g 'daemon ..." 9 minutes ago Up 37 seconds 80/tcp tmp-nginx
# Lists all containers (active and inactive)
# -a, --all
docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES e542d7c9ace2 nginx:stable "nginx -g 'daemon ..." 8 minutes ago Exited (0) About a minute ago
Remark: Show name only
docker ps --format '{{.Names}}'
# Run "Exited"(inactive) container
docker start tmp-nginx
# Display the running processes of a container
docker top tmp-nginx
UID PID PPID C STIME TTY TIME CMD root 5861 5848 0 16:22 ? 00:00:00 nginx: master process nginx -g daemon off; 101 5883 5861 0 16:22 ? 00:00:00 nginx: worker process
TIME: start 時間
Attach to a running container
# Attach to a running container
docker attach NAMES
Or
docker attach CONTAINER_ID
* 不是所有 container 都可以 attach
* To stop a container, use CTRL-c. This key sequence sends SIGKILL to the container.
detach from the container: CTRL-p CTRL-q
解決 Attach 唔到的情況
docker exec -it tmp-nginx /bin/bash
Remark
# 如果只是想 list file, 可以直接
docker exec tmp-nginx ls /etc
對 Container 進行操作
# SIGTERM PID 1 in the container --> wait 10 seconds --> SIGKILL
docker stop name
#
docker start name
#
docker restart name
# 輸入 signal 到 docker
# Default: SIGKILL
docker kill name
# 其他 signal
docker kill -s HUP <container name>
# remove an already stopped container
# -f flag will cause it to first issue a SIGKILL
docker rm name
Commit your container to a new named image (stored as a diff)
docker commit <container_id> <some_name>
* The commit operation will not include any data contained in volumes mounted inside the container.
* The --change option will apply Dockerfile instructions to the image that is created.
Dockerfile instructions: CMD|ENTRYPOINT|ENV|EXPOSE|LABEL|ONBUILD|USER|VOLUME|WORKDIR
* By default, the container being committed and its processes will be paused while the image is committed.
ie.
# 獲得 ID
docker inspect -f "{{ .Config.Env }}" ID
# 設定 ENV
docker commit --change "ENV DEBUG=true" ID testimage:v3
Networking
All of Docker 's iptables rules are added to the DOCKER chain. Do not manipulate this table manually.
If you need to add rules which load before Docker’s rules, add them to the DOCKER-USER chain.
iptables
Chain FORWARD (policy DROP) target prot opt source destination DOCKER-ISOLATION all -- 0.0.0.0/0 0.0.0.0/0 ... Chain DOCKER (1 references) target prot opt source destination Chain DOCKER-ISOLATION (1 references) target prot opt source destination RETURN all -- 0.0.0.0/0 0.0.0.0/0
Docker 's networking subsystem is pluggable, using drivers.
bridge: (Default)
host:
For standalone containers, remove network isolation between the container and the Docker host,
and use the host’s networking directly.
overlay:
Overlay networks connect multiple Docker daemons together and enable swarm services to communicate with each other.
This strategy removes the need to do OS-level routing between these containers. See overlay networks.
macvlan:
Macvlan networks allow you to assign a MAC address to a container,
making it appear as a physical device on your network.
The Docker daemon routes traffic to containers by their MAC addresses.
none:
For this container, disable all networking.
list network
docker network ls
NETWORK ID NAME DRIVER SCOPE fed2eee71eed bridge bridge local dce4e41c1f31 host host local 3d276e5f25b9 none null local
* bridge 的 host side NIC 係 docker0
* Docker uses Linux bridge capabilities to provide network connectivity to containers
inspect (看某 network 的 setting)
# 會顯示 subnet 及有什麼 container
docker network inspect bridge
[ { "Name": "bridge", "Id": "6ddceb03a59c31e19ac7dfd90d1b187c6266e1498f49aaca38f7dad8bb8d881e", "Scope": "local", "Driver": "bridge", "EnableIPv6": false, "IPAM": { "Driver": "default", "Options": null, "Config": [ { "Subnet": "172.17.0.0/16" } ] }, "Internal": false, "Containers": { "f901b1037f152d338a3c60fe12ee9e0ed2fbbf0b6a00ab5ff8bbc032e5a9b71b": { "Name": "mytry", "EndpointID": "7d3b8540c69371cc10ec5e6320f551ffa276973ce4f3535985312e0efe7966fa", "MacAddress": "02:42:ac:11:00:02", "IPv4Address": "172.17.0.2/16", "IPv6Address": "" } }, "Options": { "com.docker.network.bridge.default_bridge": "true", "com.docker.network.bridge.enable_icc": "true", "com.docker.network.bridge.enable_ip_masquerade": "true", "com.docker.network.bridge.host_binding_ipv4": "0.0.0.0", "com.docker.network.bridge.name": "docker0", "com.docker.network.driver.mtu": "1500" }, "Labels": {} } ]
# Disconnect / Connect network
# Usage: docker network <ACTION> <NETWORK> <CONTAINER>
docker network disconnect bridge myvps
docker network connect bridge myvps
# Create network
# -d, --driver
docker network create -d bridge mybridge
# driver opts
# -o "com.docker.network.bridge.name=docker1"
docker network create -d bridge -o "com.docker.network.bridge.name=docker1" mybridge
# 設定 subnet & gateway
docker network create -d bridge --subnet=10.0.0.0/24 --gateway=10.0.0.1 mybridge
Remark
--internal # create an externally isolated overlay network
# Remove network
docker network rm mybridge
Config bridge
# To configure the default bridge network
# Restart Docker for the changes to take effect.
daemon.json
{ "bip": "192.168.1.5/24", "fixed-cidr": "192.168.1.5/25", "fixed-cidr-v6": "2001:db8::/64", "mtu": 1500, "default-gateway": "10.20.1.1", "default-gateway-v6": "2001:db8:abcd::89", "dns": ["10.20.1.2","10.20.1.3"] }
# run container in another network
# "--net=" 要放在 image 名前 才不會有 Error
docker run -itd --net=mybridge --name myubuntu ubuntu
# Get Container IP
# --format, -f <= Format the output using the given Go template
# Docker adds a template function, json
docker inspect -f '{{json .NetworkSettings.Networks}}' myubuntu
# 指定 Container 在某 bridge (--net) 用某 IP (--ip)
docker run -tid --name myubuntu --ip 10.0.0.11 --net mybridge ubuntu
* User specified IP address is supported on user defined networks only
Set hostname
-h, --hostname string
Overlay networking
When you create a service that uses an overlay network,
the manager node automatically extends the overlay network to nodes that run service tasks
Port forwarding (不是 NAT 來)
Specified Explicitly Mapping (-p, --publish=)
Format:
HostIP:hostPort:containerPort[/udp]
i.e.
Internet-->8080(Host)-->80(Container)
# 將 host 的 8080 map 到 contrainer 的 80
docker run -p 8080:80 friendlyhello
Auto map all exposed ports on the host (32768 to 60999)
usage
-P | --publish-all=true|false # Default: false
maps it to a host port somewhere within an ephemeral port range.
- Image’s Dockerfile: every port with an EXPOSE line
- Commandline flag: --expose <port> (e.g. --expose=3300-3310)
ephemeral port range
cat /proc/sys/net/ipv4/ip_local_port_range
i.e.
docker run -P <imageid>
Check port mapping
# List port mappings or a specific mapping for the container
docker port NAME
docker port oods
443/tcp -> 0.0.0.0:443 80/tcp -> 0.0.0.0:80
Proxy
Containers to the outside world(Internet)
# Docker host
sysctl net.ipv4.conf.all.forwarding=1
iptables -P FORWARD ACCEPT
EXPOSE (Incoming Ports)
Expose a port, or a range of ports (e.g. --expose=3300-3310) informs Docker that the container listens on the specified network ports at runtime.
Docker uses this information to interconnect containers using links and to set up port redirection on the host system.
--expose (Expose a port from the container, without publishing it to your host)
--link when starting the new client container, then the client container can access the exposed port via a private networking interface
Environment variables
Environment variables in the client container to help indicate which interface and port to use
# The default protocol, ip, and port of the service running in the container
LINKED-SERVER_PORT=tcp://172.17.0.8:80
# A specific protocol, ip, and port of various services
LINKED-SERVER_PORT_80_TCP=tcp://172.17.0.8:80
Remark
又或者寫成
LINKED-SERVER_PORT_80_TCP_PROTO=tcp LINKED-SERVER_PORT_80_TCP_ADDR=172.17.0.8 LINKED-SERVER_PORT_80_TCP_PORT=80
Linking (Communication between two containers)
# client locally refers to server as linked-server
docker run --name client --link server:linked-server <image>
# find out what host port the container’s port 22 is mapped to
docker port test_sshd 22
# Docker uses iptables under the hood to either accept or drop communication between containers.
--icc=true # allows containers to communicate with each other
--icc=false # means containers are isolated from each other.
Set Guest
# Network
# Sets the container's interface IPv4 address
--ip=""
# The MAC address in an Ethernet network
--mac-address=""
# Add link to another container in the form of "<name or id>[:alias]"
--link=[]
# Set the Network mode for the container
--net="mybridge"
# Publish a container's port, or range of ports, to the host.
-p, --publish=[]
i.e.
1234-1236:1222-1224
Share Directories via Volumes
作用: Bypasses the Union File System to provide several useful features for persistent or shared data
# Create a named container with volumes to share
docker run -v /mnt/volume1:/volume1 --name DATA busybox true
* -v, --volume value /<host path>:/<container path> # Bind mount a volume (default [])
* busybox - a small simpler image (simplest program that you can run)
* If the path /volume1 already exists inside the container’s image,
the /mnt/volume1 mount overlays but does not remove the pre-existing content.
# mount those data volumes into your application containers
docker run -t -i --rm --volumes-from DATA --name client1 ubuntu bash
* --rm - remove the container when it exit
docker run -v /var/volume1 -v /var/volume2 busybox true
# /var/logs into the container with read only permissions as /var/host_logs
docker run -t -i -v /var/logs:/var/host_logs:ro ubuntu bash
dockerfiles - building images
Image File: https://index.docker.io/
Official images: ubuntu, centos
Run Reference
Help:
man docker-run
Usage:
docker run [OPTIONS] IMAGE[:TAG] <COMMAND] [ARG...>
Background:
# Run container in the background (Default foreground mode)
-d
# container name
–name="" # 當沒有設定時, 那會 generate a random string name
# Allocate a pseudo-tty
-t
# Keep STDIN open even if not attached (-i, --interactive=true|false)
-i
# -a=[] <-- stdin, stdout, stderr
docker run -a stdin -a stdout -i -t ubuntu /bin/bash
# Docker write the container ID out to a file
--cidfile="": Write the container ID to the file\
# By default, all containers have networking enabled
-n=true : Completely disable networking
--dns=[] : Set custom dns servers for the container
# resourse:
-m="" # RAM: <number><m/g>
-c=0 # CPU shares (relative weight)
--oom-kill-disable=true|false # Whether to disable OOM Killer
Other:
--privileged=false # Docker will enable to access to all devices on the host
--lxc-conf=[] # --lxc-conf="lxc.cgroup.cpuset.cpus = 0,1"
# Automatically remove the container when it exits (Clean up)
--rm=false (incompatible with -d)
By default a container 's file system persists even after the container exits.
This makes debugging a lot easier (since you can inspect the final state) and you retain all your data by default.
But if you are running short-term foreground processes, these container file systems can really pile up.
If instead you 'd like Docker to automatically clean up the container and
remove the file system when the container exits (此 flag 相當於 docker stop 時自動執行 "docker rm")
"help" Command
docker help
Commands: attach Attach to a running container build Build a container from a Dockerfile commit Create a new image from a container's changes cp Copy files/folders from the containers filesystem to the host path diff Inspect changes on a container's filesystem events Get real time events from the server export Stream the contents of a container as a tar archive history Show the history of an image images List images import Create a new filesystem image from the contents of a tarball info Display system-wide information inspect Return low-level information on a container kill Kill a running container load Load an image from a tar archive login Register or Login to the docker registry server logs Fetch the logs of a container port Lookup the public-facing port which is NAT-ed to PRIVATE_PORT ps List containers pull Pull an image or a repository from the docker registry server push Push an image or a repository to the docker registry server restart Restart a running container rm Remove one or more containers rmi Remove one or more images run Run a command in a new container save Save an image to a tar archive search Search for an image in the docker index start Start a stopped container stop Stop a running container tag Tag an image into a repository top Lookup the running processes of a container version Show the docker version information wait Block until a container stops, then print its exit code
保儲 dockor image
CLI
- save
- load
# save - 將 Image 保存成 tar 檔案 (`docker images nginx`見到的 image 都會保存)
# streamed to stdout by default ( tar format )
docker save nginx > nginx-all.tar
# -o, --output="", 只保儲特定 tag
docker save --output=fedora-latest.tar fedora:latest
# load - 由 STDIN 載入 tar 格式的 docker image
# -i, --input=""
docker load -i nginx-all.tar
ef68f6734aa4: Loading layer [==================================================>] 58.44 MB/58.44 MB ad5345cbb119: Loading layer [==================================================>] 54.39 MB/54.39 MB ece4f9fdef59: Loading layer [==================================================>] 3.584 kB/3.584 kB Loaded image: docker.io/nginx:latest d6a12a0f1fe5: Loading layer [==================================================>] 54.38 MB/54.38 MB 7127e93b8b58: Loading layer [==================================================>] 3.584 kB/3.584 kB Loaded image: docker.io/nginx:stable
Remark
save, load 是針對 Image 的
匯入 & 匯出 Container
# export - Export the contents of a filesystem as a tar archive to STDOUT
docker export ID > ubuntu.tar
# import - Create a new image from the contents of a tarball
docker import ubuntu.tar - ubuntu:v3.5
docker logs
# logs - batch-retrieves whatever logs are present at the time of execution.
# docker logs cli support json-file and journald backend only
docker logs [OPTS] CONTAINER
OPTS
- --timestamps , -t # Show timestamp
- --tail N # Number of lines to show from the end of the logs
- --follow , -f # Follow log output
- --since # Show logs since timestamp (e.g. 2013-01-02T13:23:37)
- --until # Show logs before a timestamp (e.g. 2013-01-02T13:23:37)
* this command is only functional for containers that are started with the json-file or journald logging driver
(If you do not specify a logging driver, the default is json-file)
i.e.
# 過去 10 min 內的 log
docker logs --since 10m rsvp
Checking current default logging driver
docker info --format '{{.LoggingDriver}}'
json-file
Checking current logging driver for container
docker inspect -f '{{.HostConfig.LogConfig.Type}}' <CONTAINER>
Configure the logging driver for a container
docker run -it --log-driver none alpine ash
logging driver modes:
Docker provides two modes for delivering messages from the container to the log driver:
- "blocking": blocking delivery from container to driver (Default)
-
"non-blocking": stores log messages in an intermediate per-container ring buffer for consumption by driver
(Default: 1 megabyte)
* When the buffer is full and a new message is enqueued, the oldest message in memory is dropped.
* Applications are likely to fail in unexpected ways when STDERR or STDOUT streams block
Change setting
docker run -it --log-opt mode=non-blocking --log-opt max-buffer-size=4m alpine ping 127.0.0.1
Other Useful Cli (diff, cp)
# diff
diff - Inspect changes on a container's filesystem
# docker diff CONTAINER
`A` - Add `D` - Delete `C` - Change
# cp
docker cp CONTAINER:PATH HOSTPATH