文章目录
Docker Compose学习
一、Docker Compose
-
介绍
- 为什么要用Docker Compose?
- 当Docker里的镜像容器很少时,我们手动build、run等操作是很方便的;
- 但是一旦容器数量变的过多 ,手动操作就会变的很繁琐,于是Docker Compose应运而生,可以很好的解决这个问题。
- 什么是Docker Compose?
- Compose是用于定义和运行多容器Docker应用程序的工具;
- 通过Compose,您可以使用YAML文件来配置应用程序的服务。然后,使用一个命令,就可以从配置中创建并启动所有服务;
- Compose是Docker官方的开源项目,需要额外安装;
- Docker里的概念
- Service:容器,单个容器;
- Project:一组关联的Service,一组容器;
- Docker Compose的使用步骤
- 使用定义您的应用环境,
Dockerfile
以便可以在任何地方复制; - 定义组成应用程序的服务,
docker-compose.yml
以便它们可以在隔离的环境中一起运行; - 运行
docker-compose up
and Compose启动并运行您的整个应用程序;
- 使用定义您的应用环境,
- 为什么要用Docker Compose?
-
安装
-
下载docker-compose文件到/usr/local/bin/目录下
# 国外镜像,速度较慢 sudo curl -L "https://github.com/docker/compose/releases/download/1.27.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose # 国内镜像 sudo curl -L "https://get.daocloud.io/docker/compose/releases/download/1.27.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
-
授予docker-compose文件操作权限
sudo chmod +x /usr/local/bin/docker-compose
-
查看版本(看到版本信息则表明安装成功)
docker-compose version
-
-
Docker Compose初体验
-
在选中目录下创建
项目目录
mkdir composetest cd 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)
-
在
项目目录
下创建requirements.txt文件flask redis
-
-
在
项目目录
下创建Dockerfile文件# 从Python 3.7映像开始构建映像。 FROM python:3.7-alpine # 将工作目录设置为/code。 WORKDIR /code # 设置flask命令使用的环境变量。 ENV FLASK_APP app.py # 安装gcc和其他依赖项 ENV FLASK_RUN_HOST 0.0.0.0 # 复制requirements.txt并安装Python依赖项。 RUN apk add --no-cache gcc musl-dev linux-headers # 向图像添加元数据以描述容器正在侦听端口5000 COPY requirements.txt requirements.txt # 将.项目中的当前目录复制到.映像中的工作目录。 RUN pip install -r requirements.txt # 将容器的默认命令设置为flask run。 EXPOSE 5000 COPY . . CMD ["python", "app.py"]
-
在
项目目录
下创建docker-compose.yml文件version: '3' # 定义了两个服务:web和redis services: # 该web服务使用从Dockerfile当前目录中构建的映像。然后,它将容器和主机绑定到暴露的端口5000 web: build: . ports: - "3333:5000" # 该redis服务使用 从Docker Hub注册表中提取的公共Redis映像 redis: image: "redis:alpine"
-
在
项目目录
下使用命令docker-compose up
-
运行完上述指令,查看镜像和容器详细信息
# 多出了两个容器 [root@lazyr composetest]# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 321b14fcd5d9 redis:alpine "docker-entrypoint.s…" 6 minutes ago Exited (0) 8 seconds ago composetest_redis_1 f70520d0cde4 composetest_web "python app.py" 6 minutes ago Exited (0) About a minute ago composetest_web_1 # 多出了一个Docker网络 [root@lazyr composetest]# docker network ls NETWORK ID NAME DRIVER SCOPE 20d2658b05df bridge bridge local # 多出的Docker网络 2ee7cb2cbff7 composetest_default bridge local c00558472d7d host host local
- 多出的容器名:composetest_redis_1、composetest_web_1
- 多出的Docker网络:使用docker-compose.yaml文件创建的一系列容器,都是统一在docker-compose维护的一个网络下
-
强行停止指令
docker-compose stop
-
指令详解
-
详细用法
Usage: docker-compose [-f <arg>...] [options] [--] [COMMAND] [ARGS...] docker-compose -h|--help Options: -f, --file FILE Specify an alternate compose file (default: docker-compose.yml) -p, --project-name NAME Specify an alternate project name (default: directory name) -c, --context NAME Specify a context name --verbose Show more output --log-level LEVEL Set log level (DEBUG, INFO, WARNING, ERROR, CRITICAL) --no-ansi Do not print ANSI control characters -v, --version Print version and exit -H, --host HOST Daemon socket to connect to --tls Use TLS; implied by --tlsverify --tlscacert CA_PATH Trust certs signed only by this CA --tlscert CLIENT_CERT_PATH Path to TLS certificate file --tlskey TLS_KEY_PATH Path to TLS key file --tlsverify Use TLS and verify the remote --skip-hostname-check Don't check the daemon's hostname against the name specified in the client certificate --project-directory PATH Specify an alternate working directory (default: the path of the Compose file) --compatibility If set, Compose will attempt to convert keys in v3 files to their non-Swarm equivalent (DEPRECATED) --env-file PATH Specify an alternate environment file Commands: build Build or rebuild services config Validate and view the Compose file create Create services down Stop and remove containers, networks, images, and volumes events Receive real time events from containers exec Execute a command in a running container help Get help on a command images List images kill Kill containers logs View output from containers 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 services rm Remove stopped containers run Run a one-off command scale Set number of containers for a service start Start services stop Stop services top Display the running processes unpause Unpause services up Create and start containers version Show version information and quit
-
-
docker-compose.yaml
-
语法核心结构
# 大结构就三层 # 版本 version: 'x.x' # 服务 services: serviceName1: #相关配置... serviceName2: #相关配置... # 其他配置(挂载卷、网络、配置) vloume: networks: config: # ....
-
二、部署博客(实战)
-
搭建博客
-
创建博客根目录
[root@lazyr wjr]# mkdir myBlog [root@lazyr wjr]# cd myBlog [root@lazyr myBlog]# pwd /home/wjr/myBlog
-
创建docker-compose.yml
[root@lazyr myBlog]vim docker-compose.yml
version: '3.3' services: db: image: mysql:5.7 volumes: - db_data:/var/lib/mysql restart: always environment: MYSQL_ROOT_PASSWORD: xxx MYSQL_DATABASE: xxx MYSQL_USER: xxx MYSQL_PASSWORD: xxx wordpress: depends_on: - db image: wordpress:latest ports: - "3456:80" restart: always environment: WORDPRESS_DB_HOST: db:3306 WORDPRESS_DB_USER: xxx WORDPRESS_DB_PASSWORD: xxx WORDPRESS_DB_NAME: xxx volumes: db_data: {}
-
后台启动
docker-compose up -d
-
查看博客网站
-
三、部署SpringBoot项目
-
创建项目
-
创建SpringBoot项目docker-compose-project,勾选如下依赖
-
项目结构
-
CountController.java
@RestController public class CountContoller { @Autowired private RedisTemplate redisTemplate; @RequestMapping("/hello") public String count(){ Long views = redisTemplate.opsForValue().increment("views"); return "<h1 align='center'>该网站访问了"+views+"次</h1>"; } }
-
application.yaml
server: port: 3344 spring: redis: host: redis port: 6379
-
Dockerfile
FROM java:8 COPY *.jar /app.jar CMD ["--server.port=3344"] EXPOSE 3344 ENTRYPOINT ["java","-jar","/app.jar"]
-
docker-compose.yml
version: '3.8' services: lazyrweb: build: . image: lazyrweb depends_on: - redis ports: - "3344:3344" redis: image: "library/redis:alpine"
-
-
打包项目
-
把项目jar包、Dockerfile、docker-compose.yml文件上传到服务器的项目路径下
[root@lazyr docker-compose-project]# pwd /home/wjr/docker-compose-project [root@lazyr docker-compose-project]# ls docker-compose-project-0.0.1-SNAPSHOT.jar docker-compose.yml Dockerfile
-
启动项目
Building lazyrweb Step 1/5 : FROM java:8 ---> d23bdf5b1b1b Step 2/5 : COPY *.jar /app.jar ---> 5118d25601f2 Step 3/5 : CMD ["--server.port=8080"] ---> Running in 819e1d81745e Removing intermediate container 819e1d81745e ---> b1be42ff6d0c Step 4/5 : EXPOSE 8080 ---> Running in a4210ef5f109 Removing intermediate container a4210ef5f109 ---> a285efe4b6bf Step 5/5 : ENTRYPOINT ["java","-jar","app.jar"] ---> Running in 659dd9f091d2 Removing intermediate container 659dd9f091d2 ---> 991bec8acdc8 Successfully built 991bec8acdc8 Successfully tagged lazyrweb:latest Starting docker-compose-project_redis_1 ... done Recreating docker-compose-project_lazyrweb_1 ... done Attaching to docker-compose-project_redis_1, docker-compose-project_lazyrweb_1 redis_1 | 1:C 17 Sep 2020 08:08:53.554 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo redis_1 | 1:C 17 Sep 2020 08:08:53.554 # Redis version=6.0.8, bits=64, commit=00000000, modified=0, pid=1, just started redis_1 | 1:C 17 Sep 2020 08:08:53.554 # 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 Sep 2020 08:08:53.555 * Running mode=standalone, port=6379. redis_1 | 1:M 17 Sep 2020 08:08:53.555 # 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 Sep 2020 08:08:53.555 # Server initialized redis_1 | 1:M 17 Sep 2020 08:08:53.555 # 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 Sep 2020 08:08:53.555 # WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command 'echo madvise > /sys/kernel/mm/transparent_hugepage/enabled' as root, and add it to your /etc/rc.local in order to retain the setting after a reboot. Redis must be restarted after THP is disabled (set to 'madvise' or 'never'). redis_1 | 1:M 17 Sep 2020 08:08:53.556 * Loading RDB produced by version 6.0.8 redis_1 | 1:M 17 Sep 2020 08:08:53.556 * RDB age 112 seconds redis_1 | 1:M 17 Sep 2020 08:08:53.556 * RDB memory usage when created 0.76 Mb redis_1 | 1:M 17 Sep 2020 08:08:53.556 * DB loaded from disk: 0.000 seconds redis_1 | 1:M 17 Sep 2020 08:08:53.556 * Ready to accept connections lazyrweb_1 | lazyrweb_1 | . ____ _ __ _ _ lazyrweb_1 | /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ lazyrweb_1 | ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ lazyrweb_1 | \\/ ___)| |_)| | | | | || (_| | ) ) ) ) lazyrweb_1 | ' |____| .__|_| |_|_| |_\__, | / / / / lazyrweb_1 | =========|_|==============|___/=/_/_/_/ lazyrweb_1 | :: Spring Boot :: (v2.3.3.RELEASE) lazyrweb_1 | lazyrweb_1 | 2020-09-17 08:08:58.590 INFO 1 --- [ main] com.wjr.DockerComposeProjectApplication : Starting DockerComposeProjectApplication v0.0.1-SNAPSHOT on ee1593a34809 with PID 1 (/app.jar started by root in /) lazyrweb_1 | 2020-09-17 08:08:58.597 INFO 1 --- [ main] com.wjr.DockerComposeProjectApplication : No active profile set, falling back to default profiles: default lazyrweb_1 | 2020-09-17 08:09:00.475 INFO 1 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode! lazyrweb_1 | 2020-09-17 08:09:00.479 INFO 1 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data Redis repositories in DEFAULT mode. lazyrweb_1 | 2020-09-17 08:09:00.547 INFO 1 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 39ms. Found 0 Redis repository interfaces. lazyrweb_1 | 2020-09-17 08:09:02.106 INFO 1 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http) lazyrweb_1 | 2020-09-17 08:09:02.158 INFO 1 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat] lazyrweb_1 | 2020-09-17 08:09:02.158 INFO 1 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.37] lazyrweb_1 | 2020-09-17 08:09:02.364 INFO 1 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext lazyrweb_1 | 2020-09-17 08:09:02.364 INFO 1 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 3557 ms lazyrweb_1 | 2020-09-17 08:09:04.654 INFO 1 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor' lazyrweb_1 | 2020-09-17 08:09:05.537 INFO 1 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path '' lazyrweb_1 | 2020-09-17 08:09:05.570 INFO 1 --- [ main] com.wjr.DockerComposeProjectApplication : Started DockerComposeProjectApplication in 8.359 seconds (JVM running for 11.007)
-
访问网站
-