docker container: Docker-Compose

Table of contents

一、Docker-Compose

1. Docker-Compose usage scenarios

2. Introduction to Docker-Compose

3. Docker-Compose installation and deployment

4. Precautions for writing YML files

5. Compose configures common fields

6. Common commands of Docker Compose

7. Docker Compose file structure

8. Docker Compose composes nginx image

9. Docker Compose writes tomcat image


一、Docker-Compose

1. Docker-Compose usage scenarios

We know that a separate application container can be defined using a Dockerfile template file, and if multiple containers need to be defined, service orchestration is required. There are many technical solutions for service orchestration. Today I will introduce Docker Compose, the official product of Docker.
docker swarm (manage cross-nodes)

Dockerfile allows users to manage a single application container; while Compose allows users to define a set of associated application containers (called a project) in a template (YAML format), such as a Web service container plus On the back-end database service container, etc.

2. Introduction to Docker-Compose

The Docker-Compose project is an official open source project of Docker, which is responsible for the rapid orchestration of Docker container clusters.

Docker-Compose divides the managed containers into three layers, namely project (project), service (service) and container (container). All the files in the Docker-Compose running directory (docker-compose.yml, extends file or environment variable file, etc.) form a project. If there is no special designation, the project name is the current directory name. A project can contain multiple services, and each service defines the image, parameters, and dependencies of the container running. A service can include multiple container instances. Docker-Compose does not solve the problem of load balancing, so other tools are needed to realize service discovery and load balancing, such as Consul.

The default project configuration file of Docker-Compose is docker-compose.yml. The configuration file can be customized through the environment variable COMPOSE_FILE or the -f parameter, which defines multiple dependent services and the containers that each service runs.

Using a Dockerfile template file allows users to easily define a separate application container. In work, we often encounter situations that require multiple containers to cooperate with each other to complete a certain task. For example, to implement a web project, in addition to the web service container itself, it is often necessary to add a back-end database service container, and even a load balancing container.

Compose allows users to define a set of associated application containers as a project through a single docker-compose.yml template file (YAML format).

The Docker-Compose project is written in Python and calls the API provided by the Docker service to manage the container. Therefore, as long as the operating platform supports the Docker API, Compose can be used for orchestration management on it.

3. Docker-Compose installation and deployment

#注意必须是在安装docker的基础上
curl -L https://github.com/docker/compose/releases/download/1.21.1/docker-compose-`uname -s`-`uname -m` -o /usr/local/bin/docker-compose
#下载安装包单独安装DockerCompose
chmod +x /usr/local/bin/docker-compose
#docker-compose添加执行权限
docker-compose --version
#查看docker-compose版本

4. Precautions for writing YML files

YML is a markup language that can display data serialization format intuitively, with high readability, similar to XML data, data structure is represented by indentation, continuous items are represented by minus signs, key-value pairs are separated by colons, and arrays are represented by middle enclosed in parentheses, hash is enclosed in curly braces {}

Precautions:

① clear case

②Represent hierarchical relationship through indentation

③ does not support tabs for indentation, only spaces can be used for indentation

④The number of indented spaces is not important, as long as the same level is aligned left and right, usually 2 spaces are indented at the beginning

⑤# Note

⑥Symbol characters are indented with 1 space, such as colon: comma, horizontal bar - followed by a space

⑦If it contains special characters, it will be treated as a string if it is surrounded by single quotes and double quotes. Single quotes do not recognize variables, and double quotes recognize variables.

#yml 格式
languages:       #序列的映射
  - Java
  - Golang
  - Python
websites:        #映射的映射
  cpu: 2
  memory: 1024M
  swap: 2048M
  disk: 60G 
数据结构:
对象映射: 键值对的字典
animal: pets

序列数组: 一组按次序排列的列表
- Cat
- Dog
- Goldfish

["Cat", "Dog", "Goldfish"]

布尔值
debug: true
debug: false
示例:
# yaml 格式
languages:       #序列的映射
  - Java
  - Golang
  - Python
websites:        #映射的映射
  cpu: 2
  memory: 1024M
  swap: 2048M
  disk: 60G 
键:{值}

# Json 格式
{
  languages: [
    'Java',
    'Golang',
    'Python'
  ],
  resources: {
    cpu: '2',
    memory: '1024M',
    swap: '2048M',
    disk: '60G'
  },
}

5. Compose configures common fields

