1. Introduction

1.1 What is Docker?

Docker was originally an in-house project initiated by dotCloud’s founder Solomon Hykes in France. It was open sourced in March 2013 under the Apache 2.0 license, and the main project code was maintained on GitHub.
Docker is developed using the Go language from Google.
Docker is a wrapper around the linux container that provides an easy-to-use container interface. It is the most popular Linux container solution.
The docker interface is quite simple, and users can easily create and destroy containers.
Docker packages the dependencies of the application and the program in a single file. Running this file will generate a virtual container.
The program runs in a virtual container, just like running on a real physical machine. With docker, you don’t have to worry about environmental issues.

1.2 Application Scenario

  • Automated packaging and publishing of web applications
  • Automated testing and continuous integration, release
  • Deploy and tune databases or other applications in a service-oriented environment

1.3 Docer’s concepts and advantage

# 1. More efficient use of system resources

Docker has higher utilization of system resources because the container does not require additional hardware virtualization and running a full operating system.

Whether it’s application execution speed, memory loss or file storage speed, it is more efficient than traditional virtual machine technology. Therefore, compared to virtual machine technology, a host with the same configuration can often run a larger number of applications.

# 2. Faster startup time

Traditional virtual machine technology often takes several minutes to start application services, while Docker container applications can run in the host kernel without having to start a full operating system, so they can achieve seconds or even milliseconds. Start time. Greatly saves development, testing, and deployment time.

# 3.

A common problem in the development of a consistent operating environment is the issue of environmental consistency. Due to the inconsistency of the development environment, test environment, and production environment, some bugs were not discovered during the development process.

The Docker image provides a complete runtime environment in addition to the kernel, ensuring consistency in the application’s runtime environment, so that there is no such problem as “this code is fine on my machine.”

# 4. Ongoing Delivery and Deployment

For development and operations (DevOps) personnel, the most desirable is to create or configure it once and run it anywhere.

With Docker, you can customize your application image for continuous integration, continuous delivery, and deployment. Developers can use Dockerfile for mirroring and integration testing with the Continuous Integration system.

O&M personnel can quickly deploy the image directly in the production environment, even with the Continuous Delivery / Deployment system for automatic deployment.

Moreover, using Dockerfile to make the image build transparent, not only the development team can understand the application running environment, but also facilitate the operation and maintenance team to understand the conditions required for the application to run, and help deploy the image in a better production environment.

# 5. Easier migration

Because Docker ensures consistent execution environments, application migration is made easier. Docker runs on many platforms, whether it’s physical machines, virtual machines, public clouds, private clouds, or even laptops, with consistent results.

Therefore, users can easily migrate applications running on one platform to another without worrying about changes in the operating environment that cause the application to fail.

2. Docker installation

System environment: docker supports centos7 at least and on 64-bit platform, kernel version is above 3.10

Version: Community Edition, Enterprise Edition (including some paid services)

# Installation docker 
yum install docker
 # start docker 
systemctl Start / Status docker 
 # View docker start state 
docker version

3. Docker basic commands

docker Search hello-docker   # search hello-docker mirror 
docker Search centos # search centos mirror 
docker pull hello-docker # obtain centos mirror 
docker RUN Hello-World    # running a docker image, generating a container instance (also through the front mirror id three runs) 
docker Image LS   # View all local mirroring 
docker ImagesRF Royalty Free   # view mirror docker 
docker Image rmi the Hello-docker # delete centos mirror 
docker PS   # listed container is running (if the container does not create processes are running, the container immediately stop) 
docker PS -a   # lists all running through the container recording 
docker Save CentOS> /opt/centos.tar.gz   # exported to the local image docker 
docker load </opt/centos.tar.gz   # Import local mirror image library to docker 
docker docker PS -aq` `STOP   # Stop running all containers 
docker docker RM` PS -aq`     # delete all container records 
docker docker ImagesRF Royalty Free -aq` rmi `    # deleted at a time All local mirror records

3.1 Two ways to start the container

The container is running the application, so you must first have an operating system as the basis
. 1. Create a new container based on the image and start it.

# 1. Run a docker 
docker run -d centos /bin/sh -c in the background " while true; do echo is running; sleep 1;done " 
    # -d background running container 
    # /bin/sh specifies the bash interpreter using centos 
    # -c run a shell command 
    # "to true the while; do echo is running; sleep 1; done" in linux background, running once per second print 
Docker PS   # cuvette process 
docker logs -f container id / name   # uninterrupted print container log information 
Docker CentOS sTOP   # stop container

# 2. Start a bash terminal and allow the user to interact with 
docker run --name mydocker -it centos /bin/ bash  
     # --name Define a name 
    for the container # -i Keep the container's standard input open 
    # -t Let Docker assign a pseudo terminal and bound to the container's standard input 
    # /bin/bash specifies the docker container to interact with the shell interpreter

