Docker笔记-Docker Compose
Compose 是用于定义和运行多容器 Docker 应用程序的工具,通过 Compose 您可以使用 YML 文件来配置应用
程序需要的所有服务。然后,使用一个命令,就可以从 YML 文件配置中创建并启动所有服务。
Compose 使用的三个步骤:
- 使用
Dockerfile
定义应用程序的环境。 - 使用
docker-compose.yml
定义构成应用程序的服务,这样它们可以在隔离环境中一起运行。 - 最后,执行
docker-compose up
命令来启动并运行整个应用程序。
docker-compose.yml
的配置案例如下(配置参数参考下文):
# yaml配置实例
version: '3'
services:
web:
build: .
ports:
- "5000:5000"
volumes:
- .:/code
- logvolume01:/var/log
links:
- redis
redis:
image: redis
volumes:
logvolume01: {}
1、Compose 安装
Linux 上我们可以从 Github 上下载它的二进制包来使用,最新发行的版本地址:
https://github.com/docker/compose/releases
运行以下命令以下载 Docker Compose 的当前稳定版本:
# https://github.com/docker/compose/releases/download/1.24.1/docker-compose-Linux-x86_64
$ sudo curl -L "https://github.com/docker/compose/releases/download/1.24.1/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
[root@zsx ~]# sudo curl -L "https://github.com/docker/compose/releases/download/1.24.1/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 633 100 633 0 0 980 0 --:--:-- --:--:-- --:--:-- 979
100 15.4M 100 15.4M 0 0 2042k 0 0:00:07 0:00:07 --:--:-- 2573k
要安装其他版本的 Compose,请替换 1.24.1
。
将可执行权限应用于二进制文件:
$ sudo chmod +x /usr/local/bin/docker-compose
创建软链:
$ sudo ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose
测试是否安装成功:
$ docker-compose --version
docker-compose version 1.24.1, build 4667896b
注意: 对于 alpine,需要以下依赖包: py-pip,python-dev,libffi-dev,openssl-dev,gcc,libc-dev 和
make。
安装方式二:
# 安装pip
$ yum -y install epel-release
$ yum -y install python-pip
# 确认版本
$ pip --version
# 更新pip
$ pip install --upgrade pip
# 安装docker-compose
$ pip install docker-compose
# 查看版本
$ docker-compose version
安装补全工具:
# 安装
$ yum install bash-completion
# 下载docker-compose脚本
$ curl -L https://raw.githubusercontent.com/docker/compose/$(docker-compose version --short)/contrib/completion/bash/docker-compose > /etc/bash_completion.d/docker-compose
2、使用
2.1 准备
创建一个测试目录:
$ mkdir composetest
$ cd composetest
在测试目录中创建一个名为 app.py 的文件,并复制粘贴以下内容:
composetest/app.py
文件代码:
import time
import redis
from flask import Flask
app = Flask(__name__)
cache = redis.Redis(host='redis', port=6379)
def get_hit_count():
retries = 5
while True:
try:
return cache.incr('hits')
except redis.exceptions.ConnectionError as exc:
if retries == 0:
raise exc
retries -= 1
time.sleep(0.5)
@app.route('/')
def hello():
count = get_hit_count()
return 'Hello World! I have been seen {} times.\n'.format(count)
在此示例中,redis 是应用程序网络上的 redis 容器的主机名,该主机使用的端口为 6379。
在 composetest 目录中创建另一个名为 requirements.txt
的文件,内容如下:
flask
redis
2.2 创建Dockerfile文件
在 composetest 目录中,创建一个名为的文件 Dockerfile
,内容如下:
FROM python:3.7-alpine
WORKDIR /code
ENV FLASK_APP app.py
ENV FLASK_RUN_HOST 0.0.0.0
RUN apk add --no-cache gcc musl-dev linux-headers
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
COPY . .
CMD ["flask", "run"]
Dockerfile 内容解释:
FROM python:3.7-alpine
:从 Python 3.7 映像开始构建镜像。WORKDIR /code
:将工作目录设置为 /code。ENV FLASK_APP app.py && ENV FLASK_RUN_HOST 0.0.0.0
:设置 flask 命令使用的环境变量。RUN apk add --no-cache gcc musl-dev linux-headers
:安装 gcc,以便诸如 MarkupSafe 和SQLAlchemy 之类的 Python 包可以编译加速。
COPY requirements.txt requirements.txt && RUN pip install -r requirements.txt
:复制 requirements.txt 并安装 Python 依赖项。
COPY . .
:将 . 项目中的当前目录复制到 . 镜像中的工作目录。CMD ["flask", "run"]
:容器提供默认的执行命令为:flask run。
2.3 创建 docker-compose.yml
在测试目录中创建一个名为 docker-compose.yml 的文件,然后粘贴以下内容:
docker-compose.yml
配置文件:
# yaml配置
version: '3'
services:
web:
build: .
ports:
- "5000:5000"
redis:
image: "redis:alpine"
该 Compose 文件定义了两个服务:web 和 redis。
web
:该 web 服务使用从 Dockerfile 当前目录中构建的镜像。然后,它将容器和主机绑定到暴露的端口5000。此示例服务使用 Flask Web 服务器的默认端口 5000 。
redis
:该 redis 服务使用 Docker Hub 的公共 Redis 映像。
2.4 使用Compose命令构建和运行您的应用
在测试目录中,执行以下命令来启动应用程序:
$ docker-compose up
如果你想在后台执行该服务可以加上 -d
参数:
$ docker-compose up -d
[root@zsx composetest]# docker-compose up
Building web
Step 1/9 : FROM python:3.7-alpine
---> f0c1a69798c7
Step 2/9 : WORKDIR /code
---> Using cache
---> 70b58a88c05f
Step 3/9 : ENV FLASK_APP app.py
---> Using cache
---> 21621b425f6d
Step 4/9 : ENV FLASK_RUN_HOST 0.0.0.0
---> Using cache
---> 9d02c3c996ee
Step 5/9 : RUN apk add --no-cache gcc musl-dev linux-headers
---> Running in ee5cc90a40a3
fetch https://dl-cdn.alpinelinux.org/alpine/v3.14/main/x86_64/APKINDEX.tar.gz
fetch https://dl-cdn.alpinelinux.org/alpine/v3.14/community/x86_64/APKINDEX.tar.gz
(1/13) Installing libgcc (10.3.1_git20210424-r2)
(2/13) Installing libstdc++ (10.3.1_git20210424-r2)
(3/13) Installing binutils (2.35.2-r2)
(4/13) Installing libgomp (10.3.1_git20210424-r2)
(5/13) Installing libatomic (10.3.1_git20210424-r2)
(6/13) Installing libgphobos (10.3.1_git20210424-r2)
(7/13) Installing gmp (6.2.1-r0)
(8/13) Installing isl22 (0.22-r0)
(9/13) Installing mpfr4 (4.1.0-r0)
(10/13) Installing mpc1 (1.2.1-r0)
(11/13) Installing gcc (10.3.1_git20210424-r2)
(12/13) Installing linux-headers (5.10.41-r0)
(13/13) Installing musl-dev (1.2.2-r3)
Executing busybox-1.33.1-r6.trigger
OK: 140 MiB in 48 packages
Removing intermediate container ee5cc90a40a3
---> bc278a142ea4
Step 6/9 : COPY requirements.txt requirements.txt
---> 5cf43856a885
Step 7/9 : RUN pip install -r requirements.txt
---> Running in c450bb22ca48
Collecting flask
Downloading Flask-2.0.2-py3-none-any.whl (95 kB)
Collecting redis
Downloading redis-4.0.1-py3-none-any.whl (118 kB)
Collecting Werkzeug>=2.0
Downloading Werkzeug-2.0.2-py3-none-any.whl (288 kB)
Collecting click>=7.1.2
Downloading click-8.0.3-py3-none-any.whl (97 kB)
Collecting Jinja2>=3.0
Downloading Jinja2-3.0.3-py3-none-any.whl (133 kB)
Collecting itsdangerous>=2.0
Downloading itsdangerous-2.0.1-py3-none-any.whl (18 kB)
Collecting deprecated
Downloading Deprecated-1.2.13-py2.py3-none-any.whl (9.6 kB)
Collecting importlib-metadata
Downloading importlib_metadata-4.8.2-py3-none-any.whl (17 kB)
Collecting MarkupSafe>=2.0
Downloading MarkupSafe-2.0.1-cp37-cp37m-musllinux_1_1_x86_64.whl (30 kB)
Collecting wrapt<2,>=1.10
Downloading wrapt-1.13.3-cp37-cp37m-musllinux_1_1_x86_64.whl (78 kB)
Collecting zipp>=0.5
Downloading zipp-3.6.0-py3-none-any.whl (5.3 kB)
Collecting typing-extensions>=3.6.4
Downloading typing_extensions-4.0.0-py3-none-any.whl (22 kB)
Installing collected packages: zipp, typing-extensions, wrapt, MarkupSafe, importlib-metadata, Werkzeug, Jinja2, itsdangerous, deprecated, click, redis, flask
Successfully installed Jinja2-3.0.3 MarkupSafe-2.0.1 Werkzeug-2.0.2 click-8.0.3 deprecated-1.2.13 flask-2.0.2 importlib-metadata-4.8.2 itsdangerous-2.0.1 redis-4.0.1 typing-extensions-4.0.0 wrapt-1.13.3 zipp-3.6.0
WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv
WARNING: You are using pip version 21.2.4; however, version 21.3.1 is available.
You should consider upgrading via the '/usr/local/bin/python -m pip install --upgrade pip' command.
Removing intermediate container c450bb22ca48
---> b404ea962607
Step 8/9 : COPY . .
---> b3ebb62f5047
Step 9/9 : CMD ["flask", "run"]
---> Running in d59641e0eb5d
Removing intermediate container d59641e0eb5d
---> 543598e9ff15
Successfully built 543598e9ff15
Successfully tagged composetest_web:latest
WARNING: Image for service web was built because it did not already exist. To rebuild this image you must use `docker-compose build` or `docker-compose up --build`.
Pulling redis (redis:alpine)...
alpine: Pulling from library/redis
97518928ae5f: Already exists
66f8c4150d27: Pull complete
09a8bf17a0bf: Pull complete
e547313af8e7: Pull complete
335eeadfbde0: Pull complete
7151fc2c01eb: Pull complete
Digest: sha256:50fc99c529b81432a592fa76354783d7fc3ba479a92fc810cbf669138c4138b7
Status: Downloaded newer image for redis:alpine
Creating composetest_web_1 ... done
Creating composetest_redis_1 ... done
Attaching to composetest_redis_1, composetest_web_1
redis_1 | 1:C 17 Nov 2021 12:47:55.857 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
redis_1 | 1:C 17 Nov 2021 12:47:55.857 # Redis version=6.2.6, bits=64, commit=00000000, modified=0, pid=1, just started
redis_1 | 1:C 17 Nov 2021 12:47:55.857 # 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 17 Nov 2021 12:47:55.858 * monotonic clock: POSIX clock_gettime
redis_1 | 1:M 17 Nov 2021 12:47:55.858 * Running mode=standalone, port=6379.
redis_1 | 1:M 17 Nov 2021 12:47:55.859 # 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 17 Nov 2021 12:47:55.859 # Server initialized
redis_1 | 1:M 17 Nov 2021 12:47:55.859 # 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 17 Nov 2021 12:47:55.859 * Ready to accept connections
web_1 | * Serving Flask app 'app.py' (lazy loading)
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 | /usr/local/lib/python3.7/site-packages/redis/connection.py:72: UserWarning: redis-py works best with hiredis. Please consider installing
web_1 | warnings.warn(msg)
web_1 | * Running on all addresses.
web_1 | WARNING: This is a development server. Do not use it in a production deployment.
web_1 | * Running on http://172.19.0.3:5000/ (Press CTRL+C to quit)
web_1 | 172.19.0.1 - - [17/Nov/2021 12:48:48] "GET / HTTP/1.1" 200 -
web_1 | 172.19.0.1 - - [17/Nov/2021 12:48:48] "GET /favicon.ico HTTP/1.1" 404 -
web_1 | 192.168.157.185 - - [17/Nov/2021 12:49:11] "GET / HTTP/1.1" 200 -
web_1 | 192.168.157.185 - - [17/Nov/2021 12:49:11] "GET /favicon.ico HTTP/1.1" 404 -
web_1 | 192.168.157.185 - - [17/Nov/2021 12:49:14] "GET / HTTP/1.1" 200 -
web_1 | 192.168.157.185 - - [17/Nov/2021 12:49:15] "GET / HTTP/1.1" 200 -
3、yml 配置指令参考
3.1 version
指定本 yml 依从的 compose 哪个版本制定的。
3.2 build
指定为构建镜像上下文路径:
例如 webapp 服务,指定为从上下文路径 ./dir/Dockerfile
所构建的镜像:
version: "3.7"
services:
webapp:
build: ./dir
或者,作为具有在上下文指定的路径的对象,以及可选的 Dockerfile 和 args:
version: "3.7"
services:
webapp:
build:
context: ./dir
dockerfile: Dockerfile-alternate
args:
buildno: 1
labels:
- "com.example.description=Accounting webapp"
- "com.example.department=Finance"
- "com.example.label-with-empty-value"
target: prod
- context:上下文路径。
- dockerfile:指定构建镜像的 Dockerfile 文件名。
- args:添加构建参数,这是只能在构建过程中访问的环境变量。
- labels:设置构建镜像的标签。
- target:多层构建,可以指定构建哪一层。
3.3 cap_add,cap_drop
添加或删除容器拥有的宿主机的内核功能。
cap_add:
- ALL # 开启全部权限
cap_drop:
- SYS_PTRACE # 关闭 ptrace权限
3.4 cgroup_parent
为容器指定父 cgroup 组,意味着将继承该组的资源限制。
cgroup_parent: m-executor-abcd
3.5 command
覆盖容器启动的默认命令。
command: ["bundle", "exec", "thin", "-p", "3000"]
3.6 container_name
指定自定义容器名称,而不是生成的默认名称。
container_name: my-web-container
3.7 depends_on
设置依赖关系。
docker-compose up
:以依赖性顺序启动服务。在以下示例中,先启动 db 和 redis ,才会启动 web。docker-compose up SERVICE
:自动包含 SERVICE 的依赖项。在以下示例中,docker-compose up web还将创建并启动 db 和 redis。
docker-compose stop
:按依赖关系顺序停止服务。在以下示例中,web 在 db 和 redis 之前停止。
version: "3.7"
services:
web:
build: .
depends_on:
- db
- redis
redis:
image: redis
db:
image: postgres
注意:web 服务不会等待 redis db 完全启动 之后才启动。
3.8 deploy
指定与服务的部署和运行有关的配置,只在 swarm 模式下才会有用。
version: "3.7"
services:
redis:
image: redis:alpine
deploy:
mode: replicated
replicas: 6
endpoint_mode: dnsrr
labels:
description: "This redis service label"
resources:
limits:
cpus: '0.50'
memory: 50M
reservations:
cpus: '0.25'
memory: 20M
restart_policy:
condition: on-failure
delay: 5s
max_attempts: 3
window: 120s
可以选参数:
endpoint_mode:访问集群服务的方式。
# Docker集群服务一个对外的虚拟ip,所有的请求都会通过这个虚拟ip到达集群服务内部的机器
endpoint_mode: vip
# DNS轮询(DNSRR),所有的请求会自动轮询获取到集群ip列表中的一个ip地址
endpoint_mode: dnsrr
labels:在服务上设置标签。可以用容器上的 labels(跟 deploy 同级的配置) 覆盖 deploy 下的 labels。
mode:指定服务提供的模式。
replicated:复制服务,复制指定服务到集群的机器上。
global:全局服务,服务将部署至集群的每个节点。
图解:下图中黄色的方块是 replicated 模式的运行情况,灰色方块是 global 模式的运行情况。
replicas:mode 为 replicated 时,需要使用此参数配置具体运行的节点数量。
resources:配置服务器资源使用的限制,例如上例子,配置 redis 集群运行需要的 cpu 的百分比 和 内存的占
用。避免占用资源过高出现异常。
restart_policy:配置如何在退出容器时重新启动容器。
- condition:可选 none,on-failure 或者 any(默认值:any)。
- delay:设置多久之后重启(默认值:0)。
- max_attempts:尝试重新启动容器的次数,超出次数,则不再尝试(默认值:一直重试)。
- window:设置容器重启超时时间(默认值:0)。
rollback_config:配置在更新失败的情况下应如何回滚服务。
parallelism:一次要回滚的容器数。如果设置为0,则所有容器将同时回滚。
delay:每个容器组回滚之间等待的时间(默认为0s)。
failure_action:如果回滚失败,该怎么办。其中一个 continue 或者 pause(默认pause)。
monitor:每个容器更新后,持续观察是否失败了的时间 (ns|us|ms|s|m|h)(默认为0s)。
max_failure_ratio:在回滚期间可以容忍的故障率(默认为0)。
order:回滚期间的操作顺序。其中一个 stop-first(串行回滚),或者 start-first(并行回滚)(默认 stop-
first )。
update_config:配置应如何更新服务,对于配置滚动更新很有用。
parallelism:一次更新的容器数。
delay:在更新一组容器之间等待的时间。
failure_action:如果更新失败,该怎么办。其中一个 continue,rollback 或者pause (默认:pause)。
monitor:每个容器更新后,持续观察是否失败了的时间 (ns|us|ms|s|m|h)(默认为0s)。
max_failure_ratio:在更新过程中可以容忍的故障率。
order:回滚期间的操作顺序。其中一个 stop-first(串行回滚),或者 start-first(并行回滚)(默认stop-
first)。
注:仅支持 V3.4 及更高版本。
3.9 devices
指定设备映射列表。
devices:
- "/dev/ttyUSB0:/dev/ttyUSB0"
3.10 dns
自定义 DNS 服务器,可以是单个值或列表的多个值。
dns: 8.8.8.8
dns:
- 8.8.8.8
- 9.9.9.9
3.11 dns_search
自定义 DNS 搜索域,可以是单个值或列表。
dns_search: example.com
dns_search:
- dc1.example.com
- dc2.example.com
3.12 entrypoint
覆盖容器默认的 entrypoint。
entrypoint: /code/entrypoint.sh
也可以是以下格式:
entrypoint:
- php
- -d
- zend_extension=/usr/local/lib/php/extensions/no-debug-non-zts-20100525/xdebug.so
- -d
- memory_limit=-1
- vendor/bin/phpunit
3.13 env_file
从文件添加环境变量,可以是单个值或列表的多个值。
env_file: .env
也可以是列表格式:
env_file:
- ./common.env
- ./apps/web.env
- /opt/secrets.env
3.14 environment
添加环境变量。您可以使用数组或字典、任何布尔值,布尔值需要用引号引起来,以确保 YML 解析器不会将其转
换为 True 或 False。
environment:
RACK_ENV: development
SHOW: 'true'
3.15 expose
暴露端口,但不映射到宿主机,只被连接的服务访问。
仅可以指定内部端口为参数:
expose:
- "3000"
- "8000"
3.16 extra_hosts
添加主机名映射,类似 docker client --add-host。
extra_hosts:
- "somehost:162.242.195.82"
- "otherhost:50.31.209.229"
以上会在此服务的内部容器中 /etc/hosts 创建一个具有 ip 地址和主机名的映射关系:
162.242.195.82 somehost
50.31.209.229 otherhost
3.17 healthcheck
用于检测 docker 服务是否健康运行。
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost"] # 设置检测程序
interval: 1m30s # 设置检测间隔
timeout: 10s # 设置检测超时时间
retries: 3 # 设置重试次数
start_period: 40s # 启动后,多少秒开始启动检测程序
3.18 image
指定容器运行的镜像,以下格式都可以:
image: redis
image: ubuntu:14.04
image: tutum/influxdb
image: example-registry.com:4000/postgresql
image: a4bc65fd # 镜像id
3.19 logging
服务的日志记录配置。
driver:指定服务容器的日志记录驱动程序,默认值为json-file。有以下三个选项
driver: "json-file"
driver: "syslog"
driver: "none"
仅在 json-file 驱动程序下,可以使用以下参数,限制日志得数量和大小。
logging:
driver: json-file
options:
max-size: "200k" # 单个文件大小为200k
max-file: "10" # 最多10个文件
当达到文件限制上限,会自动删除旧得文件。
syslog 驱动程序下,可以使用 syslog-address 指定日志接收地址。
logging:
driver: syslog
options:
syslog-address: "tcp://192.168.0.42:123"
3.20 network_mode
设置网络模式。
network_mode: "bridge"
network_mode: "host"
network_mode: "none"
network_mode: "service:[service name]"
network_mode: "container:[container name/id]"
networks 配置容器连接的网络,引用顶级 networks 下的条目 。
services:
some-service:
networks:
some-network:
aliases:
- alias1
other-network:
aliases:
- alias2
networks:
some-network:
# Use a custom driver
driver: custom-driver-1
other-network:
# Use a custom driver which takes special options
driver: custom-driver-2
aliases:同一网络上的其他容器可以使用服务名称或此别名来连接到对应容器的服务。
3.21 restart
- no:是默认的重启策略,在任何情况下都不会重启容器。
- always:容器总是重新启动。
- on-failure:在容器非正常退出时(退出状态非0),才会重启容器。
- unless-stopped:在容器退出时总是重启容器,但是不考虑在Docker守护进程启动时就已经停止了的容器
restart: "no"
restart: always
restart: on-failure
restart: unless-stopped
注:swarm 集群模式,请改用 restart_policy。
3.22 secrets
存储敏感数据,例如密码:
version: "3.1"
services:
mysql:
image: mysql
environment:
MYSQL_ROOT_PASSWORD_FILE: /run/secrets/my_secret
secrets:
- my_secret
secrets:
my_secret:
file: ./my_secret.txt
3.23 security_opt
修改容器默认的 schema 标签。
security-opt:
- label:user:USER # 设置容器的用户标签
- label:role:ROLE # 设置容器的角色标签
- label:type:TYPE # 设置容器的安全策略标签
- label:level:LEVEL # 设置容器的安全等级标签
3.24 stop_grace_period
指定在容器无法处理 SIGTERM (或者任何 stop_signal 的信号),等待多久后发送 SIGKILL 信号关闭容器。
stop_grace_period: 1s # 等待 1 秒
stop_grace_period: 1m30s # 等待 1 分 30 秒
默认的等待时间是 10 秒。
3.25 stop_signal
设置停止容器的替代信号,默认情况下使用 SIGTERM。
以下示例,使用 SIGUSR1 替代信号 SIGTERM 来停止容器。
stop_signal: SIGUSR1
3.26 sysctls
设置容器中的内核参数,可以使用数组或字典格式。
sysctls:
net.core.somaxconn: 1024
net.ipv4.tcp_syncookies: 0
sysctls:
- net.core.somaxconn=1024
- net.ipv4.tcp_syncookies=0
3.27 tmpfs
在容器内安装一个临时文件系统,可以是单个值或列表的多个值。
tmpfs: /run
tmpfs:
- /run
- /tmp
3.28 ulimits
覆盖容器默认的 ulimit。
ulimits:
nproc: 65535
nofile:
soft: 20000
hard: 40000
3.29 volumes
将主机的数据卷或着文件挂载到容器里。
version: "3.7"
services:
db:
image: postgres:latest
volumes:
- "/localhost/postgres.sock:/var/run/postgres/postgres.sock"
- "/localhost/data:/var/lib/postgresql/data"
4、Docker Compose例子
# 案例地址
https://docs.docker.com/compose/gettingstarted/
4.1 Step1 新建文件夹
$ mkdir composetest
$ cd composetest
4.2 Step2 新建app.py文件
import time
import redis
from flask import Flask
app = Flask(__name__)
cache = redis.Redis(host='redis', port=6379)
def get_hit_count():
retries = 5
while True:
try:
return cache.incr('hits')
except redis.exceptions.ConnectionError as exc:
if retries == 0:
raise exc
retries -= 1
time.sleep(0.5)
@app.route('/')
def hello():
count = get_hit_count()
return 'Hello World! I have been seen {} times.\n'.format(count)
4.3 Step3 创建requirements.txt文件
flask
redis
4.4 Step4 创建Dockerfile文件
# syntax=docker/dockerfile:1
FROM python:3.7-alpine
WORKDIR /code
ENV FLASK_APP=app.py
ENV FLASK_RUN_HOST=0.0.0.0
RUN apk add --no-cache gcc musl-dev linux-headers
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
EXPOSE 5000
COPY . .
CMD ["flask", "run"]
4.5 Step5 创建docker-compose.yml文件
version: "3.9"
services:
web:
build: .
ports:
- "5000:5000"
redis:
image: "redis:alpine"
4.6 Step6 构建
$ docker-compose up
4.7 Step7 访问
$ docker image ls
[root@zsx zhangshixing]# docker image ls
REPOSITORY TAG IMAGE ID CREATED SIZE
composetest_web latest 543598e9ff15 16 minutes ago 183MB
diytomcat latest 3ca521cc579e 9 hours ago 651MB
nginx latest e9ce56a96f8e 19 hours ago 141MB
tomcat latest 5db6fed793e9 40 hours ago 680MB
ubuntu v2 8ea6534ccd35 2 days ago 137MB
redis alpine 5c08f13a2b92 4 days ago 32.4MB
python 3.7-alpine f0c1a69798c7 4 days ago 41.9MB
tomcat <none> b0e0b0a92cf9 3 weeks ago 680MB
hello-world latest feb5d9fea6a5 7 weeks ago 13.3kB
centos latest 5d0da3dc9764 2 months ago 231MB
portainer/portainer latest 580c0e4e98b0 8 months ago 79.1MB
centos 6.7 9f1de3c6ad53 2 years ago 191MB
ubuntu 15.10 9b9cb95443b5 5 years ago 137MB
training/webapp latest 6fae60ef3446 6 years ago 349MB
$ docker service ls
[root@zsx zhangshixing]# docker service ls
Error response from daemon: This node is not a swarm manager. Use "docker swarm init" or "docker swarm join" to connect this node to swarm and try again.
$ docker network ls
[root@zsx zhangshixing]# docker network ls
NETWORK ID NAME DRIVER SCOPE
22a861c9adb3 bridge bridge local
3ec11aa11df0 composetest_default bridge local
87f220cd32d2 host host local
d61d5b0273fb none null local
9e3b5ce80e32 test-net bridge local
$ curl http://localhost:5000
Hello World! I have been seen 14 times.
4.8 Step8 其它的命令
[root@zsx ~]# docker-compose --help
Usage: docker compose [OPTIONS] COMMAND
Docker Compose
Options:
--ansi string Control when to print ANSI control characters ("never"|"always"|"auto") (default
"auto")
--compatibility Run compose in backward compatibility mode
--env-file string Specify an alternate environment file.
-f, --file stringArray Compose configuration files
--profile stringArray Specify a profile to enable
--project-directory string Specify an alternate working directory
(default: the path of the, first specified, Compose file)
-p, --project-name string Project name
Commands:
build Build or rebuild services
convert Converts the compose file to platform's canonical format
cp Copy files/folders between a service container and the local filesystem
create Creates containers for a service.
down Stop and remove containers, networks
events Receive real time events from containers.
exec Execute a command in a running container.
images List images used by the created containers
kill Force stop service containers.
logs View output from containers
ls List running compose projects
pause Pause services
port Print the public port for a port binding.
ps List containers
pull Pull service images
push Push service images
restart Restart service containers
rm Removes stopped service containers
run Run a one-off command on a service.
start Start services
stop Stop services
top Display the running processes
unpause Unpause services
up Create and start containers
version Show the Docker Compose version information
Run 'docker compose COMMAND --help' for more information on a command.
可以看到 docker-compose 的命令格式为:
$ docker compose [OPTIONS] COMMAND
具体的一些命令:
# 用于启动使用Docker Compose编排的多个容器
# 启动所有服务
$ docker-compose up
$ docker-compose up [OPTIONS] [SERVICE...]
# 在后台启动所有服务
$ docker-compose up -d
# 在后台所有启动服务,指定编排文件
$ docker-compose -f docker-compose.yml up -d
# 用于列出由Docker Compose管理的容器的状态
$ docker-compose ps
$ docker-compose ps [OPTIONS] [SERVICE...]
# 指定配置文件
$ docker-compose -f <file> ps
# 显示详细信息
$ docker-compose ps -a
# 停止正在运行的容器
$ docker-compose stop
$ docker-compose stop [OPTIONS] [SERVICE...]
# 用于停止和移除由docker-compose up创建的容器、网络和卷
$ docker-compose down
$ docker-compose down [OPTIONS]
# 除关联的卷
$ docker-compose down --volumes
# 用于查看由docker-compose启动的服务的日志
$ docker-compose logs
$ docker-compose logs [OPTIONS] [SERVICE...]
# 指定服务名称,默认情况下docker-compose logs会显示所有服务的日志,如果只想查看特定服务的日志,可以指定服务名称作为参数
$ docker-compose logs <service1> <service2>
。
# 构建(重新构建)项目中的服务容器
$ docker-compose build
$ docker-compose build [OPTIONS] [SERVICE...]
# 拉取服务依赖的镜像
$ docker-compose pull
$ docker-compose pull [OPTIONS] [SERVICE...]
# 用于重新启动由docker-compose启动的服务容器
$ docker-compose restart
$ docker-compose restart [OPTIONS] [SERVICE...]
# 删除所有(停止状态的)服务容器
$ docker-compose rm
$ docker-compose rm [OPTIONS] [SERVICE...]
# 用于启动由docker-compose管理的服务容器
$ docker-compose start
$ docker-compose start [SERVICE...]
# 在指定服务上执行一个命令
$ docker-compose run
$ docker-compose run [OPTIONS] SERVICE [COMMAND] [ARGS...]
$ docker-compose run <service> <command>
# 查看web服务可用的环境变量
$ docker-compose run web env
# 附加到终端,默认情况下,docker-compose run命令会启动一个新容器并在其中运行命令,然后退出,如果想要在容器中进行交互操作,可以使用-it选项将命令附加到终端
$ docker-compose run -it <service> <command>
# 用于扩展或缩小Docker Compose中的服务实例数量
$ docker-compose scale
$ docker-compose scale <service1>=<num1> <service2>=<num2> ...
# 用于暂停运行中的服务容器
$ docker-compose pause
$ docker-compose pause [SERVICE...]
# 用于停止运行中的服务容器,它会立即终止容器的运行,类似于强制执行Ctrl+C中断
$ docker-compose kill
$ docker-compose kill [OPTIONS] [SERVICE...]
# 用于验证和显示由docker-compose.yml文件定义的服务配置
$ dokcer-compose config
$ docker-compose config [OPTIONS] [SERVICE...]
# 用于创建在Docker Compose文件中定义的服务的容器,但不会启动这些容器,它主要用于预先创建容器,以便稍后通过 docker-compose start或docker-compose up命令启动这些容器
$ docker-compose create
$ docker-compose create [OPTIONS] [SERVICE...]
# 用于在运行中的服务容器中执行命令,它允许你与正在运行的容器进行交互并在其内部执行命令
$ docker-compose exec
$ docker compose exec [OPTIONS] SERVICE COMMAND [ARGS...]
# 这个例子将会进入名为web的服务容器,并在容器内执行ls -l命令来列出文件和目录
$ docker-compose exec web ls -l
# 用于查看由Docker Compose管理的服务容器的端口映射情况,它允许你查看服务容器的公开端口与主机上的端口之间的映射关系
$ docker-compose port
$ docker-compose push [OPTIONS] [SERVICE...]
# 用于取消暂停一个或多个由Docker Compose管理的服务容器,它允许你恢复被暂停的服务容器的正常运行状态
$ docker-compose unpause
$ docker compose unpause [SERVICE...]
# 这个例子将会取消暂停名为web和db的服务容器
$ docker-compose unpause web db
5、yaml规则
# docker-compose.yaml核心
# https://docs.docker.com/compose/compose-file
# 3层
version:"' #版本
services: #服务
服务1:web
# 服务配置
images
build
network
.......
服务2: redis
#其他配置 网络/卷、全局规则
volumes:
networks:
configs:
6、快速入门 Compose and WordPress(开源博客系统)
官方文档:https://docs.docker.com/samples/wordpress/
$ mkdir my_wordpress
$ cd my_wordpress/
# 创建docker-compose.yml
version: "3.3"
services:
db:
image: mysql:5.7
volumes:
- db_data:/var/lib/mysql
restart: always
environment:
MYSQL_ROOT_PASSWORD: somewordpress
MYSQL_DATABASE: wordpress
MYSQL_USER: wordpress
MYSQL_PASSWORD: wordpress
wordpress:
depends_on:
- db
image: wordpress:latest
volumes:
- wordpress_data:/var/www/html
ports:
- "8000:80"
restart: always
environment:
WORDPRESS_DB_HOST: db:3306
WORDPRESS_DB_USER: wordpress
WORDPRESS_DB_PASSWORD: wordpress
WORDPRESS_DB_NAME: wordpress
volumes:
db_data: {}
wordpress_data: {}
$ docker-compose up -d | docker-compose up
[root@zsx my_wordpress]# docker-compose up
Creating network "my_wordpress_default" with the default driver
Creating volume "my_wordpress_db_data" with default driver
Creating volume "my_wordpress_wordpress_data" with default driver
Pulling db (mysql:5.7)...
5.7: Pulling from library/mysql
a10c77af2613: Pull complete
b76a7eb51ffd: Pull complete
258223f927e4: Pull complete
2d2c75386df9: Pull complete
63e92e4046c9: Pull complete
f5845c731544: Pull complete
bd0401123a9b: Pull complete
2724b2da64fd: Pull complete
d10a7e9e325c: Pull complete
1c5fd9c3683d: Pull complete
2e35f83a12e9: Pull complete
Digest: sha256:7a3a7b7a29e6fbff433c339fc52245435fa2c308586481f2f92ab1df239d6a29
Status: Downloaded newer image for mysql:5.7
Pulling wordpress (wordpress:latest)...
latest: Pulling from library/wordpress
7d63c13d9b9b: Already exists
24b15dfd3cfa: Pulling fs layer
64625c2e355f: Pulling fs layer
275a8dd8f358: Pull complete
eb1c8ccc797a: Pull complete
0aaf98f0c33a: Pull complete
e6e7c544c3e3: Pull complete
4ae870a5fb80: Pull complete
98833c4f4a49: Pull complete
f1a6af6bf10a: Pull complete
a56ec4dacea3: Pull complete
ab49679021a9: Pull complete
62d224267322: Pull complete
50baad31f9e0: Pull complete
0dce3ac87bb9: Pull complete
6e8719cc3579: Pull complete
69628185e06b: Pull complete
3a97cd45ec02: Pull complete
abb42ef6cbf3: Pull complete
80b88db9d84e: Pull complete
ebe8bf4c22f9: Pull complete
Digest: sha256:34cc2ea05ac3622a9baf969eafc2a770339d8bdddc4ea740da9288d4a96b5fb0
Status: Downloaded newer image for wordpress:latest
Creating my_wordpress_db_1 ... done
Creating my_wordpress_wordpress_1 ... done
Attaching to my_wordpress_db_1, my_wordpress_wordpress_1
db_1 | 2021-11-17 13:36:21+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.36-1debian10 started.
db_1 | 2021-11-17 13:36:22+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
db_1 | 2021-11-17 13:36:22+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.36-1debian10 started.
db_1 | 2021-11-17 13:36:22+00:00 [Note] [Entrypoint]: Initializing database files
db_1 | 2021-11-17T13:36:22.339349Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
db_1 | 2021-11-17T13:36:22.811795Z 0 [Warning] InnoDB: New log files created, LSN=45790
db_1 | 2021-11-17T13:36:22.895504Z 0 [Warning] InnoDB: Creating foreign key constraint system tables.
wordpress_1 | WordPress not found in /var/www/html - copying now...
db_1 | 2021-11-17T13:36:22.967677Z 0 [Warning] No existing UUID has been found, so we assume that this is the first time that this server has been started. Generating a new UUID: 5ac7f67d-47ab-11ec-b66f-0242ac140002.
db_1 | 2021-11-17T13:36:22.990812Z 0 [Warning] Gtid table is not ready to be used. Table 'mysql.gtid_executed' cannot be opened.
wordpress_1 | Complete! WordPress has been successfully copied to /var/www/html
wordpress_1 | No 'wp-config.php' found in /var/www/html, but 'WORDPRESS_...' variables supplied; copying 'wp-config-docker.php' (WORDPRESS_DB_HOST WORDPRESS_DB_NAME WORDPRESS_DB_PASSWORD WORDPRESS_DB_USER)
wordpress_1 | AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 172.20.0.3. Set the 'ServerName' directive globally to suppress this message
wordpress_1 | AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 172.20.0.3. Set the 'ServerName' directive globally to suppress this message
wordpress_1 | [Wed Nov 17 13:36:24.552305 2021] [mpm_prefork:notice] [pid 1] AH00163: Apache/2.4.51 (Debian) PHP/7.4.25 configured -- resuming normal operations
wordpress_1 | [Wed Nov 17 13:36:24.552370 2021] [core:notice] [pid 1] AH00094: Command line: 'apache2 -D FOREGROUND'
db_1 | 2021-11-17T13:36:24.948286Z 0 [Warning] A deprecated TLS version TLSv1 is enabled. Please use TLSv1.2 or higher.
db_1 | 2021-11-17T13:36:24.948298Z 0 [Warning] A deprecated TLS version TLSv1.1 is enabled. Please use TLSv1.2 or higher.
db_1 | 2021-11-17T13:36:24.948652Z 0 [Warning] CA certificate ca.pem is self signed.
db_1 | 2021-11-17T13:36:25.101761Z 1 [Warning] root@localhost is created with an empty password ! Please consider switching off the --initialize-insecure option.
db_1 | 2021-11-17 13:36:27+00:00 [Note] [Entrypoint]: Database files initialized
db_1 | 2021-11-17 13:36:27+00:00 [Note] [Entrypoint]: Starting temporary server
db_1 | 2021-11-17 13:36:27+00:00 [Note] [Entrypoint]: Waiting for server startup
db_1 | 2021-11-17T13:36:27.742491Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
db_1 | 2021-11-17T13:36:27.748425Z 0 [Note] mysqld (mysqld 5.7.36) starting as process 75 ...
db_1 | 2021-11-17T13:36:27.757803Z 0 [Note] InnoDB: PUNCH HOLE support available
db_1 | 2021-11-17T13:36:27.757816Z 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
db_1 | 2021-11-17T13:36:27.757820Z 0 [Note] InnoDB: Uses event mutexes
db_1 | 2021-11-17T13:36:27.757822Z 0 [Note] InnoDB: GCC builtin __atomic_thread_fence() is used for memory barrier
db_1 | 2021-11-17T13:36:27.757824Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.11
db_1 | 2021-11-17T13:36:27.757827Z 0 [Note] InnoDB: Using Linux native AIO
db_1 | 2021-11-17T13:36:27.758223Z 0 [Note] InnoDB: Number of pools: 1
db_1 | 2021-11-17T13:36:27.758422Z 0 [Note] InnoDB: Using CPU crc32 instructions
db_1 | 2021-11-17T13:36:27.765018Z 0 [Note] InnoDB: Initializing buffer pool, total size = 128M, instances = 1, chunk size = 128M
db_1 | 2021-11-17T13:36:27.812392Z 0 [Note] InnoDB: Completed initialization of buffer pool
db_1 | 2021-11-17T13:36:27.831530Z 0 [Note] InnoDB: If the mysqld execution user is authorized, page cleaner thread priority can be changed. See the man page of setpriority().
db_1 | 2021-11-17T13:36:27.852260Z 0 [Note] InnoDB: Highest supported file format is Barracuda.
db_1 | 2021-11-17T13:36:27.870988Z 0 [Note] InnoDB: Creating shared tablespace for temporary tables
db_1 | 2021-11-17T13:36:27.871061Z 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...
db_1 | 2021-11-17T13:36:27.922228Z 0 [Note] InnoDB: File './ibtmp1' size is now 12 MB.
db_1 | 2021-11-17T13:36:27.923595Z 0 [Note] InnoDB: 96 redo rollback segment(s) found. 96 redo rollback segment(s) are active.
db_1 | 2021-11-17T13:36:27.923606Z 0 [Note] InnoDB: 32 non-redo rollback segment(s) are active.
db_1 | 2021-11-17T13:36:27.928045Z 0 [Note] InnoDB: Waiting for purge to start
db_1 | 2021-11-17T13:36:27.978670Z 0 [Note] InnoDB: 5.7.36 started; log sequence number 2749732
db_1 | 2021-11-17T13:36:27.979192Z 0 [Note] Plugin 'FEDERATED' is disabled.
db_1 | 2021-11-17T13:36:27.987243Z 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool
db_1 | 2021-11-17T13:36:27.994173Z 0 [Note] InnoDB: Buffer pool(s) load completed at 211117 13:36:27
db_1 | 2021-11-17T13:36:27.995566Z 0 [Note] Found ca.pem, server-cert.pem and server-key.pem in data directory. Trying to enable SSL support using them.
db_1 | 2021-11-17T13:36:27.995576Z 0 [Note] Skipping generation of SSL certificates as certificate files are present in data directory.
db_1 | 2021-11-17T13:36:27.995579Z 0 [Warning] A deprecated TLS version TLSv1 is enabled. Please use TLSv1.2 or higher.
db_1 | 2021-11-17T13:36:27.995582Z 0 [Warning] A deprecated TLS version TLSv1.1 is enabled. Please use TLSv1.2 or higher.
db_1 | 2021-11-17T13:36:27.996152Z 0 [Warning] CA certificate ca.pem is self signed.
db_1 | 2021-11-17T13:36:27.996182Z 0 [Note] Skipping generation of RSA key pair as key files are present in data directory.
db_1 | 2021-11-17T13:36:27.998792Z 0 [Warning] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory.
db_1 | 2021-11-17T13:36:28.006867Z 0 [Note] Event Scheduler: Loaded 0 events
db_1 | 2021-11-17T13:36:28.007065Z 0 [Note] mysqld: ready for connections.
db_1 | Version: '5.7.36' socket: '/var/run/mysqld/mysqld.sock' port: 0 MySQL Community Server (GPL)
db_1 | 2021-11-17 13:36:28+00:00 [Note] [Entrypoint]: Temporary server started.
db_1 | Warning: Unable to load '/usr/share/zoneinfo/iso3166.tab' as time zone. Skipping it.
db_1 | Warning: Unable to load '/usr/share/zoneinfo/leap-seconds.list' as time zone. Skipping it.
db_1 | 2021-11-17T13:36:29.685968Z 3 [ERROR] InnoDB: posix_fallocate(): Failed to preallocate data for file ./ibdata1, desired size 67108864 bytes. Operating system error number 28. Check that the disk is not full or a disk quota exceeded. Make sure the file system supports this function. Some operating system error numbers are described at http://dev.mysql.com/doc/refman/5.7/en/operating-system-error-codes.html
db_1 | 2021-11-17T13:36:29.790284Z 3 [Warning] InnoDB: 1048576 bytes should have been written. Only 458752 bytes written. Retrying for the remaining bytes.
db_1 | Warning: Unable to load '/usr/share/zoneinfo/zone.tab' as time zone. Skipping it.
db_1 | Warning: Unable to load '/usr/share/zoneinfo/zone1970.tab' as time zone. Skipping it.
db_1 | 2021-11-17 13:36:30+00:00 [Note] [Entrypoint]: Creating database wordpress
db_1 | 2021-11-17 13:36:30+00:00 [Note] [Entrypoint]: Creating user wordpress
db_1 | 2021-11-17 13:36:30+00:00 [Note] [Entrypoint]: Giving user wordpress access to schema wordpress
db_1 |
db_1 | 2021-11-17 13:36:30+00:00 [Note] [Entrypoint]: Stopping temporary server
db_1 | 2021-11-17T13:36:30.508846Z 0 [Note] Giving 0 client threads a chance to die gracefully
db_1 | 2021-11-17T13:36:30.508863Z 0 [Note] Shutting down slave threads
db_1 | 2021-11-17T13:36:30.508869Z 0 [Note] Forcefully disconnecting 0 remaining clients
db_1 | 2021-11-17T13:36:30.508873Z 0 [Note] Event Scheduler: Purging the queue. 0 events
db_1 | 2021-11-17T13:36:30.509375Z 0 [Note] Binlog end
db_1 | 2021-11-17T13:36:30.509873Z 0 [Note] Shutting down plugin 'ngram'
db_1 | 2021-11-17T13:36:30.509880Z 0 [Note] Shutting down plugin 'partition'
db_1 | 2021-11-17T13:36:30.509882Z 0 [Note] Shutting down plugin 'BLACKHOLE'
db_1 | 2021-11-17T13:36:30.509885Z 0 [Note] Shutting down plugin 'ARCHIVE'
db_1 | 2021-11-17T13:36:30.509887Z 0 [Note] Shutting down plugin 'PERFORMANCE_SCHEMA'
db_1 | 2021-11-17T13:36:30.509907Z 0 [Note] Shutting down plugin 'MRG_MYISAM'
db_1 | 2021-11-17T13:36:30.509912Z 0 [Note] Shutting down plugin 'MyISAM'
db_1 | 2021-11-17T13:36:30.509919Z 0 [Note] Shutting down plugin 'INNODB_SYS_VIRTUAL'
db_1 | 2021-11-17T13:36:30.509922Z 0 [Note] Shutting down plugin 'INNODB_SYS_DATAFILES'
db_1 | 2021-11-17T13:36:30.509924Z 0 [Note] Shutting down plugin 'INNODB_SYS_TABLESPACES'
db_1 | 2021-11-17T13:36:30.509925Z 0 [Note] Shutting down plugin 'INNODB_SYS_FOREIGN_COLS'
db_1 | 2021-11-17T13:36:30.509927Z 0 [Note] Shutting down plugin 'INNODB_SYS_FOREIGN'
db_1 | 2021-11-17T13:36:30.509929Z 0 [Note] Shutting down plugin 'INNODB_SYS_FIELDS'
db_1 | 2021-11-17T13:36:30.509931Z 0 [Note] Shutting down plugin 'INNODB_SYS_COLUMNS'
db_1 | 2021-11-17T13:36:30.509932Z 0 [Note] Shutting down plugin 'INNODB_SYS_INDEXES'
db_1 | 2021-11-17T13:36:30.509934Z 0 [Note] Shutting down plugin 'INNODB_SYS_TABLESTATS'
db_1 | 2021-11-17T13:36:30.509936Z 0 [Note] Shutting down plugin 'INNODB_SYS_TABLES'
db_1 | 2021-11-17T13:36:30.509937Z 0 [Note] Shutting down plugin 'INNODB_FT_INDEX_TABLE'
db_1 | 2021-11-17T13:36:30.509939Z 0 [Note] Shutting down plugin 'INNODB_FT_INDEX_CACHE'
db_1 | 2021-11-17T13:36:30.509940Z 0 [Note] Shutting down plugin 'INNODB_FT_CONFIG'
db_1 | 2021-11-17T13:36:30.509942Z 0 [Note] Shutting down plugin 'INNODB_FT_BEING_DELETED'
db_1 | 2021-11-17T13:36:30.509944Z 0 [Note] Shutting down plugin 'INNODB_FT_DELETED'
db_1 | 2021-11-17T13:36:30.509945Z 0 [Note] Shutting down plugin 'INNODB_FT_DEFAULT_STOPWORD'
db_1 | 2021-11-17T13:36:30.509947Z 0 [Note] Shutting down plugin 'INNODB_METRICS'
db_1 | 2021-11-17T13:36:30.509949Z 0 [Note] Shutting down plugin 'INNODB_TEMP_TABLE_INFO'
db_1 | 2021-11-17T13:36:30.509950Z 0 [Note] Shutting down plugin 'INNODB_BUFFER_POOL_STATS'
db_1 | 2021-11-17T13:36:30.509952Z 0 [Note] Shutting down plugin 'INNODB_BUFFER_PAGE_LRU'
db_1 | 2021-11-17T13:36:30.509954Z 0 [Note] Shutting down plugin 'INNODB_BUFFER_PAGE'
db_1 | 2021-11-17T13:36:30.509955Z 0 [Note] Shutting down plugin 'INNODB_CMP_PER_INDEX_RESET'
db_1 | 2021-11-17T13:36:30.509957Z 0 [Note] Shutting down plugin 'INNODB_CMP_PER_INDEX'
db_1 | 2021-11-17T13:36:30.509958Z 0 [Note] Shutting down plugin 'INNODB_CMPMEM_RESET'
db_1 | 2021-11-17T13:36:30.509960Z 0 [Note] Shutting down plugin 'INNODB_CMPMEM'
db_1 | 2021-11-17T13:36:30.509962Z 0 [Note] Shutting down plugin 'INNODB_CMP_RESET'
db_1 | 2021-11-17T13:36:30.509963Z 0 [Note] Shutting down plugin 'INNODB_CMP'
db_1 | 2021-11-17T13:36:30.509965Z 0 [Note] Shutting down plugin 'INNODB_LOCK_WAITS'
db_1 | 2021-11-17T13:36:30.509966Z 0 [Note] Shutting down plugin 'INNODB_LOCKS'
db_1 | 2021-11-17T13:36:30.509968Z 0 [Note] Shutting down plugin 'INNODB_TRX'
db_1 | 2021-11-17T13:36:30.509970Z 0 [Note] Shutting down plugin 'InnoDB'
db_1 | 2021-11-17T13:36:30.510064Z 0 [Note] InnoDB: FTS optimize thread exiting.
db_1 | 2021-11-17T13:36:30.511766Z 0 [Note] InnoDB: Starting shutdown...
db_1 | 2021-11-17T13:36:30.613210Z 0 [Note] InnoDB: Dumping buffer pool(s) to /var/lib/mysql/ib_buffer_pool
db_1 | 2021-11-17T13:36:30.614166Z 0 [Note] InnoDB: Buffer pool(s) dump completed at 211117 13:36:30
db_1 | 2021-11-17T13:36:31.932081Z 0 [Note] InnoDB: Shutdown completed; log sequence number 12659654
db_1 | 2021-11-17T13:36:31.933189Z 0 [Note] InnoDB: Removed temporary tablespace data file: "ibtmp1"
db_1 | 2021-11-17T13:36:31.933204Z 0 [Note] Shutting down plugin 'MEMORY'
db_1 | 2021-11-17T13:36:31.933210Z 0 [Note] Shutting down plugin 'CSV'
db_1 | 2021-11-17T13:36:31.933214Z 0 [Note] Shutting down plugin 'sha256_password'
db_1 | 2021-11-17T13:36:31.933216Z 0 [Note] Shutting down plugin 'mysql_native_password'
db_1 | 2021-11-17T13:36:31.933297Z 0 [Note] Shutting down plugin 'binlog'
db_1 | 2021-11-17T13:36:31.934507Z 0 [Note] mysqld: Shutdown complete
db_1 |
db_1 | 2021-11-17 13:36:32+00:00 [Note] [Entrypoint]: Temporary server stopped
db_1 |
db_1 | 2021-11-17 13:36:32+00:00 [Note] [Entrypoint]: MySQL init process done. Ready for start up.
db_1 |
db_1 | 2021-11-17T13:36:32.781689Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
db_1 | 2021-11-17T13:36:32.783050Z 0 [Note] mysqld (mysqld 5.7.36) starting as process 1 ...
db_1 | 2021-11-17T13:36:32.785342Z 0 [Note] InnoDB: PUNCH HOLE support available
db_1 | 2021-11-17T13:36:32.785356Z 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
db_1 | 2021-11-17T13:36:32.785359Z 0 [Note] InnoDB: Uses event mutexes
db_1 | 2021-11-17T13:36:32.785361Z 0 [Note] InnoDB: GCC builtin __atomic_thread_fence() is used for memory barrier
db_1 | 2021-11-17T13:36:32.785363Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.11
db_1 | 2021-11-17T13:36:32.785367Z 0 [Note] InnoDB: Using Linux native AIO
db_1 | 2021-11-17T13:36:32.785547Z 0 [Note] InnoDB: Number of pools: 1
db_1 | 2021-11-17T13:36:32.787122Z 0 [Note] InnoDB: Using CPU crc32 instructions
db_1 | 2021-11-17T13:36:32.788548Z 0 [Note] InnoDB: Initializing buffer pool, total size = 128M, instances = 1, chunk size = 128M
db_1 | 2021-11-17T13:36:32.794481Z 0 [Note] InnoDB: Completed initialization of buffer pool
db_1 | 2021-11-17T13:36:32.796197Z 0 [Note] InnoDB: If the mysqld execution user is authorized, page cleaner thread priority can be changed. See the man page of setpriority().
db_1 | 2021-11-17T13:36:32.821367Z 0 [Note] InnoDB: Highest supported file format is Barracuda.
db_1 | 2021-11-17T13:36:32.830037Z 0 [Note] InnoDB: Creating shared tablespace for temporary tables
db_1 | 2021-11-17T13:36:32.830126Z 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...
db_1 | 2021-11-17T13:36:32.856655Z 0 [Note] InnoDB: File './ibtmp1' size is now 12 MB.
db_1 | 2021-11-17T13:36:32.857162Z 0 [Note] InnoDB: 96 redo rollback segment(s) found. 96 redo rollback segment(s) are active.
db_1 | 2021-11-17T13:36:32.857171Z 0 [Note] InnoDB: 32 non-redo rollback segment(s) are active.
db_1 | 2021-11-17T13:36:32.857387Z 0 [Note] InnoDB: Waiting for purge to start
db_1 | 2021-11-17T13:36:32.907628Z 0 [Note] InnoDB: 5.7.36 started; log sequence number 12659654
db_1 | 2021-11-17T13:36:32.908107Z 0 [Note] Plugin 'FEDERATED' is disabled.
db_1 | 2021-11-17T13:36:32.917965Z 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool
db_1 | 2021-11-17T13:36:32.922357Z 0 [Note] Found ca.pem, server-cert.pem and server-key.pem in data directory. Trying to enable SSL support using them.
db_1 | 2021-11-17T13:36:32.922376Z 0 [Note] Skipping generation of SSL certificates as certificate files are present in data directory.
db_1 | 2021-11-17T13:36:32.922383Z 0 [Warning] A deprecated TLS version TLSv1 is enabled. Please use TLSv1.2 or higher.
db_1 | 2021-11-17T13:36:32.922388Z 0 [Warning] A deprecated TLS version TLSv1.1 is enabled. Please use TLSv1.2 or higher.
db_1 | 2021-11-17T13:36:32.923119Z 0 [Warning] CA certificate ca.pem is self signed.
db_1 | 2021-11-17T13:36:32.923162Z 0 [Note] Skipping generation of RSA key pair as key files are present in data directory.
db_1 | 2021-11-17T13:36:32.923869Z 0 [Note] Server hostname (bind-address): '*'; port: 3306
db_1 | 2021-11-17T13:36:32.923950Z 0 [Note] IPv6 is available.
db_1 | 2021-11-17T13:36:32.923966Z 0 [Note] - '::' resolves to '::';
db_1 | 2021-11-17T13:36:32.923986Z 0 [Note] Server socket created on IP: '::'.
db_1 | 2021-11-17T13:36:32.925977Z 0 [Note] InnoDB: Buffer pool(s) load completed at 211117 13:36:32
db_1 | 2021-11-17T13:36:32.930458Z 0 [Warning] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory.
db_1 | 2021-11-17T13:36:32.938605Z 0 [Note] Event Scheduler: Loaded 0 events
db_1 | 2021-11-17T13:36:32.938733Z 0 [Note] mysqld: ready for connections.
db_1 | Version: '5.7.36' socket: '/var/run/mysqld/mysqld.sock' port: 3306 MySQL Community Server (GPL)
$ http://192.168.157.113:8000
7、SpringBoot打包成Docker镜像
7.1 编写一个springboot项目并且打包成jar包
package com.example.demo.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello(){
return "Hello World!!!";
}
}
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
7.2 安装docker插件
Docker integration
7.3 在target目录下编写Dockerfile文件
FROM java:8
COPY *.jar /app.jar
CMD ["--server.port=8080"]
EXPOSE 8080
ENTRYPOINT ["java","-jar","/app.jar"]
7.4 构建镜像
$ docker build -t demo:v1 .
[root@zsx demodocker]# docker build -t demo:v1 .
Sending build context to Docker daemon 17.35MB
Step 1/5 : FROM java:8
8: Pulling from library/java
5040bd298390: Pull complete
fce5728aad85: Pull complete
76610ec20bf5: Pull complete
60170fec2151: Pull complete
e98f73de8f0d: Pull complete
11f7af24ed9c: Pull complete
49e2d6393f32: Pull complete
bb9cdec9c7f3: Pull complete
Digest: sha256:c1ff613e8ba25833d2e1940da0940c3824f03f802c449f3d1815a66b7f8c0e9d
Status: Downloaded newer image for java:8
---> d23bdf5b1b1b
Step 2/5 : COPY *.jar /app.jar
---> 14d65030b1ee
Step 3/5 : CMD ["--server.port=8080"]
---> Running in a6d97239ee29
Removing intermediate container a6d97239ee29
---> e791321b2a71
Step 4/5 : EXPOSE 8080
---> Running in d0a832d6f522
Removing intermediate container d0a832d6f522
---> aa34141b1acd
Step 5/5 : ENTRYPOINT ["java","-jar","/app.jar"]
---> Running in d6e8b1a37793
Removing intermediate container d6e8b1a37793
---> e1cacbe7acb1
Successfully built e1cacbe7acb1
Successfully tagged demo:v1
$ docker images
7.5 运行
$ docker run -d -P --name spring-boot-demo demo:v1
$ curl http://192.168.33.113:49153/hello
8、SpringBoot使用Docker Compose打包
package com.example.demo1.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@Autowired
StringRedisTemplate stringRedisTemplate;
@RequestMapping("/hello")
public String hello() {
long views = stringRedisTemplate.opsForValue().increment("views");
return "您的网站被放访问了" + views + "次!!!";
}
}
package com.example.demo1;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Demo1Application {
public static void main(String[] args) {
SpringApplication.run(Demo1Application.class, args);
}
}
server.port=8080
spring.redis.host=redis
spring.redis.port=6379
FROM java:8
COPY *.jar /app.jar
CMD ["--server.port=8080"]
EXPOSE 8080
ENTRYPOINT ["java","-jar","/app.jar"]
version: '3.3'
services:
kuangapp:
build: .
image: democompose:v1
depends_on:
- redis
ports:
- "8080:8080"
redis:
image: "redis:alpine"
$ docker-compose up
network "demodockercompose_default" with the default driver
Pulling redis (redis:alpine)...
alpine: Pulling from library/redis
97518928ae5f: Pull complete
66f8c4150d27: Pull complete
09a8bf17a0bf: Pull complete
e547313af8e7: Pull complete
335eeadfbde0: Pull complete
7151fc2c01eb: Pull complete
Digest: sha256:50fc99c529b81432a592fa76354783d7fc3ba479a92fc810cbf669138c4138b7
Status: Downloaded newer image for redis:alpine
Building kuangapp
Step 1/5 : FROM java:8
---> d23bdf5b1b1b
Step 2/5 : COPY *.jar /app.jar
---> 6c9ac87654f7
Step 3/5 : CMD ["--server.port=8080"]
---> Running in 9a405586e220
Removing intermediate container 9a405586e220
---> 214642179828
Step 4/5 : EXPOSE 8080
---> Running in 13656a392e1a
Removing intermediate container 13656a392e1a
---> 5d63444b57ed
Step 5/5 : ENTRYPOINT ["java","-jar","/app.jar"]
---> Running in 90c019755846
Removing intermediate container 90c019755846
---> 5d4adc9ec9c8
Successfully built 5d4adc9ec9c8
Successfully tagged democompose:v1
WARNING: Image for service kuangapp was built because it did not already exist. To rebuild this image you must use `docker-compose build` or `docker-compose up --build`.
Creating demodockercompose_redis_1 ... done
Creating demodockercompose_kuangapp_1 ... done
Attaching to demodockercompose_redis_1, demodockercompose_kuangapp_1
redis_1 | 1:C 18 Nov 2021 05:39:02.317 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
redis_1 | 1:C 18 Nov 2021 05:39:02.317 # Redis version=6.2.6, bits=64, commit=00000000, modified=0, pid=1, just started
redis_1 | 1:C 18 Nov 2021 05:39:02.317 # 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 18 Nov 2021 05:39:02.318 * monotonic clock: POSIX clock_gettime
redis_1 | 1:M 18 Nov 2021 05:39:02.319 * Running mode=standalone, port=6379.
redis_1 | 1:M 18 Nov 2021 05:39:02.319 # 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 18 Nov 2021 05:39:02.319 # Server initialized
redis_1 | 1:M 18 Nov 2021 05:39:02.319 # 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 18 Nov 2021 05:39:02.319 * Ready to accept connections
kuangapp_1 |
kuangapp_1 | . ____ _ __ _ _
kuangapp_1 | /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
kuangapp_1 | ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
kuangapp_1 | \\/ ___)| |_)| | | | | || (_| | ) ) ) )
kuangapp_1 | ' |____| .__|_| |_|_| |_\__, | / / / /
kuangapp_1 | =========|_|==============|___/=/_/_/_/
kuangapp_1 | :: Spring Boot :: (v2.5.4)
kuangapp_1 |
kuangapp_1 | 2021-11-18 05:39:04.350 INFO 1 --- [ main] com.example.demo1.Demo1Application : Starting Demo1Application v0.0.1-SNAPSHOT using Java 1.8.0_111 on 9891fca7c1d2 with PID 1 (/app.jar started by root in /)
kuangapp_1 | 2021-11-18 05:39:04.353 INFO 1 --- [ main] com.example.demo1.Demo1Application : No active profile set, falling back to default profiles: default
kuangapp_1 | 2021-11-18 05:39:05.586 INFO 1 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
kuangapp_1 | 2021-11-18 05:39:05.608 INFO 1 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data Redis repositories in DEFAULT mode.
kuangapp_1 | 2021-11-18 05:39:05.697 INFO 1 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 10 ms. Found 0 Redis repository interfaces.
kuangapp_1 | 2021-11-18 05:39:06.584 INFO 1 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
kuangapp_1 | 2021-11-18 05:39:06.631 INFO 1 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
kuangapp_1 | 2021-11-18 05:39:06.631 INFO 1 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.52]
kuangapp_1 | 2021-11-18 05:39:06.764 INFO 1 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
kuangapp_1 | 2021-11-18 05:39:06.765 INFO 1 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2288 ms
kuangapp_1 | 2021-11-18 05:39:08.794 INFO 1 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
kuangapp_1 | 2021-11-18 05:39:08.814 INFO 1 --- [ main] com.example.demo1.Demo1Application : Started Demo1Application in 5.317 seconds (JVM running for 6.072)
$ curl http://192.168.33.113:8080/hello