curl -sSL https://get.daocloud.io/docker | sh # 使用docker version查看是否安装成功 grx@ubuntu:~$ docker version Client: Docker Engine - Community Version: 20.10.2 API version: 1.41 Go version: go1.13.15 Git commit: 2291f61 Built: Mon Dec 28 16:17:29 2020 OS/Arch: linux/amd64 Context: default Experimental: true
Server: Docker Engine - Community Engine: Version: 20.10.2 API version: 1.41 (minimum version 1.12) Go version: go1.13.15 Git commit: 8891c58 Built: Mon Dec 28 16:15:23 2020 OS/Arch: linux/amd64 Experimental: false containerd: Version: 1.4.3 GitCommit: 269548fa27e0089a8b8278fc4fc781d7f65a939b runc: Version: 1.0.0-rc92 GitCommit: ff819c7e9184c13b7c2607fe6c30ae19403a7aff docker-init: Version: 0.19.0 GitCommit: de40ad0
# hello world grx@ubuntu:~$ sudo docker run hello-world Unable to find image 'hello-world:latest' locally latest: Pulling from library/hello-world 0e03bdcc26d7: Pull complete Digest: sha256:1a523af650137b8accdaed439c17d684df61ee4d74feac151b5b337bd29e7eec Status: Downloaded newer image for hello-world:latest
Hello from Docker! This message shows that your installation appears to be working correctly.
To generate this message, Docker took the following steps: 1. The Docker client contacted the Docker daemon. 2. The Docker daemon pulled the "hello-world" image from the Docker Hub. (amd64) 3. The Docker daemon created a new container from that image which runs the executable that produces the output you are currently reading. 4. The Docker daemon streamed that output to the Docker client, which sent it to your terminal.
To try something more ambitious, you can run an Ubuntu container with: $ docker run -it ubuntu bash
Share images, automate workflows, and more with a free Docker ID: https://hub.docker.com/
For more examples and ideas, visit: https://docs.docker.com/get-started/
# 查看下载的hello-world镜像 grx@ubuntu:~$ docker images REPOSITORY TAG IMAGE ID CREATED SIZE hello-world latest bf756fb1ae65 12 months ago 13.3kB
docker version # 显示docker的版本信息 docker info # 显示docker的系统信息,包括镜像和容器的数量 docker --help # 帮助命令
2. 镜像命令
docker images 查看所有本地的镜像
1 2 3 4 5 6 7 8 9 10 11 12 13 14
grx@ubuntu:~$ docker images REPOSITORY TAG IMAGE ID CREATED SIZE hello-world latest bf756fb1ae65 12 months ago 13.3kB
# 解释 REPOSITORY 镜像的仓库源 TAG 镜像的标签 IMAGE ID 镜像的id CREATED 镜像的创建时间 SIZE 镜像的大小
# 可选项 -a, --all # 列出所有镜像 -q, --quiet # 只显示镜像的id
docker search 搜索镜像
1 2 3 4 5 6 7
grx@ubuntu:~$ docker search mysql --filter=STARS=3000 NAME DESCRIPTION STARS OFFICIAL AUTOMATED mysql MySQL is a widely used, open-source relation… 10380 [OK] mariadb MariaDB is a community-developed fork of MyS… 3848 [OK]
# 测试,启动并进入容器 grx@ubuntu:~$ docker run -it centos /bin/bash [root@404f3411db81 /]# ls # 查看容器内的centos,基础版本,很多命令都是不完善的! bin dev etc home lib lib64 lost+found media mnt opt proc root run sbin srv sys tmp usr var # 从容器中退回主机 [root@404f3411db81 /]# exit exit grx@ubuntu:~$
grx@ubuntu:~$ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES grx@ubuntu:~$ docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 404f3411db81 centos "/bin/bash" 4 minutes ago Exited (0) 2 minutes ago youthful_germain 6b5a4d54c5a2 hello-world "/hello" 3 days ago Exited (0) 3 days ago compassionate_sanderson
grx@ubuntu:~$ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 72fb134a68ba centos "/bin/sh -c 'while t…" 5 seconds ago Up 4 seconds infallible_leavitt
attach Attach local standard input, output, and error streams to a running container # 当前shell下attach连接指定运行镜像 build Build an image from a Dockerfile # 通过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 # 创建一个新的容器,同run,但不启动容器 diff Inspect changes to files or directories on a container's filesystem # 查看docker容器变化 events Get real time events from the server # 从docker服务获取容器实时事件 exec Run a command in a running container # 在已存在的容器上运行命令 export Export a container's filesystem as a tar archive # 导出容器的内容作为一个tar归档文件[对应import] history Show the history of an image # 显示一个镜像形成历史 images List images # 列出系统当前镜像 import Import the contents from a tarball to create a filesystem image # 从tar包中的内容创建一个新的文件系统映像[对应export] info Display system-wide information # 显示系统相关信息 inspect Return low-level information on Docker objects # 查看容器详细信息 kill Kill one or more running containers # kill指定docker容器 load Load an image from a tar archive or STDIN # 从一个tar包中加载一个镜像[对应save] login Log in to a Docker registry # 注册或者登录一个docker源服务器 logout Log out from a Docker registry # 从当前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 # 从docker镜像源服务器拉取指定镜像或者库镜像 push Push an image or a repository to a registry # 推送指定镜像或库镜像至docker源服务器 rename Rename a container # 重命名容器 restart Restart one or more containers # 重启运行的容器 rm Remove one or more containers # 移除一个或者多个容器 rmi Remove one or more images # 移除一个或者多个镜像【无容器使用该镜像才可删除,否则需要删除相关容器才可继续或者-f强制删除】 run Run a command in a new container # 创建一个新的容器并运行一个命令 save Save one or more images to a tar archive (streamed to STDOUT by default) # 保存一个镜像为一个tar包【对应load】 search Search the Docker Hub for images # 在docker hub中搜索镜像 start Start one or more stopped containers # 启动容器 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 # 查看docker版本号 wait Block until one or more containers stop, then print their exit codes # 截取容器停止时的退出状态值
UnionFS(联合文件系统):Union文件系统(UnionFS)是一种分层、轻量级并且高性能的文件系统,它支持对文件系统的修改作为一次提交来一层层的叠加,同时可以将不同目录挂载到一个虚拟文件系统下(unite several directories into a single virtual file system)。Union文件系统是Docker镜像的基础,镜像可以通过分层来进行继承,基于基础镜像(没有父镜像),可以制作各种具体的应用镜像。
[root@0d071b81ab34 /]# cd volume01/ [root@0d071b81ab34 volume01]# touch container.txt [root@0d071b81ab34 volume01]# ls container.txt
进入目录查看文件是否生成成功
1 2 3
root@ubuntu:/var/lib/docker# cd /var/lib/docker/volumes/1fb27c72ab89873d52f3f0c7cdb935c97fc77c539891b8fd820f5651530f5936/_data root@ubuntu:/var/lib/docker/volumes/1fb27c72ab89873d52f3f0c7cdb935c97fc77c539891b8fd820f5651530f5936/_data# ls container.txt
这种方式我们未来使用的十分多,因为我们通常会构建自己的镜像!
假设构建镜像的时候没有挂载卷,要手动镜像挂载 -v 卷名:容器内路径!
6. 数据卷容器
多个容器共享数据?
1 2
# 通过我们自己构建的镜像,启动3个,进行测试。 grx@ubuntu:~$ docker run -it --name docker01 grx/centos
# 在docker01容器进入volume01文件夹,创建docker01.txt文件,再去docker02容器查看是否同步成功 grx@ubuntu:~$ docker attach docker01 [root@6f3103cdfacb /]# ls bin etc lib lost+found mnt proc run srv tmp var volume02 dev home lib64 media opt root sbin sys usr volume01 [root@6f3103cdfacb /]# cd volume01/ [root@6f3103cdfacb volume01]# touch docker01.txt [root@6f3103cdfacb volume01]# ls docker01.txt # 在docker02容器中发现docker01.txt同步成功! [root@19e8fc7975fe /]# ls volume01/ docker01.txt # 再新建一个docker03容器 grx@ubuntu:~$ docker run -it --name docker03 --volumes-from docker01 grx/centos [root@545bede4aeb1 /]# ls bin etc lib lost+found mnt proc run srv tmp var volume02 dev home lib64 media opt root sbin sys usr volume01 [root@545bede4aeb1 /]# cd volume01/ [root@545bede4aeb1 volume01]# ls docker01.txt
# run运行,发现我们的ls -a生效 grx@ubuntu:~/docker-study$ docker run cmdtest . .. .dockerenv bin dev etc home lib lib64 lost+found media mnt opt proc root run sbin srv sys tmp usr var
# 想追加一个命令 -l,ls -al grx@ubuntu:~/docker-study$ docker run cmdtest -l docker: Error response from daemon: OCI runtime create failed: container_linux.go:370: starting container process caused: exec: "-l": executable file not found in $PATH: unknown. # CMD的情况下,-l替换了CMD["ls", "-a"]命令,所以报错
Log in to a Docker registry. If no server is specified, the default is defined by the daemon.
Options: -p, --password string Password --password-stdin Take the password from stdin -u, --username string Username
grx@ubuntu:~/docker-study$ docker login -u guorongxun Password: WARNING! Your password will be stored unencrypted in /home/grx/.docker/config.json. Configure a credential helper to remove this warning. See https://docs.docker.com/engine/reference/commandline/login/#credentials-store
grx@ubuntu:~/docker-study$ docker network ls NETWORK ID NAME DRIVER SCOPE c08d1685aeba bridge bridge local 9d2b1da969f4 host host local 82a620858c5e none null local
Options: --alias strings Add network-scoped alias for the container --driver-opt strings driver options for the network --ip string IPv4 address (e.g., 172.30.100.104) --ip6 string IPv6 address (e.g., 2001:db8::33) --link list Add link to another container --link-local-ip strings Add a link-local address for the container
grx@ubuntu:~/docker-study/idea$ docker run -d -P --name demo01 docker-idea:1.0 grx@ubuntu:~/docker-study/idea$ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES dc06296da58a docker-idea:1.0 "java -jar /app.jar …" 16 seconds ago Up 14 seconds 0.0.0.0:49158->8080/tcp demo01 grx@ubuntu:~/docker-study/idea$ curl localhost:49158/hello Hello,grx!
九、Docker Compose
1. 简介
官方介绍:
Compose is a tool for defining and running multi-container Docker applications. With Compose, you use a YAML file to configure your application’s services. Then, with a single command, you create and start all the services from your configuration. To learn more about all the features of Compose, see the list of features. Compose works in all environments: production, staging, development, testing, as well as CI workflows. You can learn more about each case in Common Use Cases. Using Compose is basically a three-step process:
Define your app’s environment with a Dockerfile so it can be reproduced anywhere.
Define the services that make up your app in docker-compose.yml so they can be run together in an isolated environment.
Run docker-compose up and Compose starts and runs your entire app.
grx@ubuntu:~/docker-study/composetest$ docker-compose up Recreating composetest_web_1 ... done Starting composetest_redis_1 ... done Attaching to composetest_redis_1, composetest_web_1 redis_1 | 1:C 01 Feb 2021 12:40:30.288 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo redis_1 | 1:C 01 Feb 2021 12:40:30.290 # Redis version=6.0.10, bits=64, commit=00000000, modified=0, pid=1, just started redis_1 | 1:C 01 Feb 2021 12:40:30.290 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf redis_1 | 1:M 01 Feb 2021 12:40:30.291 * Running mode=standalone, port=6379. redis_1 | 1:M 01 Feb 2021 12:40:30.291 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128. redis_1 | 1:M 01 Feb 2021 12:40:30.291 # Server initialized redis_1 | 1:M 01 Feb 2021 12:40:30.291 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect. redis_1 | 1:M 01 Feb 2021 12:40:30.291 * Loading RDB produced by version 6.0.10 redis_1 | 1:M 01 Feb 2021 12:40:30.291 * RDB age 12 seconds redis_1 | 1:M 01 Feb 2021 12:40:30.291 * RDB memory usage when created 0.77 Mb redis_1 | 1:M 01 Feb 2021 12:40:30.291 * DB loaded from disk: 0.000 seconds redis_1 | 1:M 01 Feb 2021 12:40:30.292 * Ready to accept connections web_1 | * Serving Flask app "app.py" web_1 | * Environment: production web_1 | WARNING: This is a development server. Do not use it in a production deployment. web_1 | Use a production WSGI server instead. web_1 | * Debug mode: off web_1 | * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
测试:
1 2 3 4 5 6 7 8 9 10 11
grx@ubuntu:~/docker-study/composetest$ curl localhost:5000 Hello World! I have been seen 1 times. grx@ubuntu:~/docker-study/composetest$ curl localhost:5000 Hello World! I have been seen 2 times. grx@ubuntu:~/docker-study/composetest$ curl localhost:5000 Hello World! I have been seen 3 times.
grx@ubuntu:~/docker-study/composetest$ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 5b8514df95f9 composetest_web "flask run" About a minute ago Up About a minute 0.0.0.0:5000->5000/tcp composetest_web_1 b37f7d6a39b2 redis:alpine "docker-entrypoint.s…" 3 minutes ago Up About a minute 6379/tcp composetest_redis_1
grx@ubuntu:~/docker-study/demo-app$ ll total 25788 drwxrwxr-x 2 grx grx 4096 Feb 1 21:31 ./ drwxrwxr-x 8 grx grx 4096 Feb 1 21:30 ../ -rw-rw-r-- 1 grx grx 174 Feb 1 21:31 docker-compose.yml -rw-rw-r-- 1 grx grx 26387267 Feb 1 21:31 docker-demo-0.0.1-SNAPSHOT.jar -rw-rw-r-- 1 grx grx 114 Feb 1 21:31 Dockerfile
构建项目:
1
grx@ubuntu:~/docker-study/demo-app$ docker-compose up -d
十、Docker Swarm
准备环境
四台linux服务器,安装Docker。
工作模式
1. 搭建集群
初始化节点:
1 2 3 4 5 6 7 8 9
# ubuntu-01 grx@ubuntu:~$ docker swarm init --advertise-addr 192.168.10.101 Swarm initialized: current node (g45sjzfi6j96xtjz9kyq9fto5) is now a manager.
To add a worker to this swarm, run the following command:
# ubuntu-02 grx@ubuntu:~$ docker swarm join --token SWMTKN-1-4gfig6ws393mvp1aia396is2e2hgeoo82jlor4n1gcphhr7d8m-cocg3dc29sdvu1nmory9oogvh 192.168.10.101:2377 This node joined a swarm as a worker.
查看集群内所有节点,该命令必须在manager上执行:
1 2 3 4 5
# ubuntu-01 grx@ubuntu:~$ docker node ls ID HOSTNAME STATUS AVAILABILITY MANAGER STATUS ENGINE VERSION g45sjzfi6j96xtjz9kyq9fto5 * ubuntu Ready Active Leader 20.10.2 tfj7m5uy8p8zbjhqhqqe06i9x ubuntu Ready Active 20.10.3
把所有节点都加入集群:
1 2 3 4 5 6
grx@ubuntu:~$ docker node ls ID HOSTNAME STATUS AVAILABILITY MANAGER STATUS ENGINE VERSION 3pn00dhd23cttjiqia2fthb2a ubuntu Ready Active 20.10.3 g45sjzfi6j96xtjz9kyq9fto5 ubuntu Ready Active Leader 20.10.2 h4d7f61anu3hgckypkyzj3hw5 * ubuntu Ready Active Reachable 20.10.3 tfj7m5uy8p8zbjhqhqqe06i9x ubuntu Ready Active 20.10.3
2. 理解Raft协议
保证集群主节点个数不少于3个,这样当其中一个主节点fail的时候,大多数节点可用,不影响正常运行。
实验一(2个manager):
将ubuntu-01的docker停止,发现另外一个主节点ubuntu-04也不能使用
1 2 3 4 5 6
# ubuntu-01 grx@ubuntu:~$ systemctl stop docker
# ubuntu-04 grx@ubuntu:~$ docker node ls Error response from daemon: rpc error: code = Unknown desc = The swarm does not have a leader. It's possible that too few managers are online. Make sure more than half of the managers are online.
实验二(3个manager):
将ubuntu-03以manager的身份加入
1 2 3 4 5 6 7 8
# ubuntu-03 grx@ubuntu:~$ docker node ls ID HOSTNAME STATUS AVAILABILITY MANAGER STATUS ENGINE VERSION 3pn00dhd23cttjiqia2fthb2a ubuntu Down Active 20.10.3 aec10kndzwetb35rhjlf7rj94 * ubuntu Ready Active Reachable 20.10.3 g45sjzfi6j96xtjz9kyq9fto5 ubuntu Ready Active Reachable 20.10.2 h4d7f61anu3hgckypkyzj3hw5 ubuntu Ready Active Leader 20.10.3 tfj7m5uy8p8zbjhqhqqe06i9x ubuntu Ready Active 20.10.3
此时将ubuntu-01的docker停止,另一个主节点ubuntu-04仍然可用:
1 2 3 4 5 6 7 8 9 10 11
# ubuntu-01 grx@ubuntu:~$ systemctl stop docker
# ubuntu-04 grx@ubuntu:~$ docker node ls ID HOSTNAME STATUS AVAILABILITY MANAGER STATUS ENGINE VERSION 3pn00dhd23cttjiqia2fthb2a ubuntu Down Active 20.10.3 aec10kndzwetb35rhjlf7rj94 ubuntu Ready Active Reachable 20.10.3 g45sjzfi6j96xtjz9kyq9fto5 ubuntu Down Active Unreachable 20.10.2 h4d7f61anu3hgckypkyzj3hw5 * ubuntu Ready Active Leader 20.10.3 tfj7m5uy8p8zbjhqhqqe06i9x ubuntu Ready Active 20.10.3
再将ubuntu-03的docker停止,发现ubuntu-04不可用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# ubuntu-03 grx@ubuntu:~$ systemctl stop docker
# ubuntu-04 grx@ubuntu:~$ docker node ls ID HOSTNAME STATUS AVAILABILITY MANAGER STATUS ENGINE VERSION 3pn00dhd23cttjiqia2fthb2a ubuntu Down Active 20.10.3 aec10kndzwetb35rhjlf7rj94 ubuntu Ready Active Unreachable 20.10.3 g45sjzfi6j96xtjz9kyq9fto5 ubuntu Down Active Unreachable 20.10.2 h4d7f61anu3hgckypkyzj3hw5 * ubuntu Ready Active Leader 20.10.3 tfj7m5uy8p8zbjhqhqqe06i9x ubuntu Ready Active 20.10.3 # 一段时间后... grx@ubuntu:~$ docker node ls Error response from daemon: rpc error: code = Unknown desc = The swarm does not have a leader. It's possible that too few managers are online. Make sure more than half of the managers are online.
3. Swarm集群弹性创建服务
集群式:docker service
1 2 3 4 5 6 7 8 9 10 11 12 13 14
grx@ubuntu:~$ docker service --help
Commands: create Create a new service inspect Display detailed information on one or more services logs Fetch the logs of a service or task ls List services ps List the tasks of one or more services rm Remove one or more services rollback Revert changes to a service's configuration scale Scale one or multiple replicated services update Update a service
Run 'docker service COMMAND --help' for more information on a command.
在manager节点上启动服务:
1 2 3 4 5 6
# ubuntu-01 grx@ubuntu:~$ docker service create -p 8888:80 --name my-nginx nginx ysgvv51zczqwj53z61h6l33ct overall progress: 1 out of 1 tasks 1/1: running [==================================================>] verify: Service converged
查看启动的服务:
1 2 3 4 5
# ubuntu-01 # 目前只有1个副本 grx@ubuntu:~$ docker service ls ID NAME MODE REPLICAS IMAGE PORTS ysgvv51zczqw my-nginx replicated 1/1 nginx:latest *:8888->80/tcp
创建3个副本:
1 2 3 4 5 6 7 8 9 10 11
# ubuntu-01 grx@ubuntu:~$ docker service update --replicas 3 my-nginx my-nginx overall progress: 3 out of 3 tasks 1/3: running [==================================================>] 2/3: running [==================================================>] 3/3: running [==================================================>] verify: Service converged
# 或者使用scale命令 # grx@ubuntu:~$ docker service scale my-nginx=3