When using docker run to create a container, the steps that Docker runs in the background are as follows:

# 1. Check if the specified image exists locally. If it does not exist, download it from the public repository.

# 2. Create and start a container with an image

# 3. Allocate a file system and hang on a read-write layer outside the read-only mirror layer

# 4. Bridge a virtual interface to the container from the bridge interface configured by the host.

# 5. Configure an ip address from the address pool to the container

# 6. Execute the user-specified application

# 7. The container is terminated after execution

2. Restart a stopped (contained) container

[root@localhost ~] # docker ps -a # First query record 
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
Ee92fcf6f32d centos               " /bin/bash "               4 days ago Exited (137) 3 days ago kickass_raman

[root@localhost ~] # docker start ee9 # Restart this container 
ee9

[root@localhost ~] # docker exec -it ee9 /bin/bash # Enter the container interactive interface 
[root@ee92fcf6f32d /] #    # Note the user name, has become the container user name

3.2 Submit to create a custom image

# 1. We enter the interactive centos container and find that there is no vim command 
    docker run - it centos
 # 2. In the current container, install a vim 
    yum install - y vim
 # 3. After installing vim, exit exits the container 
    exit
 # 4. View the container record of the vim just installed 
    docker container ls - a
 # 5. Submit this container, create a new image 
    docker commit 059fdea031ba chaoyu/centos- vim
 # 6. View the image file 
    docker images

3.3 external access container

Network applications can be run in the container, but for external access to these applications, port mapping can be specified with the -p or -P parameters.

Docker run -d -P training/ webapp python app.py
   # -P parameter will randomly map the port to the open network port of the container

# Check the map of Port 
Docker PS - L
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
Training cfd632821d7a / the webapp      " Python app.py "      21 is seconds The seconds The 0.0.0.0:32768->5000/ ago Member 20 is Up TCP brave_fermi
 # host ip: 5000 32768 Port Mapping container

# View container logs 
Docker logs -f cfd   # # uninterrupted display log

# can also specify the mapping port 
docker run -d -p 9000:5000 training/webapp python app.py with the -p parameter

Open the browser to access the server’s 9000 port, the content shows Hello world! Indicates normal startup

(If the access fails, check your firewall and the security group of the cloud server)

4. Custom image with dockerfile

Mirroring is the basis of the container, and each time you execute docker run, you specify which image to use as the basis for the container to run. Our previous examples all used images from the docker hub. Direct use of these images can only meet certain requirements. When the image does not meet our needs, we have to customize these images.

# Customized image is to customize each layer of the added configuration file. If you can edit, install, build, and manipulate the commands for each layer, write them to a script, and use scripts to build and customize the image. This script is the dockerfile. 
# Dockerfile is a text file that contains a strip of instructions (Instruction), each instruction builds a layer, so the content of each instruction is to describe how the layer should be constructed.
Scratch the FROM # production base image base image, try to use the official image as a base image 
the FROM CentOS # using the base image 
the FROM Ubuntu: 14.04 # base image with the tag 

LABEL Version "1.0" = # container meta-information, help, Metadata, Note code similar to 
the LABEL = Maintainer "yc_uuu@163.com "
 
# for complex RUN command, to avoid useless layered, multiple commands with a backslash line feed, a synthesis order! 
RUN yum update && yum install - y vim \
    Python -dev # backslash wrap 
RUN / bin / bash -c " Source $ the HOME / .bashrc; echo $ the HOME" 

WORKDIR / root # equivalent of linux cd command to change directories, try to use absolute paths! ! ! Do not cd RUN 
WORKDIR / the Test # If you do not automatically create 
WORKDIR demo # re-entering the demo folder 
RUN pwd      # print the results should be / the Test / demo 

the ADD and COPY
Hello the ADD /   # to add local files to the mirror, it's hello local executable files are copied to the mirror / directory 
the ADD test.tar.gz /   # added to the root directory and extract 

WORKDIR / root
Hello test ADD /   # enter / root / hello executable commands added to the test directory, that is, / root / test / hello an absolute path 
COPY hello test /   # is equivalent to the above-described effects ADD

ADD and COPY
   - Use the COPY command first
     - ADD has the decompression function in addition to the COPY function
Add remote files / directories using curl or wget

ENV # environment variable, using as much as possible to increase the maintainability ENV 
ENV MYSQL_VERSION 5.6 # provided a constant mysql 
RUN yum install -y mysql-server = "$ {MYSQL_VERSION}"
VOLUME and EXPOSE
Storage and network

RUN and CMD and ENTRYPOINT
RUN: Execute the command and create a new Image Layer
CMD: Set the default commands and parameters to be executed after the container is started.
ENTRYPOINT: Set the command to run when the container starts

Shell format and Exec format
RUN yum install - y vim
CMD echo "hello docker"
ENTRYPOINT echo “hello docker”

