First, the use of common containers

1. The Mysql container

Pull the mirror

#Pull MySQL 5.7 image
docker pull centos/mysql-57-centos7
Copy the code

Create a container

#Create the mysql5.7 containerDocker run -di --name=mysql5.7 -p 3306:3306 -e MYSQL_ROOT_PASSWORD=root centos/ mysql-57-centos7Copy the code

-p indicates port mapping in the format of host port mapping: container running port -e indicates adding environment variables MYSQL_ROOT_PASSWORD is the remote login password of user root (the password is empty if user root is used in container).

-d enables the daemon container

-I indicates to start the container

MySQL > create MySQL

#Pull MySQL 5.7 imageDocker exec it mysql5.7 /bin/bash
#Log in to mysql in the container
mysql -u root -p
Copy the code

2. The Tomcat container

Pull the mirror

#Pull the Tomcat image
docker pull tomcat
Copy the code

Create a container

#Create a Tomcat container; And mount the Webapps directory
docker run -di --name=mytomcat -p 8080:8080 -v /usr/local/tomcat/webapps:/usr/local/tomcat/webapps tomcat

#WARNING: IPv4 forwarding is disabled. Networking will not work.
#Do the following
#1. Edit sysctl.conf
vi /etc/sysctl.conf
#2. Add to the end of the file opened above
net.ipv4.ip_forward=1
#3. Restart the network
systemctl restart network
Copy the code

3. The Nginx container

Pull the mirror

#Pull the Nginx image
docker pull nginx
Copy the code

Create a container

#Create an nginx container
docker run -di --name=mynginx -p 80:80  nginx
Copy the code

4. Redis container

Pull the mirror

#Pull the Redis image
docker pull redis
Copy the code

Create a container

#Create a Redis container
docker run -di --name=myredis -p 6379:6379 redis
Copy the code

Container operation

#Enter the Redis container
docker exec -it myredis /bin/bash

#Go to the Redis installation directory
cd /usr/local/bin

#Connect the redis
./redis-cli
Copy the code

Remote connection container

5. The rabbitmq container

  1. Download the RabbitMQ image

docker pull rabbitmq:management

  1. runsudo docker run -di -p 15672:15672 -p 4369:4369 -p 5672:5672 --name myrabitmq rabbitmq:management‘docker run-di -p 15672:15672:p 5672:5672 –name myrabitMQ container ID ‘
5672: Application access port. 15672: Console Web port number

Docker Compose 5. Docker Compose

1. Introduction and Composition

Introduction to the

The Compose project is Docker’s official open source project, which is responsible for the rapid choreography of Docker container clusters.

Docker is a tool for defining and running multi-container Docker applications. With Compose, you can configure your own services from a YMAL file, and then create and run all the services from the configuration file with a single command.

composition

Docker-compose manages containers in three layers, namely project, Service and Container.

Docker-compose all files in the docker-compose running directory (docker-compose. Yml, extends file, environment variable file, etc.) form a process. If no specific project name is specified, it is the current directory name. A project can contain multiple services, each of which defines the images, parameters, and dependencies that the container runs on.

Multiple container instances can be included in a service.

  • Service: A container for an application that can actually contain several instances of the container running the same image. Each service has its own name, which image it uses, which data volumes it mounts, which network it belongs to, which other services it depends on, and so on.
  • Project: A completion business unit consisting of a set of associated application containers, defined in docker-comemess.yml. That is, one of Compose’s configuration files can be parsed into a project. Compose analyzes the specified configuration file to figure out all the container management and deployment operations that the configuration file requires.

Docker-compose’s project configuration file defaults to docker-comemage. yml, which can be customized by using the environment variable COMPOSE_FILE or -f parameter. The configuration file defines multiple dependent services and the container in which each service runs.

Using a Dockerfile template allows users to easily define a separate application container. In the work, it is common to encounter the need for multiple containers to cooperate to complete a task.

For example, to deploy a Web project, you often need to add a back-end database service container, or even a load balancing container, in addition to a Web service container.

2. Installation and uninstallation

The curl -l https://github.com/docker/compose/releases/download/1.24.1/docker-compose- ` ` uname - s - ` uname -m ` - o /usr/local/bin/docker-compose
#Example Set the executable permission of a file
chmod +x /usr/local/bin/docker-compose

#Viewing version Information
docker-compose -version

#Uninstall the docker - compose
rm -f /usr/local/bin/docker-compose
Copy the code

3. Common commands

SUBCOMMAND explain
build Build or rebuild the service
help Command assistance
kill Kill the container
logs Displays the output of the container
port Prints the bound open port
ps According to the container
pull Pull the service mirror
restart Restart the service
rm Delete stopped containers
run Run a one-time command
scale Set the number of containers for the service
start Open the service
stop Stop the service
up Create and start the container service (-d: Background start)

Template file