field describe
build Specify the Dockerfile file name. To specify the Dockerfile file, you need to use the dockerfile tag in the child tag of the build tag to specify
dockerfile Build image context path dockerfile-nginx
context Can be a path to a dockerfile, or a url address pointing to a git repository
image specify mirror
command Execute the command, override the command executed by default after the container starts
container_name Specify the container name, because the container name is unique, if you specify a custom name, you cannot scale the specified number of containers
deploy Specify the configuration related to deployment and running services, which can only be used in Swarm mode
environment Add environment variables
networks Join the network, refer to the entries under the top-level networks
network_mode Set the network mode of the container, such as host, bridge, ...
ports Expose the container port, the same as -p, but the port cannot be lower than 60
volumes Mount a host directory or command volume to the container, and name the volume to define the volume name at the top-level volumes
volumes_from Mount volume from another service or container, optional parameters :ro and :rw, only version '2' support
hostname container hostname
sysctls Set kernel parameters inside the container
links To connect to another container, - service name[:service alias]
privileged It is used to give the container root permission, pay attention to it is not safe, true | false
restart Set the restart strategy, no, always, no-failure, unless-stopped, no, the default strategy, do not restart the container when the container exits. on-failure, when the container exits abnormally (exit status is not 0), the container will be restarted. on-failure: 3, restart the container when the container exits abnormally, up to 3 times. always, always restart the container when the container exits. unless-stopped, always restart containers when they exit, but disregard containers that were stopped when the Docker daemon started.
depends_on

When using Compose, the biggest advantage is to type fewer startup commands, but the order in which the general project containers are started is required. If you start the container directly from top to bottom, it may fail to start due to container dependencies. For example, if you start the application container without starting the database container, the application container will exit because the database cannot be found. The depends_on tag is used to solve the problem of container dependency and startup sequence. For example:

php:
  depends_on:
    - apache #Start apache first
    - mysql #Start mysql

6. Common commands of Docker Compose

Order describe
build rebuild service
ps list containers
up Create and start containers
exec Execute the command inside the container
scale Specify the number of service containers to start
top show container processes
logs View container output
down Delete containers, networks, data volumes and images
stop/start/restart stop/start/restart service

7. Docker Compose file structure

yum install -y tree
tree /opt/compose_nginx
/opt/compose_nginx/
├── docker-compose.yml #Create template script
├── nginx
│?? ├── Dockerfile #Create container script
│?? ├── nginx- 1.12.0.tar.gz #Copy source package
└── wwwroot
    └── index.html #Site page 

8. Docker Compose composes nginx image

①首先创建一个docker-compose的文件夹其中创建nginx文件夹用于nginx的镜像生成和wwwroot文件夹用于存放自定义编写的nginx主页文件
mkdir -p  /opt/docker-compose
mkdir -p  /opt/docker-compose/wwwroot
echo "<h1>this is test web</h1>" > /opt/compose_nginx/wwwroot/index.html
#创建自定义主页内容
mkdir -p  /opt/docker-compose/nginx
②然后让nginx的编译安装包放入/opt/docker-compose/nginx
③进入目录编写nginx的Dockerfile文件实现nginx镜像生成
cd  /opt/docker-compose/nginx
vim Dockerfile
#文件内容如下:
FROM centos:7
#定义基于镜像centos:7
MAINTAINER this is nginx image <nginx>
#用户信息,镜像维护用户为nginx
RUN yum -y install  pcre-devel zlib-devel gcc gcc-c++ make
#安装编译nginx需要的编译工具
RUN  useradd -M -s /sbin/nologin nginx
#创建nginx用户
ADD nginx-1.12.0.tar.gz /opt/
#将nginx包复制到镜像的/opt/目录下,docker会自动解压
WORKDIR /opt/nginx-1.12.0
#定义后面命令的执行路径是解压后的nginx包目录
RUN ./configure \
--prefix=/usr/local/nginx \
--user=nginx \
--group=nginx \
--with-http_stub_status_module && make && make install
#编译安装nginx
ENV PATH /usr/local/nginx/sbin:$PATH
#定义变量PATH
EXPOSE 80
EXPOSE 443
#指定http和https的端口
ENTRYPOINT [ "/usr/local/nginx/sbin/nginx", "-g", "daemon off;" ]
#关闭nginx在后台运行,保存退出。
④进入/opt/docker-compose目录编写docker-compose.yml文件
cd  /opt/docker-compose
vim  docker-compose.yml
#文件内容如下:
version: '3'
#docker-compose版本为3
services:
#使用services定义服务
  nginx:
#容器名为nginx
    container_name: web1
#使用dockerfile来构建镜像
    hostname: nginx-test