Exec format
RUN ["apt -get","install","- y","vim"]
CMD [" /bin/ echo","hello docker"]
ENTRYPOINT [" /bin/ echo","hello docker"]


Running the command through the shell format will read the $name command, and the exec format will only execute one command instead of the shell command.
Cat Dockerfile
    FROM centos
    ENV name Docker
    EntryPoint [ " / bin / echo", "the Hello $ name"] # This is just the echo command execution, can not read the shell variables 
    EntryPoint [ "/ bin / bash", "- c", "echo the Hello $ name " ]

CMD
The default command to execute when the container starts
If the docker run specifies another command (docker run -it [image] /bin/ bash ), the CMD command is ignored.
If multiple CMDs are defined, only the last one is executed

ENTRYPOINT
Let the container run as an application or service
Will not be ignored, will definitely execute
Best practice: write a shell script as an entrypoint
COPY docker -entrypoint.sh /usr/local/ bin
ENTRYPOINT ["docker - entrypoint.sh]
EXPOSE 27017
CMD ["mongod"]

[root@master home] # more Dockerfile 
FROm centos
ENV name Docker
# CMD ["/bin/bash","-c","echo hello $name"] 
ENTRYPOINT [ " /bin/bash " , " -c " , " echo hello $name"]

5.0 Posted to the repository

5.1 Docker hub has a mirror release

Docker provides a repository docker hub similar to github.

Official website (registration required)

# After registering docker id, login dockerhub in linux 
    docker login

# Note To ensure that the account name tag image, if the mirror name does not need to change it Tag 
    Docker Tag chaoyu / CentOS-vim peng104 / centos- vim
     # syntax is: docker tag repository name peng104 / repository name

# docker image to dockerhub 
    docker push peng104/centps-cmd- exec :latest

# dockerhubCheck the image 
# first delete the local image, then test the download pull image file 
    docker pull peng104/centos-entrypoint- exec

5.2 Private repository

The docker hub is public, others can be downloaded, not safe, so you can also use the private repository provided by the docker registry.

# 1. Download a docker official private repository image 
    docker pull registry
 # 2. Run a docker private container repository 
docker run -d -p 5000:5000 -v /opt/data/registry:/var/lib/ registry registry
     - d background Run 
     - p port map host 5000: 5000 -v data volume in the container
     mount host /opt/data/registry :/var/lib/ registry
    Registry image name
    /var/lib/ registry Placing private repository locations
 # Docker does not allow non-HTTPS push mirrors by default. We can cancel this restriction by Docker configuration options 
# 3. Modify the docker's configuration file, so he supports http way to upload private Mirror 
    vim / etc / docker / daemon.json 
     # write the following 
    {
         " Registry-Mirrors " : [ " http://f1361db2.m.daocloud.io " ],
         " insecure-registries " :[ " 192.168.11.37:5000 " ]
    }
# 4. docker service profile modification 
    Vim / lib / systemd / System / docker.service
 # found [-Service] This block code area, write the following parameters 
    [-Service]
    EnvironmentFile = - / etc / docker / daemon.json
 # 5. The reload docker service 
    systemctl daemon- reload
 # 6. The Restart Service docker 
    systemctl the restart docker
     # Note: Restart docker service, all the containers are hung

# 7. Modify the tag labeled local mirror of his own private repository to push 
    Docker tag docker.io/peng104/hello-world-docker 192.168.11.37:5000/peng- the Hello
     # browser to access http://192.168.119.10: 5000/v2/_catalogView repository 
# 8. Download the mirror of the private repository 
    docker pull 192.168.11.37:5000/peng-hello

6.0 Example Demo

Write a dockerfile, build your own image, and run the flask program.

Make sure app.py and dockerfile are in the same directory!

# 1. Prepare the app.py flask program 
    [root@localhost ~] # cat app.py 
    from flask import Flask
    App =Flask( __name__ )
    @app.route( ' / ' )
     def hello():
         return  " hello docker " 
    if  __name__ == " __main__ " :
        App.run(host = ' 0.0.0.0 ' ,port=8080 )
    [root@master home] # ls 
    app.py Dockerfile

# 2. Write dockerfile 
    [root@localhost ~] # cat Dockerfile 
    FROM python:2.7 
    LABEL maintainer = " Warm and new "
    RUN pip install flask
    COPY app.py /app/ 
    WORKDIR / app
    EXPOSE 8080 
    CMD [ " python " , " app.py " ]

# 3. Build the image image, find the Dockerfile in the current directory, and start building the 
    docker build -t peng104/flask-hello- docker .

# 4. View the created images 
    docker image ls

# 5. Start the flask-hello-docker container and map a port for external access to 
    docker run -d -p 8080:8080 peng104/flask-hello- docker

# 6. Check the running container 
    docker container ls

# 7. Push this image to the private repository 
    docker tag peng104/flask-hello-docker 192.168.11.37:5000/peng- flask web
    Docker push 192.168.11.37:5000/peng-flaskweb