华子目录
容器编排工具docker compose
compose介绍
- Docker Compose是一个用于定义和运行多容器Docker应用程序的工具。它使用yaml文件来配置应用程序的服务,然后使用一个命令,就可以启动并运行配置的所有服务。Docker Compose非常适合用于开发、测试和部署分布式应用,因为它可以管理容器的生命周期,使用单个命令就可以启动或停止多个容器。
compose使用的三个步骤
- 使用
dockerfile
定义应用程序的环境 - 使用
docker-compose.yml
定义构成应用程序的服务,这样它们可以在隔离环境中一起运行 - 最后,执行
docker-compose up
命令来启动并运行整个应用程序
docker-compose.yml文件案例
version '2'
services:
web:
build:
ports:
- "5000:5000"
volumes:
- .:/code
redis:
image: redis
compose具有管理应用程序整个生命周期的命令
- 启动,停止和重建服务
- 查看正在运行的服务的状态
- 流式传输运行服务的日志输出
- 在服务上运行一次性命令
docker compose安装
安装条件
- docker compose依靠docker engine进行有意义的工作,因此请确保你已在本地或远程安装docker engine,具体取决于你的设置
- 要以非root用户身份运行compose,请参考以非root用户身份管理docker
- 安装系统
- Linux
- Mac
- Windows
- 备用安装选项(使用pip安装/安装为容器)
在Linux系统上安装compose
(1)下载安装
- 在GitHub上,查询适合自己的版本https://github.com/docker/compose/releases/download/v2.26.0/docker-compose-linux-x86_64
[root@server ~]# wget https://github.com/docker/compose/releases/download/v2.26.0/docker-compose-linux-x86_64
[root@server ~]# mv docker-compose-linux-x86_64 docker-compose
[root@server ~]# mv docker-compose /usr/local/bin/
[root@server ~]# chmod +x /usr/local/bin/docker-compose
[root@server ~]# docker-compose version
Docker Compose version v2.26.0 #显示安装成功
- 通过pip安装
[root@server ~]# yum install epel-release -y #安装pip需要先安装epel-release包
[root@server ~]# yum install -y python-pip #安装pip
[root@server ~]# pip install --upgrade pip #升级pip
[root@server ~]# pip install docker-compose #安装docker-compose
(1)添加执行权限
[root@server ~]# chmod +x /usr/bin/docker-compose
(2)查看版本
[root@server ~]# docker-compose --version #查看docker-compose版本
docker compose卸载
(1)正常系统安装卸载
[root@server ~]# rm -vf /usr/local/bin/docker-compose
(2)pip安装卸载
[root@server ~]# pip uninstall docker-compose
docker compose运用演示
- 创建compose工作目录
[root@server ~]# mkdir compose-test
[root@server ~]# cd compose-test/
- 创建一个app.py文件,后面在项目目录中调用文件
[root@server compose-test]# vim 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)
if __name__ == "__main__":
app.run(host="0.0.0.0",debug=True)
注:redis是应用程序网络上redis容器的主机名,我们使用redis的默认端口是6379
- 创建requirements.txt项目目录中调用的另一个文件
[root@server compose-test]# vim requirements.txt
flask
redis
- 在compose-test目录中创建dockerfile文本
[root@server compose-test]# vim Dockerfile
FROM python:3.7
WORKDIR /code
ENV FLASK_APP app.py
ENV FLASK_RUN_HOST 0.0.0.0
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
COPY . .
CMD ["flask","run"]
注:
- 从python3.7映射开始构建镜像
- 将工作目录设置为/code
- 设置flask命令使用的环境变量
- 复制requirements.txt并安装python依赖项
- 安装python依赖项
- 将.项目中的当前目录复制到.镜像中的工作目录
- 将容器的默认命令设置为flask run
- 创建docker-compose.yml项目目录中调用的文件
[root@server compose-test]# vim docker-compose.yml
version: '3'
services:
web:
build: .
ports:
- "5000:5000"
redis:
image: "redis:alpine"
此compose文件定义了两个服务,web和redis,该web服务:
- 使用build指定构建上下文路径,"."表示利用当前目录中的dockerfile构建应用镜像
- 将容器上的公开端口5000转发到主机上的端口5000,我们使用Flask Web服务器的默认端口5000
- 如果本地不存在该镜像,compose将尝试拉取Redis镜像
- 使用compose构建并运行你的应用程序
- 在项目目录中,启动应用程序
docker-compose up
- 构建之前可以先将python:3.7和redis:alpine拉取到本地
[root@server compose-test]# docker pull python:3.7
3.7: Pulling from library/python
0e29546d541c: Pull complete
9b829c73b52b: Pull complete
cb5b7ae36172: Pull complete
6494e4811622: Pull complete
6f9f74896dfa: Pull complete
fcb6d5f7c986: Pull complete
7a72d131c196: Pull complete
c4221d178521: Pull complete
71d5c5b5a91f: Pull complete
Digest: sha256:d9abbc0737ff8d23a546859c85903f1b8235a1495a405d5a47cbc55747f27b20
Status: Downloaded newer image for python:3.7
docker.io/library/python:3.7
[root@server compose-test]# docker pull redis:alpine
alpine: Pulling from library/redis
59bf1c3509f3: Pull complete
719adce26c52: Pull complete
b8f35e378c31: Pull complete
d034517f789c: Pull complete
3772d4d76753: Pull complete
211a7f52febb: Pull complete
Digest: sha256:4bed291aa5efb9f0d77b76ff7d4ab71eee410962965d052552db1fb80576431d
Status: Downloaded newer image for redis:alpine
docker.io/library/redis:alpine
[root@server compose-test]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
python 3.7 ad37de9b03ef 2 years ago 903MB
mysql latest 3218b38490ce 2 years ago 516MB
redis alpine 3900abf41552 2 years ago 32.4MB
ubuntu latest ba6acccedd29 2 years ago 72.8MB
[root@server compose-test]# docker-compose up -d #-d后台运行该服务
WARN[0000] /root/compose-test/docker-compose.yml: `version` is obsolete
[+] Building 22.1s (10/10) FINISHED docker:default
=> [web internal] load build definition from Dockerfile 0.0s
=> => transferring dockerfile: 221B 0.0s
=> [web internal] load metadata for docker.io/library/python:3.7 0.0s
=> [web internal] load .dockerignore 0.0s
=> => transferring context: 2B 0.0s
=> [web 1/5] FROM docker.io/library/python:3.7 0.0s
=> [web internal] load build context 0.0s
=> => transferring context: 319B 0.0s
=> CACHED [web 2/5] WORKDIR /code 0.0s
=> [web 3/5] COPY requirements.txt requirements.txt 0.0s
=> [web 4/5] RUN pip install -r requirements.txt 21.5s
=> [web 5/5] COPY . . 0.1s
=> [web] exporting to image 0.4s
=> => exporting layers 0.4s
=> => writing image sha256:ab305846f0c5b6917a118d6ef17b001317d4a04c15d4 0.0s
=> => naming to docker.io/library/compose-test-web 0.0s
[+] Running 3/3
✔ Network compose-test_default Crea... 0.2s
✔ Container compose-test-redis-1 St... 0.2s
✔ Container compose-test-web-1 Star... 0.1s
- 浏览器查询http://192.168.80.132:5000,进行验证
- 刷新页面,数字增加
- 另开一个终端,查看镜像和容器验证
[root@server ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
compose-test-web latest ab305846f0c5 17 minutes ago 916MB
python 3.7 ad37de9b03ef 2 years ago 903MB
mysql latest 3218b38490ce 2 years ago 516MB
redis alpine 3900abf41552 2 years ago 32.4MB
ubuntu latest ba6acccedd29 2 years ago 72.8MB
[root@server ~]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
6d70bdd98730 redis:alpine "docker-entrypoint.s…" 19 minutes ago Up 19 minutes 6379/tcp compose-test-redis-1
1b02950d60cd compose-test-web "flask run" 19 minutes ago Up 19 minutes 0.0.0.0:5000->5000/tcp, :::5000->5000/tcp compose-test-web-1
ea6beb680b7a mysql:latest "docker-entrypoint.s…" 20 hours ago Exited (255) 32 minutes ago 0.0.0.0:3306->3306/tcp, :::3306->3306/tcp, 33060/tcp mysql
871fe7e0e9a3 ubuntu:latest "bash" 21 hours ago Exited (255) 32 minutes ago ubuntu
- 关闭服务
在新开的终端docker-compose down
,或者在启动应用程序的原始终端中按Ctrl+C
来停止应用程序
修改compose配置,添加存储卷
[root@server compose-test]# vim docker-compose.yml
version: '3'
services:
web:
build: .
ports:
- "5000:5000"
volumes:
- .:/code
redis:
image: "redis:alpine"
注:
将主机的数据卷挂载到容器里
测试存储卷
- 重新启动compose
[root@server compose-test]# docker-compose up
WARN[0000] /root/compose-test/docker-compose.yml: `version` is obsolete
[+] Running 1/0
⠋ Container compose-test-web-1 Recreated 0.1s
✔ Container compose-test-redis-1 Created 0.0s
Attaching to redis-1, web-1
redis-1 | 1:C 31 Mar 2024 07:04:14.920 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
redis-1 | 1:C 31 Mar 2024 07:04:14.935 # Redis version=6.2.6, bits=64, commit=00000000, modified=0, pid=1, just started
redis-1 | 1:C 31 Mar 2024 07:04:14.935 # 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 31 Mar 2024 07:04:14.940 * monotonic clock: POSIX clock_gettime
redis-1 | 1:M 31 Mar 2024 07:04:14.941 * Running mode=standalone, port=6379.
redis-1 | 1:M 31 Mar 2024 07:04:14.941 # Server initialized
redis-1 | 1:M 31 Mar 2024 07:04:14.941 # 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 31 Mar 2024 07:04:14.941 * Loading RDB produced by version 6.2.6
redis-1 | 1:M 31 Mar 2024 07:04:14.941 * RDB age 236 seconds
redis-1 | 1:M 31 Mar 2024 07:04:14.941 * RDB memory usage when created 0.77 Mb
redis-1 | 1:M 31 Mar 2024 07:04:14.941 # Done loading RDB, keys loaded: 0, keys expired: 0.
redis-1 | 1:M 31 Mar 2024 07:04:14.941 * DB loaded from disk: 0.000 seconds
redis-1 | 1:M 31 Mar 2024 07:04:14.941 * Ready to accept connections
web-1 | * Serving Flask app 'app.py'
web-1 | * Debug mode: off
web-1 | WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
web-1 | * Running on all addresses (0.0.0.0)
web-1 | * Running on http://127.0.0.1:5000
web-1 | * Running on http://172.19.0.3:5000
web-1 | Press CTRL+C to quit
- 在宿主机的存储卷上,修改代码
[root@server compose-test]# vim 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 am along! I have been seen {} times.\n'.format(count)
if __name__ == "__main__":
app.run(host="0.0.0.0",debug=True)
重新启动
[root@server compose-test]# docker-compose up
- 在浏览器上刷新,验证成功
docker-compose其他命令
- 在后台运行服务,(-d)
[root@server compose-test]# docker-compose up -d
- 使用
docker-compose ps
查看当前正在运行的内容
[root@server compose-test]# docker-compose ps
WARN[0000] /root/compose-test/docker-compose.yml: `version` is obsolete
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
compose-test-redis-1 redis:alpine "docker-entrypoint.s…" redis 12 minutes ago Up 3 minutes 6379/tcp
compose-test-web-1 compose-test-web "flask run" web 7 minutes ago Up 3 minutes 0.0.0.0:5000->5000/tcp, :::5000->5000/tcp
docker-compose run
命令允许你为服务运行一次性命令。例如:要查看web服务可用的环境变量
[root@server compose-test]# docker-compose run web env
WARN[0000] /root/compose-test/docker-compose.yml: `version` is obsolete
PATH=/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=ccc93be20d0c
TERM=xterm
LANG=C.UTF-8
GPG_KEY=0D96DF4D4110E5C43FBFB17F2D347EA6AA65421D
PYTHON_VERSION=3.7.12
PYTHON_PIP_VERSION=21.2.4
PYTHON_SETUPTOOLS_VERSION=57.5.0
PYTHON_GET_PIP_URL=https://github.com/pypa/get-pip/raw/3cb8888cc2869620f57d5d2da64da38f516078c7/public/get-pip.py
PYTHON_GET_PIP_SHA256=c518250e91a70d7b20cceb15272209a4ded2a0c263ae5776f129e0d9b5674309
FLASK_APP=app.py
FLASK_RUN_HOST=0.0.0.0
HOME=/root
- 停止服务
[root@server compose-test]# docker-compose stop
WARN[0000] /root/compose-test/docker-compose.yml: `version` is obsolete
[+] Stopping 2/2
✔ Container compose-test-redis-1 Stopped 0.3s
✔ Container compose-test-web-1 Stopped 10.4s
- 使用down命令完全删除容器,加
--volumes
参数还可以删除redis容器使用的数据卷
[root@server compose-test]# docker-compose down --volumes
WARN[0000] /root/compose-test/docker-compose.yml: `version` is obsolete
[+] Running 3/3
✔ Container compose-test-web-1 Removed 0.0s
✔ Container compose-test-redis-1 Removed 0.0s
✔ Network compose-test_default Removed 0.2s
[root@server ~]# docker-compose --help
Usage: docker compose [OPTIONS] COMMAND
Define and run multi-container applications with Docker
Options:
--ansi string Control when to print ANSI control characters ("never"|"always"|"auto") (default "auto")
--compatibility Run compose in backward compatibility mode
--dry-run Execute command in dry run mode
--env-file stringArray Specify an alternate environment file
-f, --file stringArray Compose configuration files
--parallel int Control max parallelism, -1 for unlimited (default -1)
--profile stringArray Specify a profile to enable
--progress string Set type of progress output (auto, tty, plain, quiet) (default "auto")
--project-directory string Specify an alternate working directory
(default: the path of the, first specified, Compose file)
-p, --project-name string Project name
Commands:
attach Attach local standard input, output, and error streams to a service's running container
build Build or rebuild services
config Parse, resolve and render compose file in 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
scale Scale services
start Start services
stats Display a live stream of container(s) resource usage statistics
stop Stop services
top Display the running processes
unpause Unpause services
up Create and start containers
version Show the Docker Compose version information
wait Block until the first service container stops
watch Watch build context for service and rebuild/refresh containers when files are updated
Run 'docker compose COMMAND --help' for more information on a command.
实例2
以下是一个简单的Docker Compose实例,用于部署一个基于Nginx的Web应用程序:
首先,你需要创建一个docker-compose.yml
文件,该文件定义了应用程序的服务以及每个服务的配置。在这个例子中,我们将定义一个名为web
的服务,该服务使用Nginx镜像:
version: '3'
services:
web:
image: nginx
ports:
- "8080:80"
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf
在这个配置中:
version: '3'
指定了Docker Compose文件的版本。services
下面定义了我们的服务,这里只有一个名为web
的服务。image: nginx
指定了服务使用的Docker镜像,这里是Nginx。ports
将主机的8080端口映射到容器的80端口,这样我们就可以通过访问主机的8080端口来访问Nginx服务。volumes
将当前目录下的nginx.conf
文件挂载到容器的/etc/nginx/nginx.conf
路径,这样我们就可以自定义Nginx的配置。
接下来,你需要创建一个自定义的Nginx配置文件nginx.conf
,例如:
server {
listen 80;
server_name localhost;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
}
这个配置定义了一个监听80端口的服务器,并将请求映射到容器的/usr/share/nginx/html
目录。try_files
指令用于处理单页面应用(SPA)中的路由问题。
现在,你可以将你的Web应用文件(例如index.html
)放在与docker-compose.yml
和nginx.conf
相同的目录中。
最后,运行以下命令来启动你的Web应用程序:
docker-compose up -d
-d
参数表示在后台运行容器。运行此命令后,Docker Compose将构建并启动Nginx容器,并将你的Web应用文件作为Nginx的根目录。你现在可以通过访问http://localhost:8080
来查看你的Web应用程序。
当你需要停止并删除容器时,可以使用以下命令:
docker-compose down
docker与docker-compose的区别
Docker与Docker Compose的主要区别体现在它们的功能和用途上。
-
Docker是一个开源的应用容器引擎,它允许开发者将应用程序及其依赖打包到一个可移植的容器中,然后发布到任何流行的Linux机器上,实现虚拟化。每个容器之间完全隔离,有自己的文件系统,进程不会相互影响,能区分计算资源。这种容器化技术解决了运行环境和配置问题,方便进行持续集成并有助于整体发布。通过Docker,用户可以快速地交付、测试和部署软件,同时大大减少了编写代码和在生产环境中运行代码的延迟。
-
而Docker Compose则是一个用于定义和运行多个容器Docker应用程序的工具。它使用YAML文件来配置应用程序的服务,用户只需通过一个命令,就可以从YAML文件配置中创建并启动所有容器服务。这使得管理、运行和扩展多容器Docker应用程序变得更加简单和高效。通过Docker Compose,用户可以定义多个容器之间的调用关系,同时启动或关闭这些容器,而无需手动一个个创建和运行。
-
总的来说,Docker主要用于单个容器的管理,而Docker Compose则主要用于定义和运行多个容器的Docker应用程序。它们共同构成了Docker生态系统的重要部分,使得应用程序的部署和管理变得更加便捷和高效。