docker入门级详解
1 docker安装
yum install docker[root@topcheer ~]# systemctl start docker[root@topcheer ~]# mkdir -p /etc/docker [root@topcheer ~]# vim /etc/docker/daemon.json #配置阿里云镜像加速{"registry-mirrors": ["XXXXXXXXXXXXXXXX"]}[root@topcheer ~]# systemctl daemon-reload #加载配置文件 [root@topcheer ~]# systemctl restart docker #重启[root@topcheer ~]#
2 docker命令
2.1 docker帮助命令
-
docker version
1 [root@topcheer ~]# docker version 2 Client: 3 Version: 1.13.1 4 API version: 1.26 5 Package version: docker-1.13.1-103.git7f2769b.el7.centos.x86_64 6 Go version: go1.10.3 7 Git commit: 7f2769b/1.13.1 8 Built:Sun Sep 15 14:06:47 2019 9 OS/Arch: linux/amd6410 11 Server:12 Version: 1.13.113 API version: 1.26 (minimum version 1.12)14 Package version: docker-1.13.1-103.git7f2769b.el7.centos.x86_6415 Go version: go1.10.316 Git commit: 7f2769b/1.13.117 Built:Sun Sep 15 14:06:47 201918 OS/Arch: linux/amd6419 Experimental:false20 [root@topcheer ~]#
-
docker info
1 [root@topcheer ~]# docker info 2 Containers: 1 3 Running: 0 4 Paused: 0 5 Stopped: 1 6 Images: 1 7 Server Version: 1.13.1 8 Storage Driver: overlay2 9 Backing Filesystem: xfs10 Supports d_type: true11 Native Overlay Diff: true12 Logging Driver: jouald13 Cgroup Driver: systemd14 Plugins:15 Volume: local16 Network: bridge host macvlan null overlay17 Swarm: inactive18 Runtimes: docker-runc runc19 Default Runtime: docker-runc20 Init Binary: /usr/libexec/docker/docker-init-current21 containerd version: (expected: aa8187dbd3b7ad67d8e5e3a15115d3eef43a7ed1)22 runc version: 9c3c5f853ebf0ffac0d087e94daef462133b69c7 (expected: 9df8b306d01f59d3a8029be411de015b7304dd8f)23 init version: fec3683b971d9c3ef73f284f176672c44b448662 (expected: 949e6facb77383876aeff8a6944dde66b3089574)24 Security Options:25 seccomp26WARNING: You're not using the default seccomp profile27Profile: /etc/docker/seccomp.json28 selinux29 Keel Version: 3.10.0-957.el7.x86_6430 Operating System: CentOS Linux 7 (Core)31 OSType: linux32 Architecture: x86_6433 Number of Docker Hooks: 334 CPUs: 435 Total Memory: 1.777 GiB36 Name: topcheer37 ID: SR5A:YSH6:3YGH:YEZ4:PWLB:EEVE:3L5S:Z5AR:ARIA:SDGX:CZI5:MJ7O38 Docker Root Dir: /var/lib/docker39 Debug Mode (client): false40 Debug Mode (server): false41 Registry: https://index.docker.io/v1/42 Experimental: false43 Insecure Registries:44 127.0.0.0/845 Registry Mirrors:46 https://lara9y80.mirror.aliyuncs.com47 Live Restore Enabled: false48 Registries: docker.io (secure)49 [root@topcheer ~]#
-
docker --help
[root@topcheer ~]# docker --helpUsage: docker COMMANDA self-sufficient runtime for containersOptions: --config string Location of client config files (default "/root/.docker") -D, --debug Enable debug mode --helpPrint usage -H, --host list Daemon socket(s) to connect to (default []) -l, --log-level stringSet the logging level ("debug", "info", "wa", "error", "fatal") (default "info") --tlsUse TLS; implied by --tlsverify --tlscacert stringTrust certs signed only by this CA (default "/root/.docker/ca.pem") --tlscert string Path to TLS certificate file (default "/root/.docker/cert.pem") --tlskey string Path to TLS key file (default "/root/.docker/key.pem") --tlsverify Use TLS and verify the remote -v, --versionPrint version information and quitManagement Commands: containerManage containers imageManage images network Manage networks nodeManage Swarm nodes plugin Manage plugins secret Manage Docker secrets service Manage services stackManage Docker stacks swarmManage Swarm system Manage Docker volume Manage volumesCommands: attach Attach to a running container buildBuild 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 diffInspect changes on a container's filesystem events Get real time events from the server execRun 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 infoDisplay system-wide information inspect Retu low-level information on Docker objects killKill one or more running containers loadLoad an image from a tar archive or STDIN loginLog in to a Docker registry logout Log out from a Docker registry logsFetch the logs of a container pausePause all processes within one or more containers portList port mappings or a specific mapping for the container ps List containers pullPull an image or a repository from a registry pushPush 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 saveSave one or more images to a tar archive (streamed to STDOUT by default) search Search the Docker Hub for images startStart one or more stopped containers statsDisplay a live stream of container(s) resource usage statistics stopStop 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 waitBlock until one or more containers stop, then print their exit codesRun 'docker COMMAND --help' for more information on a command.[root@topcheer ~]#
2.2 镜像命令
-
docker images
[root@topcheer ~]# docker imagesREPOSITORY TAG IMAGE IDCREATED SIZEdocker.io/hello-worldlatest fce289e99eb98 months ago1.84 kB[root@topcheer ~]#REPOSITORY:表示镜像的仓库源TAG:镜像的标签IMAGE ID:镜像IDCREATED:镜像创建时间SIZE:镜像大小 同一仓库源可以有多个 TAG,代表这个仓库源的不同个版本,我们使用 REPOSITORY:TAG 来定义不同的镜像。如果你不指定一个镜像的版本标签,例如你只使用 ubuntu,docker 将默认使用 ubuntu:latest 镜像
-
docker search
[root@topcheer ~]# docker search redisINDEXNAMEDESCRIPTION STARS OFFICIALAUTOMATEDdocker.iodocker.io/redisRedis is an open source key-value store th...7342 [OK]docker.iodocker.io/bitnami/redisBitnami Redis Docker Image 127 [OK]docker.iodocker.io/sameersbn/redis 77[OK]docker.iodocker.io/grokzen/redis-clusterRedis cluster 3.0, 3.2, 4.0 & 5.056docker.iodocker.io/rediscommander/redis-commanderAlpine image for redis-commander - Redis m...31[OK]docker.iodocker.io/kubeguide/redis-masterredis-master with "Hello World!"29docker.iodocker.io/redislabs/redis Clustered in-memory database engine compat...23docker.iodocker.io/arm32v7/redisRedis is an open source key-value store th...17docker.iodocker.io/redislabs/redisearch Redis With the RedisSearch module pre-load...17docker.iodocker.io/oliver006/redis_exporter Prometheus Exporter for Redis Metrics. Su...15docker.iodocker.io/webhippie/redis Docker images for Redis 10[OK]docker.iodocker.io/s7anley/redis-sentinel-dockerRedis Sentinel 9[OK]docker.iodocker.io/insready/redis-stat Docker image for the real-time Redis monit...8[OK]docker.iodocker.io/redislabs/redisgraph A graph database module for Redis8[OK]docker.iodocker.io/arm64v8/redisRedis is an open source key-value store th...6docker.iodocker.io/bitnami/redis-sentinelBitnami Docker Image for Redis Sentinel 6[OK]docker.iodocker.io/centos/redis-32-centos7 Redis in-memory data structure store, used...4docker.iodocker.io/redislabs/redismodAn automated build of redismod - latest Re...4[OK]docker.iodocker.io/circleci/redisCircleCI images for Redis2[OK]docker.iodocker.io/frodenas/redisA Docker Image for Redis2[OK]docker.iodocker.io/runnable/redis-stunnelstunnel to redis provided by linking conta...1[OK]docker.iodocker.io/tiredofit/redis Redis Server w/ Zabbix monitoring and S6 O...1[OK]docker.iodocker.io/wodby/redis Redis container image with orchestration1[OK]docker.iodocker.io/cflondonservices/redisDocker image for running redis 0docker.iodocker.io/xetamus/redis-resourceforked redis-resource0[OK][root@topcheer ~]#
-
docker pull
[root@topcheer ~]# docker pull docker.io/redisUsing default tag: latestTrying to pull repository docker.io/library/redis ...latest: Pulling from docker.io/library/redisb8f262c62ec6: Pull complete93789b5343a5: Pull complete49cdbb315637: Pull complete2c1ff453e5c9: Pull complete9341ee0a5d4a: Pull complete770829e1df34: Pull completeDigest: sha256:5dcccb533dc0deacce4a02fe9035134576368452db0b4323b98a4b2ba2d3b302Status: Downloaded newer image for docker.io/redis:latest[root@topcheer ~]# docker imagesREPOSITORY TAG IMAGE IDCREATED SIZEdocker.io/redis latest 63130206b0fa9 days ago 98.2 MBdocker.io/hello-worldlatest fce289e99eb98 months ago1.84 kB[root@topcheer ~]#
-
docker rmi
[root@topcheer ~]# docker rmi 63130206b0faUntagged: docker.io/redis:latestUntagged: docker.io/redis@sha256:5dcccb533dc0deacce4a02fe9035134576368452db0b4323b98a4b2ba2d3b302Deleted: sha256:63130206b0fa808e4545a0cb4a1f14f6d40b8a7e2e6fda0a31fd326c2ac0971cDeleted: sha256:9476758634326bb436208264d0541e9a0d42e4add35d00c2a7408f810223013dDeleted: sha256:0f3d9de16a216bfa5e2c2bd0e3c2ba83afec01a1b326d9f39a5ea7aecc112bafDeleted: sha256:452d665d4efca3e6067c89a332c878437d250312719f9ea8fff8c0e350b6e471Deleted: sha256:d6aec371927a9d4bfe4df4ee8e510624549fc08bc60871ce1f145997f49d4d37Deleted: sha256:2957e0a13c30e89650dd6c00644c04aa87ce516284c76a67c4b32cbb877de178Deleted: sha256:2db44bce66cde56fca25aeeb7d09dc924b748e3adfe58c9cc3eb2bd2f68a1b68[root@topcheer ~]# docker imagesREPOSITORY TAG IMAGE IDCREATED SIZEdocker.io/hello-worldlatest fce289e99eb98 months ago1.84 kB[root@topcheer ~]#
2.3 容器命令
-
docker run
OPTIONS说明(常用):有些是一个减号,有些是两个减号 --name="容器新名字": 为容器指定一个名称;-d: 后台运行容器,并返回容器ID,也即启动守护式容器;-i:以交互模式运行容器,通常与 -t 同时使用;-t:为容器重新分配一个伪输入终端,通常与 -i 同时使用;-P: 随机端口映射;-p: 指定端口映射,有以下四种格式 ip:hostPort:containerPort ip::containerPort hostPort:containerPort containerPort [root@topcheer ~]# docker run -it centos /bin/bash[root@3d2a94b63807 /]# cd /[root@3d2a94b63807 /]# ll
-
docker ps
OPTIONS说明(常用): -a :列出当前所有正在运行的容器+历史上运行过的-l :显示最近创建的容器。-n:显示最近n个创建的容器。-q :静默模式,只显示容器编号。--no-trunc :不截断输出。退出容器 exit:容器停止退出 crtl p q容器不停止退出[root@topcheer ~]# docker psCONTAINER IDIMAGECOMMAND CREATED STATUS PORTSNAMES3d2a94b63807centos "/bin/bash" 3 minutes agoUp 3 minutesnostalgic_darwin[root@topcheer ~]#
-
docker stop
root@topcheer ~]# docker psCONTAINER IDIMAGECOMMAND CREATED STATUS PORTSNAMES3d2a94b63807centos "/bin/bash" 3 minutes agoUp 3 minutesnostalgic_darwin[root@topcheer ~]# docker stop 3d2a94b638073d2a94b63807
-
docker start
[root@topcheer ~]# docker start 3d2a94b638073d2a94b63807[root@topcheer ~]# docker psCONTAINER IDIMAGECOMMAND CREATED STATUS PORTSNAMES3d2a94b63807centos "/bin/bash" 6 minutes agoUp 17 secondsnostalgic_darwin[root@topcheer ~]#
-
docker rm
[root@topcheer ~]# docker rm -f $(docker ps -a -q)3d2a94b63807299b22d3d143[root@topcheer ~]# docker psCONTAINER IDIMAGECOMMAND CREATED STATUS PORTSNAMES[root@topcheer ~]#
-
docker run -d
[root@topcheer ~]# docker run -d centos3c618cadb296fd013384201958f175085395a505a0aa1f7727e3c24b744b0b7f[root@topcheer ~]# 问题:然后docker ps -a 进行查看, 会发现容器已经退出很重要的要说明的一点: Docker容器后台运行,就必须有一个前台进程.容器运行的命令如果不是那些一直挂起的命令(比如运行top,tail),就是会自动退出的。 这个是docker的机制问题,比如你的web容器,我们以nginx为例,正常情况下,我们配置启动服务只需要启动响应的service即可。例如service nginx start但是,这样做,nginx为后台进程模式运行,就导致docker前台没有运行的应用,这样的容器后台启动后,会立即自杀因为他觉得他没事可做了.所以,最佳的解决方案是,将你要运行的程序以前台进程的形式运行
-
docker logs
*-t 是加入时间戳*-f 跟随最新的日志打印*--tail 数字 显示最后多少条[root@topcheer ~]# docker run -d centos /bin/sh -c "while true;do echo hello zzyy;sleep 2;done"6c4bb3ce4c35a5380b553e686b806a1581bfb8dd0a115f63fa9b14da6195e667[root@topcheer ~]# docker ps -aCONTAINER IDIMAGECOMMAND CREATED STATUS PORTSNAMES6c4bb3ce4c35centos "/bin/sh -c 'while..."6 seconds agoUp 4 secondseloquent_shannon3c618cadb296centos "/bin/bash" About a minute agoExited (0) About a minute agoupbeat_jepsen[root@topcheer ~]# docker logs -f -t --tail 6c4bb3ce4c35"docker logs" requires exactly 1 argument(s).See 'docker logs --help'.Usage: docker logs [OPTIONS] CONTAINERFetch the logs of a container[root@topcheer ~]# docker ps -aCONTAINER IDIMAGECOMMAND CREATED STATUS PORTSNAMES6c4bb3ce4c35centos "/bin/sh -c 'while..."47 seconds ago Up 46 seconds eloquent_shannon3c618cadb296centos "/bin/bash" 2 minutes agoExited (0) 2 minutes agoupbeat_jepsen[root@topcheer ~]# docker logs -tf --tail10 6c4bb3ce4c35unknown flag: --tail10See 'docker logs --help'.[root@topcheer ~]# docker logs -tf --tail 10 6c4bb3ce4c352019-09-22T10:23:14.595414000Z hello zzyy2019-09-22T10:23:16.597109000Z hello zzyy2019-09-22T10:23:18.600019000Z hello zzyy2019-09-22T10:23:20.602673000Z hello zzyy2019-09-22T10:23:22.605026000Z hello zzyy2019-09-22T10:23:24.625059000Z hello zzyy
-
docker top 查看容器内运行的进程
[root@topcheer ~]# docker top 6c4bb3ce4c35UID PID PPIDCSTIMETTY TIMECMDroot116050 116030 018:21?00:00:00/bin/sh -c while true;do echo hello zzyy;sleep 2;doneroot116250 116050 218:25?00:00:00sleep 2[root@topcheer ~]#
-
docker inspect 查看容器内部细节
[root@topcheer ~]# docker inspect 6c4bb3ce4c35[{"Id": "6c4bb3ce4c35a5380b553e686b806a1581bfb8dd0a115f63fa9b14da6195e667","Created": "2019-09-22T10:21:57.924998005Z","Path": "/bin/sh","Args": ["-c","while true;do echo hello zzyy;sleep 2;done"],"State": {"Status": "running","Running": true,"Paused": false,"Restarting": false,"OOMKilled": false,"Dead": false,"Pid": 116050,"ExitCode": 0,"Error": "","StartedAt": "2019-09-22T10:21:58.43216616Z","FinishedAt": "0001-01-01T00:00:00Z"},"Image": "sha256:67fa590cfc1c207c30b837528373f819f6262c884b7e69118d060a0c04d70ab8","ResolvConfPath": "/var/lib/docker/containers/6c4bb3ce4c35a5380b553e686b806a1581bfb8dd0a115f63fa9b14da6195e667/resolv.conf","HostnamePath": "/var/lib/docker/containers/6c4bb3ce4c35a5380b553e686b806a1581bfb8dd0a115f63fa9b14da6195e667/hostname","HostsPath": "/var/lib/docker/containers/6c4bb3ce4c35a5380b553e686b806a1581bfb8dd0a115f63fa9b14da6195e667/hosts","LogPath": "","Name": "/eloquent_shannon","RestartCount": 0,"Driver": "overlay2","MountLabel": "system_u:object_r:svirt_sandbox_file_t:s0:c71,c940","ProcessLabel": "system_u:system_r:svirt_lxc_net_t:s0:c71,c940","AppArmorProfile": "","ExecIDs": null,"HostConfig": {"Binds": null,"ContainerIDFile": "","LogConfig": {"Type": "jouald","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": "","UsesMode": "","ShmSize": 67108864,"Runtime": "docker-runc","ConsoleSize": [0,0],"Isolation": "","CpuShares": 0,"Memory": 0,"NanoCpus": 0,"CgroupParent": "","BlkioWeight": 0,"BlkioWeightDevice": null,"BlkioDeviceReadBps": null,"BlkioDeviceWriteBps": null,"BlkioDeviceReadIOps": null,"BlkioDeviceWriteIOps": null,"CpuPeriod": 0,"CpuQuota": 0,"CpuRealtimePeriod": 0,"CpuRealtimeRuntime": 0,"CpusetCpus": "","CpusetMems": "","Devices": [],"DiskQuota": 0,"KeelMemory": 0,"MemoryReservation": 0,"MemorySwap": 0,"MemorySwappiness": -1,"OomKillDisable": false,"PidsLimit": 0,"Ulimits": null,"CpuCount": 0,"CpuPercent": 0,"IOMaximumIOps": 0,"IOMaximumBandwidth": 0},"GraphDriver": {"Name": "overlay2","Data": {"LowerDir": "/var/lib/docker/overlay2/d8d3dca6c9115b3c782bf358a744475e78f5e62b627cca79e10a34e754310933-init/diff:/var/lib/docker/overlay2/7bc85336eb8ca768f43d8eb3d5f27bdf35fa99068be45c84622d18c0f87c90bd/diff","MergedDir": "/var/lib/docker/overlay2/d8d3dca6c9115b3c782bf358a744475e78f5e62b627cca79e10a34e754310933/merged","UpperDir": "/var/lib/docker/overlay2/d8d3dca6c9115b3c782bf358a744475e78f5e62b627cca79e10a34e754310933/diff","WorkDir": "/var/lib/docker/overlay2/d8d3dca6c9115b3c782bf358a744475e78f5e62b627cca79e10a34e754310933/work"}},"Mounts": [],"Config": {"Hostname": "6c4bb3ce4c35","Domainname": "","User": "","AttachStdin": false,"AttachStdout": false,"AttachStderr": false,"Tty": false,"OpenStdin": false,"StdinOnce": false,"Env": ["PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"],"Cmd": ["/bin/sh","-c","while true;do echo hello zzyy;sleep 2;done"],"Image": "centos","Volumes": null,"WorkingDir": "","Entrypoint": null,"OnBuild": null,"Labels": {"org.label-schema.build-date": "20190801","org.label-schema.license": "GPLv2","org.label-schema.name": "CentOS Base Image","org.label-schema.schema-version": "1.0","org.label-schema.vendor": "CentOS"}},"NetworkSettings": {"Bridge": "","SandboxID": "d5f116b329f01e9bab7f985282fd568e379c8e7aa4fcc3677b9b025ded771149","HairpinMode": false,"LinkLocalIPv6Address": "","LinkLocalIPv6PrefixLen": 0,"Ports": {},"SandboxKey": "/var/run/docker/netns/d5f116b329f0","SecondaryIPAddresses": null,"SecondaryIPv6Addresses": null,"EndpointID": "825091555bc0adfdf32667650884ec2b6274c44c787291870de32ec2cee8575b","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": "fe000671b1b7f9a2e634f409bd33ada7bed50e818a28c1d9c8245aba67b1b625","EndpointID": "825091555bc0adfdf32667650884ec2b6274c44c787291870de32ec2cee8575b","Gateway": "172.17.0.1","IPAddress": "172.17.0.2","IPPrefixLen": 16,"IPv6Gateway": "","GlobalIPv6Address": "","GlobalIPv6PrefixLen": 0,"MacAddress": "02:42:ac:11:00:02"}}}}][root@topcheer ~]#