The template file is the core of Compose and involves many directive keywords, most of which have similar meanings to docker run parameters.

The default template file name is docker-comemage. yml in YAML format. For example, the Compose template file:

version: "2"
services:
  web:
    images: nginx
    ports:
      - "8080:80"
    volumes:
      - /usr/local/abc:/usr/local/cba
#volumes:

#networks:
Copy the code

Docker Compose template file is divided into three areas, as follows:

  • Services A service under which you can define the services required by an application. Each service has its own name, image to use, data volume to mount, network to which it belongs, other services to which it depends, and so on.
  • Volumes data volumes that you can define (name, etc.) and then mount to different services.
  • Networks Indicates the application network, under which you can define the application name, network type, and so on.

5. Application of Compose

Creating a template File

#Creating a folder
mkdir -p /usr/local/mycompose

#Enter folder
cd /usr/local/mycompose

#Create docker-comemess. yml file; The following
vi docker-compose.yml
Copy the code

Writing a template file

version: '3'
services:
  redis1:
    image: redis
    ports:
      - "6379:6379"
    container_name: "redis1"
    networks: 
      - dev
  mysql1:
    image: centos/mysql-57-centos7
    environment:
      MYSQL_ROOT_PASSWORD: "root"
    ports: 
      - "3306:3306"
    container_name: "mysql1"
    networks: 
      - dev
  web1:
    image: tomcat
    ports: 
      - "9090:8080"
    container_name: "web1"
    networks: 
      - dev
      - pro
networks:
  dev:
    driver: bridge
  pro:
    driver: bridge
Copy the code

Start the service

cd /usr/local/mycompose
#Up the command line
docker-compose up

#To start the system in the background, run the -d command
docker-compose up -d

#If you want to stop
docker-compose stop
Copy the code

Two, construct own mirror image

There are two ways to construct your mirror image:

Docker commit command Docker build command and Dockerfile fileCopy the code

Note: when we say to construct our own mirror image, we do not mean to make a mirror image by ourselves, but to package it into a mirror image on the existing basis.

1. Docker commit command

Take installing a Redis as an example. Start by finding a simple mirror image

centos    7                   5182e96772bf        5 months ago        200MB
Copy the code

There is a mirror image of Centos7 in there, this is an operating system, nothing else.

Create a container redis01

[root@localhost ~]# docker run -it --name=redis01 -p 6379:6379 centos:7 /bin/bash
Copy the code

Enter the container installation environment (you don’t need to re-install the environment if it already exists) :

yum install gcc-c++

yum install ruby

yum -y install gcc automake autoconf libtool make
Copy the code

Upload the source file, install Redis, and start Redis

Testing:

Jedis jedis = new Jedis("192.168.25.134",7000);
System.out.println(jedis.ping());
jedis.close();
Copy the code

Save the container as a mirror image

[root@localhost ~]# docker commit redis01 myredis
Copy the code

Create a container with the new mirror image

[root@localhost ~]# docker run -di --name=redis02 -p 6379:6379 myredis
Copy the code

2. Dockerfile file

Docker can automatically build images from the contents of dockerfiles. Dockerfile is a text file that contains all the commands to create an image. Using the docker build command, you can build an image according to the content of the Dockerfile. Before introducing how to build, we will introduce the basic syntax structure of Dockerfile.

For example, create a Dockerfile file with the following contents.

FROM centos:7
MAINTAINER zl

RUN yum install gcc-c++ -y -y -y -y
RUN yum install ruby -y -y -y -y

RUN mkdir /opt/redis/
ADD redis /opt/redis

EXPOSE 6379

Copy the code

FROM centos:7 indicates that this mirror is based on the centos:7 mirror.

MAINTAINER ZL Description This: this dockerfile file is created by a MAINTAINER ZL.

Yum install gcc-c++ -y -y -y RUN yum install gcc-C ++ -y -y RUN yum install gcc-C ++ -y -y RUN yum install gcc-C ++ -y -y

RUN yum install ruby-y-y-y RUN yum install ruby-y-y-y

RUN mkdir /opt/redis/ Create a directory in the docker container /opt/redis/ ADD redis/ opt/redis upload the reids file (folder) on the local machine to the /opt/redis directory in the docker container.

The EXPOSE 6379 container exposes the port 6379

3. Dockerfile instructions

FROM

Usage:

FROM <image>
Copy the code
  • FROMSpecifies the base source image to build the image. If there is no local image, it will automatically pull the image from the Docker public library.
  • FROMMust be the first directive in a non-comment line of a Dockerfile, i.e. a Dockerfile fromFROMStatement start.
  • ifFROMStatement does not specify a mirror labellatestThe label.

MAINTAINER

Usage:

MAINTAINER <name>
Copy the code

Specify the user to create the image

RUN