#主机名为nginx-test
    build:
      context: ./nginx
#指定Dockerfile文件所在位置
      dockerfile: Dockerfile
#指定文件名
    ports:
#映射端口
      - 1216:80
      - 1217:443
    networks:
      lnmp:
        ipv4_address: 172.18.0.10
#加入网络设置此容器ip
    volumes:
      - ./wwwroot:/usr/local/nginx/html
#设置数据卷挂载
networks:
#设置网络为自定义网络
  lnmp:
    driver: bridge
#网络模式
    ipam:
      config:
          - subnet: 172.18.0.0/16
#设置自定义网络的网段,设置完后保存退出
⑤编写完毕docker-compose.yml文件后进行镜像创建并启动容器
docker-compose -f docker-compose.yml up -d
#创建并启动容器,-f指定yml文件,-d表示在后台运行
docker ps -a
#可以看到容器在运行及映射端口
浏览器访问映射端口进行测试成功。

9. Docker Compose writes tomcat image

①首先创建一个tomcat的docker_compose文件夹
mkdir -p /opt/compose_tomcat/tomcat
②将tomcat编译安装的jdk包和tomcat包放入tomcat文件夹中
③进入tomcat文件夹编写Dockerfile文件
cd /opt/compose_tomcat/tomcat
vim  Dockerfile
#文件内容如下
FROM centos:7
#基于centos:7镜像
ADD jdk-8u201-linux-x64.tar.gz  /usr/local
ADD apache-tomcat-9.0.16.tar.gz  /usr/local
RUN mv /usr/local/jdk1.8.0_201  /usr/local/java  && mv /usr/local/apache-tomcat-9.0.16 /usr/local/tomcat
#将jdk和tomcat压缩包复制到镜像的/usr/local文件夹下并改名
ENV JAVA_HOME /usr/local/java
ENV JAVA_BIN /usr/local/java/bin
ENV JRE_HOME /usr/local/java/jre
ENV CLASSPATH /usr/local/java/jre/bin:/usr/local/java/lib:/usr/local/java/jre/lib/charsets.jar
ENV PATH $JAVA_BIN:/usr/local/java/jre/bin:$PATH
#定义路径变量
RUN mkdir /usr/local/tomcat/webapps/lucien \
    && echo -e "<%@ page language=\"java\" import=\"java.util.*\" pageEncoding=\"UTF-8\"%>\n<html>\n<head>\n<title>JSP test1 page</title>\n</head>\n<body>\n<% out.println(\"123456\");%>\n</body>\n</html>" > /usr/local/tomcat/webapps/lucien/index.jsp \
    && sed -i '71a <Host name="localhost" appBase="webapps" unpackWARs="true" autoDeploy="true" xmlValidation="false" xmlNamespaceAware="false">' /usr/local/tomcat/conf/server.xml \
    && sed -i '72a <Context docBase="/usr/local/tomcat/webapps/lucien" path="" reloadable="true">'  /usr/local/tomcat/conf/server.xml \
    && sed -i '73a </Context>'  /usr/local/tomcat/conf/server.xml \
    && sed -i '74a </Host>'  /usr/local/tomcat/conf/server.xml
#首先创建tomcat主页存放路径,然后添加主页内容,修改环境变量生效
EXPOSE 8080
#定义端口
ENTRYPOINT ["/usr/local/tomcat/bin/catalina.sh","run"]
#启动tomcat
④到compose_tomcat路径下创建tomcat的yml文件
cd /opt/compose_tomcat
vim docker-compose.yml
#内容如下:
version: '3'
#docker-compose版本
services:
#定义servers
  tomcat:
#容器名tomcat
    container_name: web2
    hostname: tomcat-test
#主机名tomcat-test
    build:
      context: ./tomcat
      dockerfile: Dockerfile
#镜像构建dockerfile文件夹位置及名称
    ports:
      - 1280:8080
#端口映射
    networks:
      lnmp:
        ipv4_address: 172.19.0.100
#tomcatip定义
networks:
  lnmp:
    driver: bridge
    ipam:
      config:
          - subnet: 172.19.0.0/16
#自定义网络模式和网段,保存退出
⑤创建并启动tomcat容器,注意在/opt/compose_tomcat路径下执行
docker-compose -f docker-compose.yml up -d
#创建后台启动tomcat容器
docker ps -a 
#查看容器状态及端口映射
#访问本机的1280端口查看是否成功

Guess you like

Origin blog.csdn.net/weixin_67287151/article/details/130286690