一张图概括整篇文章内容:
来自:https://medium.com/@nagarwal/lifecycle-of-docker-container-d2da9f85959
lxc->libcontainer->runC
OCI(Open Container Initiative):围绕容器格式和运行时制定一个开放的工业化标准
OCF(Open Container Format):
docker镜像仓库:https://hub.docker.com
docker:C/S架构:docker client,DOCKER_HOST(运行docker_daemon),docker Registry
DOCKER_HOST运行Docker_daemon进程,监听在某个socket上:默认socket为unix socket,只允许本地连接;还有ipv4和ipv6两种监听方式。DOCKER_HOST上面运行容器,存放容器运行容器的镜像
Registry:DOCKER_HOST的镜像来自于Registry
DOCKER_HOST与Registry之间拉取和推送镜像采用https协议
docker镜像加速:docker服务器在国外,国内拉取镜像很慢
docker有企业版和社区版两种:docker-ee,docker-ce
docker镜像是分层创建的
标识一个镜像: 仓库名:标签 如:nginx:1.15 nginx:latest nginx:stable
容器有生命周期
Docker objects:images,containers,networks,volumes,plugins,other objects
安装及使用docker
docker安装环境要求:64位CPU,内核3.10+,cgroups and namespaces
安装:默认仓库安装或者安装docker源(推荐)
[root@docker2 ~]# wget https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo -O /etc/yum.repos.d/docker.repo
[root@docker2 ~]# yum repolist
[root@docker2 ~]# yum list docker-ce --showduplicates
已加载插件:fastestmirror
Loading mirror speeds from cached hostfile
* base: mirrors.aliyun.com
* extras: mirrors.aliyun.com
* updates: mirrors.aliyun.com
可安装的软件包
docker-ce.x86_64 17.03.0.ce-1.el7.centos docker-ce-stable
docker-ce.x86_64 17.03.1.ce-1.el7.centos docker-ce-stable
docker-ce.x86_64 17.03.2.ce-1.el7.centos docker-ce-stable
docker-ce.x86_64 17.03.3.ce-1.el7 docker-ce-stable
docker-ce.x86_64 17.06.0.ce-1.el7.centos docker-ce-stable
docker-ce.x86_64 17.06.1.ce-1.el7.centos docker-ce-stable
docker-ce.x86_64 17.06.2.ce-1.el7.centos docker-ce-stable
docker-ce.x86_64 17.09.0.ce-1.el7.centos docker-ce-stable
docker-ce.x86_64 17.09.1.ce-1.el7.centos docker-ce-stable
docker-ce.x86_64 17.12.0.ce-1.el7.centos docker-ce-stable
docker-ce.x86_64 17.12.1.ce-1.el7.centos docker-ce-stable
docker-ce.x86_64 18.03.0.ce-1.el7.centos docker-ce-stable
docker-ce.x86_64 18.03.1.ce-1.el7.centos docker-ce-stable
docker-ce.x86_64 18.06.0.ce-3.el7 docker-ce-stable
docker-ce.x86_64 18.06.1.ce-3.el7 docker-ce-stable
docker-ce.x86_64 3:18.09.0-3.el7 docker-ce-stable
[root@docker2 ~]# yum install docker-ce-18.06.1.ce-3.el7 -y
docker组件:
环境配置文件:
/etc/sysconfig/docker-network/etc/sysconfig/docker-network/etc/sysconfig/docker
unit file:
/etc/systemd/system/docker.service
Docker Registry配置文件:
/etc/container/registries.conf
配置文件:/etc/docker/docker.daemon.json
docker镜像加速:
- docker cn
- 阿里云镜像加速
- 中国科技大学
[root@docker2 ~]# mkdir -p /etc/docker
[root@docker2 ~]# cat >> /etc/docker/daemon.json <<EOF
> {
> "registry-mirrors": ["https://7f28zkr3.mirror.aliyuncs.com"]
> }
> EOF
启动容器:
[root@docker2 ~]# systemctl start docker.service
[root@docker2 ~]# systemctl enable docker.service
Created symlink from /etc/systemd/system/multi-user.target.wants/docker.service to /usr/lib/systemd/system/docker.service.
[root@docker2 ~]# docker version
Client:
Version: 18.06.1-ce
API version: 1.38
Go version: go1.10.3
Git commit: e68fc7a
Built: Tue Aug 21 17:23:03 2018
OS/Arch: linux/amd64
Experimental: false
Server:
Engine:
Version: 18.06.1-ce
API version: 1.38 (minimum version 1.12)
Go version: go1.10.3
Git commit: e68fc7a
Built: Tue Aug 21 17:25:29 2018
OS/Arch: linux/amd64
Experimental: false
docker info 查看docker信息
[root@docker2 ~]# docker info
Containers: 0
Running: 0
Paused: 0
Stopped: 0
Images: 0
Server Version: 18.06.1-ce
Storage Driver: overlay2
Backing Filesystem: xfs
Supports d_type: true
Native Overlay Diff: true
Logging Driver: json-file
Cgroup Driver: cgroupfs
Plugins:
Volume: local
Network: bridge host macvlan null overlay
Log: awslogs fluentd gcplogs gelf journald json-file logentries splunk syslog
Swarm: inactive
Runtimes: runc
Default Runtime: runc
Init Binary: docker-init
containerd version: 468a545b9edcd5932818eb9de8e72413e616e86e
runc version: 69663f0bd4b60df09991c08812a60108003fa340
init version: fec3683
Security Options:
seccomp
Profile: default
Kernel Version: 3.10.0-862.el7.x86_64
Operating System: CentOS Linux 7 (Core)
OSType: linux
Architecture: x86_64
CPUs: 1
Total Memory: 974.6MiB
Name: docker2
ID: R4C5:VHVN:YWXB:SFH5:EZJP:I3SJ:7QFG:43PY:344D:3JHJ:DHF4:WSJ5
Docker Root Dir: /var/lib/docker
Debug Mode (client): false
Debug Mode (server): false
Registry: https://index.docker.io/v1/
Labels:
Experimental: false
Insecure Registries:
127.0.0.0/8
Registry Mirrors:
https://7f28zkr3.mirror.aliyuncs.com/
Live Restore Enabled: false
docker对镜像的操作:
[root@docker2 ~]# docker image --help
Usage: docker image COMMAND
Manage images
Commands:
build Build an image from a Dockerfile
history Show the history of an image
import Import the contents from a tarball to create a filesystem image
inspect Display detailed information on one or more images
load Load an image from a tar archive or STDIN
ls List images
prune Remove unused images
pull Pull an image or a repository from a registry
push Push an image or a repository to a registry
rm Remove one or more images
save Save one or more images to a tar archive (streamed to STDOUT by default)
tag Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE
Run 'docker image COMMAND --help' for more information on a command.
docker search搜索镜像:
[root@docker2 ~]# docker search nginx
NAME DESCRIPTION STARS OFFICIAL AUTOMATED
nginx Official build of Nginx. 10645 [OK]
jwilder/nginx-proxy Automated Nginx reverse proxy for docker con… 1497 [OK]
richarvey/nginx-php-fpm Container running Nginx + PHP-FPM capable of… 671 [OK]
jrcs/letsencrypt-nginx-proxy-companion LetsEncrypt container to use with nginx as p… 457 [OK]
kong Open-source Microservice & API Management la… 271 [OK]
webdevops/php-nginx Nginx with PHP-FPM 119 [OK]
kitematic/hello-world-nginx A light-weight nginx container that demonstr… 116
docker image 拉取镜像:
[root@docker2 ~]# docker image pull nginx:1.15-alpine
1.15-alpine: Pulling from library/nginx
cd784148e348: Pull complete
6e3058b2db8a: Pull complete
7ca4d29669c1: Pull complete
a14cf6997716: Pull complete
Digest: sha256:385fbcf0f04621981df6c6f1abd896101eb61a439746ee2921b26abc78f45571
Status: Downloaded newer image for nginx:1.15-alpine
[root@docker2 ~]# docker image pull busybox
Using default tag: latest
latest: Pulling from library/busybox
b4a6e23922dd: Pull complete
Digest: sha256:8ccbac733d19c0dd4d70b4f0c1e12245b5fa3ad24758a11035ee505c629c0796
Status: Downloaded newer image for busybox:latest
查看镜像:docker image ls
[root@docker2 ~]# docker image ls --help
Usage: docker image ls [OPTIONS] [REPOSITORY[:TAG]]
List images
Aliases:
ls, images, list
Options:
-a, --all Show all images (default hides intermediate images)
--digests Show digests
-f, --filter filter Filter output based on conditions provided
--format string Pretty-print images using a Go template
--no-trunc Don't truncate output
-q, --quiet Only show numeric IDs
[root@docker2 ~]# docker image ls --no-trunc
REPOSITORY TAG IMAGE ID CREATED SIZE
nginx 1.15-alpine sha256:315798907716a51610bb3c270c191e0e61112b19aae9a3bb0c2a60c53d074750 3 days ago 17.8MB
busybox latest sha256:758ec7f3a1ee85f8f08399b55641bfb13e8c1109287ddc5e22b68c3d653152ee 3 days ago
对docker容器的操作:
[root@docker2 ~]# docker container --help
Usage: docker container COMMAND
Manage containers
Commands:
attach Attach local standard input, output, and error streams to a running container
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
exec Run a command in a running container
export Export a container's filesystem as a tar archive
inspect Display detailed information on one or more containers
kill Kill one or more running containers
logs Fetch the logs of a container
ls List containers
pause Pause all processes within one or more containers
port List port mappings or a specific mapping for the container
prune Remove all stopped containers
rename Rename a container
restart Restart one or more containers
rm Remove one or more containers
run Run a command in a new container
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
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
wait Block until one or more containers stop, then print their exit codes
Run 'docker container COMMAND --help' for more information on a command.
运行一个容器:docker container run
[root@docker2 ~]# 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@docker2 ~]# docker container run --name b1 -it busybox:latest
/ # ls /
bin dev etc home proc root sys tmp usr var
在b1容器上跑一个httpd
容器内运行httpd
/ # httpd -h
httpd: option requires an argument -- h
BusyBox v1.29.3 (2018-12-24 21:25:20 UTC) multi-call binary.
Usage: httpd [-ifv[v]] [-c CONFFILE] [-p [IP:]PORT] [-u USER[:GRP]] [-r REALM] [-h HOME]
or httpd -d/-e/-m STRING
Listen for incoming HTTP requests
-i Inetd mode
-f Don't daemonize
-v[v] Verbose
-p [IP:]PORT Bind to IP:PORT (default *:80)
-u USER[:GRP] Set uid/gid after binding to port
-r REALM Authentication Realm for Basic Authentication
-h HOME Home directory (default .)
-c FILE Configuration file (default {/etc,HOME}/httpd.conf)
-m STRING MD5 crypt STRING
-e STRING HTML encode STRING
-d STRING URL decode STRING
/ # mkdir /data/html -p
/ # echo "busybox" >> /data/html/index.html
/ # httpd -f -h /data/html
新开shell,查看b1容器的详情,IP,
[root@docker2 ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
4b046064f896 busybox:latest "sh" 23 minutes ago Up 23 minutes b1
[root@docker2 ~]# docker inspect b1 | grep IPAddress
"SecondaryIPAddresses": null,
"IPAddress": "172.17.0.2",
"IPAddress": "172.17.0.2",
通过IP访问该容器的服务:
[root@docker2 ~]# curl 172.17.0.2
busybox
退出容器再查看:(docker ps 与docker container ls一样)
/ # httpd -f -h /data/html
^C
/ # exit
[root@docker2 ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
[root@docker2 ~]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
4b046064f896 busybox:latest "sh" 25 minutes ago Exited (130) 16 seconds ago b1
[root@docker2 ~]# docker container ls
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
[root@docker2 ~]# docker container ls -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
4b046064f896 busybox:latest "sh" 26 minutes ago Exited (130) 36 seconds ago b1
启动停止的容器:
[root@docker2 ~]# docker start -a -i b1
/ #
新开shell查看:
[root@docker2 ~]# docker container ls
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
4b046064f896 busybox:latest "sh" 30 minutes ago Up 37 seconds b1
使用kill强行停掉容器(测试):
[root@docker2 ~]# docker kill b1
b1
[root@docker2 ~]# docker container ls
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
运行一个容器,指定容器名字为web1,后台运行,使用nginx:1.15-alpine镜像
[root@docker2 ~]# docker container run --name web1 -d nginx:1.15-alpine
aa7f935730ed5404a1ac81709ccf02d99bdbab8314a27e48884012ce23627ae3
[root@docker2 ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
aa7f935730ed nginx:1.15-alpine "nginx -g 'daemon of…" 5 seconds ago Up 4 seconds 80/tcp web1
查看该容器详细信息:
[root@docker2 ~]# docker inspect web1
[root@docker2 ~]# docker inspect web1 | grep -i ipaddress
"SecondaryIPAddresses": null,
"IPAddress": "172.17.0.2",
"IPAddress": "172.17.0.2",
[root@docker2 ~]# curl -s 172.17.0.2 | grep -i welcome
<title>Welcome to nginx!</title>
<h1>Welcome to nginx!</h1>
运行一个容器,名字为kvstor1,后台运行,使用redis:5镜像
[root@docker2 ~]# docker container run --name kvstor1 -d redis:5
Unable to find image 'redis:5' locally
5: Pulling from library/redis
177e7ef0df69: Pull complete
66ec699db42d: Pull complete
9af6d87fd347: Pull complete
de9172cdb09c: Pull complete
27733a222e28: Pull complete
ef1ae1903ba4: Pull complete
Digest: sha256:86654d77602cbfeb873191488d176b215067549b7491364c3f84046f5753f0a0
Status: Downloaded newer image for redis:5
b2a481f1fde0e1ec517ed01684fdd2b1fa7d51d8738aee46342b0ea2ced8c54e
[root@docker2 ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
b2a481f1fde0 redis:5 "docker-entrypoint.s…" 5 seconds ago Up 4 seconds 6379/tcp kvstor1
aa7f935730ed nginx:1.15-alpine "nginx -g 'daemon of…" 8 minutes ago Up 8 minutes 80/tcp web1
在运行的容器中执行命令:
[root@docker2 ~]# docker container exec --help
Usage: docker container 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
-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>])
-w, --workdir string Working directory inside the container
[root@docker2 ~]# docker container exec -it kvstor1 /bin/sh
# ls /
bin boot data dev etc home lib lib64 media mnt opt proc root run sbin srv sys tmp usr var
# redis-cli
127.0.0.1:6379> keys *
(empty list or set)
127.0.0.1:6379> SELECT 1
OK
127.0.0.1:6379[1]> exit
# exit
查看一个容器的日志,docker container logs
[root@docker2 ~]# docker container logs --help
Usage: docker container logs [OPTIONS] CONTAINER
Fetch the logs of a container
Options:
--details Show extra details provided to logs
-f, --follow Follow log output
--since string Show logs since timestamp (e.g. 2013-01-02T13:23:37) or relative (e.g. 42m for 42 minutes)
--tail string Number of lines to show from the end of the logs (default "all")
-t, --timestamps Show timestamps
--until string Show logs before a timestamp (e.g. 2013-01-02T13:23:37) or relative (e.g. 42m for 42 minutes)
[root@docker2 ~]# docker container logs web1
172.17.0.1 - - [30/Dec/2018:06:40:19 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0" "-"
172.17.0.1 - - [30/Dec/2018:06:40:41 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0" "-"
172.17.0.1 - - [30/Dec/2018:06:40:48 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0" "-"
对docker网络的操作:
[root@docker2 ~]# docker network --help
Usage: docker network COMMAND
Manage networks
Commands:
connect Connect a container to a network
create Create a network
disconnect Disconnect a container from a network
inspect Display detailed information on one or more networks
ls List networks
prune Remove all unused networks
rm Remove one or more networks
Run 'docker network COMMAND --help' for more information on a command.
[root@docker2 ~]# docker network ls
NETWORK ID NAME DRIVER SCOPE
1f1d3b3c2f74 bridge bridge local
76bea4912e96 host host local
a33261fb3dc7 none null local