Each RUN command executes the specified command based on the current image, and can be used in two ways

  • RUN (the command is run in a shell – /bin/sh -c – shell form)
  • RUN [” executable “, “param1”, “param2”] (exec form)

The RUN command will execute the specified command based on the current image and submit it as a new image. Subsequent runs are based on the image submitted after the previous RUN. Images are hierarchical and can be created from any historical submission point of an image, similar to source control.

The exec method is parsed to a JSON array, so you must use double quotes instead of single quotes. Exec does not invoke a command shell, so it does not inherit corresponding variables, such as:

RUN [ "echo", "$HOME" ]
Copy the code

This approach will not reach the output HOME variable, the correct approach should be like this

RUN [ "sh", "-c", "echo", "$HOME" ]
Copy the code

EXPOSE

EXPOSE <port> [<port>...]
Copy the code

Tell the Docker server container to map the local port, need to use the -p or -p option when Docker run.

ENV

ENV <key> <value> # Only one variable ENV <key>=<value> # Allow multiple variables to be set at onceCopy the code

Specifies a link variable that will be used by subsequent RUN directives and retained when the container runs.

Example:

ENV myName="John Doe" myDog=Rex\ The\ Dog \
    myCat=fluffy
Copy the code

Is equivalent to

ENV myName John Doe
ENV myDog Rex The Dog
ENV myCat fluffy
Copy the code

The use variable is used as $myName.

ADD

ADD <src>... <dest>
Copy the code

ADD copies the localhost file, directory, or remote file URLS from and adds them to the container specified path.

< SRC > Supports regular fuzzy matching by GO. For details, see GO Filepath.Match

ADD hom* /mydir/ # adds all files starting with "hom" ADD hom? .txt /mydir/ # ? is replaced with any single characterCopy the code
  • <dest>The path must be an absolute path if<dest>If no, the system automatically creates the corresponding directory
  • <src>The path must be relative to the path where the Dockerfile resides, or it can be a network address.
  • <src>If it is a directory, only the contents of the directory will be copied, but the directory itself will not be copied

COPY

COPY <src>... <dest>
Copy the code

COPY Copies new files or directories from being added to the specified path in the container. The only difference is that you cannot specify remote file URLS.

WORKDIR

WORKDIR /path/to/workdir
Copy the code

Configure the working directory for subsequent RUN, CMD, and ENTRYPOINT directives. Multiple WORKDIR directives can be used, and subsequent commands, if their arguments are relative paths, will be based on the path specified by the previous command.

WORKDIR /a
WORKDIR b
WORKDIR c
RUN pwd

Copy the code

The final path is/A /b/c.

The WORKDIR directive can call an environment variable after ENV sets the variable:

ENV DIRPATH /path
WORKDIR $DIRPATH/$DIRNAME
Copy the code

The final path is /path/$DIRNAME.

VOLUME

VOLUME ["/data"]
Copy the code

Create a mount point that can be mounted from localhost or other containers, more on that later. Directory mounting.

USER

USER daemon
Copy the code

Specify the user name or UID used to RUN the container, as well as the subsequent RUN, CMD, and ENTRYPOINT. Finally do not add, add after the container to run to add the user name.

ONBUILD

ONBUILD [INSTRUCTION]
Copy the code

Configure the operation instructions to perform when the created image is used as the base image for other newly created images.

For example, Dockerfile creates the image image-a with the following content:

[...].  ONBUILD ADD . /app/src ONBUILD RUN /usr/local/bin/python-build --dir /app/src [...]Copy the code

If A new image is created based on image-a and the new Dockerfile uses FROM image-a to specify the base image, the ONBUILD directive will be executed automatically, which is equivalent to adding two directives later.

# Automatically run the following
ADD . /app/src
RUN /usr/local/bin/python-build --dir /app/src
Copy the code

It is recommended to label images using the ONBUILD directive, such as Ruby :1.9-onbuild.

docker build

$ docker build --help Usage: docker build [OPTIONS] PATH | URL | - Build a new image from the source code at PATH --force-rm=false Always remove Intermediate containers, even after unsuccessful builds --no-cache=false Do not use cache when building the image # --quiet=false Suppress the verbose output generated by the containers --rm=true Remove intermediate containers after a Remove the transition layer container after the build is successful. --tag="" Repository name (and optionally a tag) to be applied to the resulting image in case of successCopy the code

Such as:

docker build -t=abc:001 .
Copy the code

Docker build Specifies the directory where the Dockerfile resides

-t indicates the name and label of the mirror. ABC is the name and 001 is the label.

Find Dockerfile in the current directory.

Three, mirror image import and export

1. Image backup

We can save the image as a tar file by using the following command

docker  save -o mynginx.tar mynginx_i
Copy the code

2. Restore and migrate the image

First we delete the mynginx_img image and then execute this command to restore it

docker load -i mynginx.tar
Copy the code

-i Indicates the input file

After the command is executed, view the image again. The image is restored