Two hour introduction to docker


1. Introduction

1.1 what is docker

Docker was originally an internal project initiated by Solomon hykes, founder of dotcloud company, during his stay in France. In March 2013, it was open source under the Apache 2.0 license agreement, and the main project code was maintained on GitHub.

Docker is developed and implemented with go language launched by Google.

Docker is a kind of encapsulation of Linux container, which provides a simple and easy-to-use container interface. It is the most popular Linux container solution.

The interface of docker is quite simple. Users can easily create and destroy containers.

Docker packages the application and its dependencies in one file. Running this file generates 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 the environment.

1.2 application scenarios

Automatic packaging and publishing of web applications

Automated testing and continuous integration, release

Deploying and adjusting databases or other applications in a service-oriented environment

1.3 differences

1. Physical machine


2. Virtual machine


3. Docker container


1.4 three concepts and advantages of docker

Advantages of docker container

1. More efficient use of system resources

Because the container does not need hardware virtualization and running a complete operating system, docker has higher utilization of system resources.

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

2. Faster startup time

Traditional virtual machine technology usually takes several minutes to start application services, while docker container applications, because they run directly in the host kernel, do not need to start the complete operating system, so they can achieve second level, or even millisecond level startup time. It greatly saves the time of development, testing and deployment.

3. Consistent operating environment

A common problem in the development process is environment consistency. Due to the inconsistency of development environment, test environment and production environment, some bugs are not found in the development process.

The docker image provides a complete runtime environment in addition to the kernel, ensuring the consistency of the application runtime environment, so that there will be no such problems as “this code is OK on my machine”.

4. Continuous delivery and deployment

For Devops personnel, the most desirable thing is to create or configure it once, and it can run normally anywhere.

Docker can realize continuous integration, continuous delivery and deployment by customizing application image. Developers can build the image through dockerfile and conduct integration test with continuous integration system, while operation and maintenance personnel can quickly deploy the image directly in the production environment, or even automatically deploy it with continuous delivery / deployment system.

Moreover, using dockerfile to make the image construction transparent not only enables the development team to understand the application running environment, but also facilitates the operation and maintenance team to understand the conditions required for the application running, so as to help deploy the image in a better production environment.

5. Easier migration

Because docker ensures the consistency of execution environment, it makes application migration easier. Docker can run on many platforms, whether it is a physical machine, a virtual machine, a public cloud, a private cloud, or even a notebook.

Therefore, users can easily migrate the application running on one platform to another platform without worrying about the situation that the application cannot run normally due to the change of running environment.

2. Docker installation

System environment: docker supports at least centos7 on 64 bit platform with kernel version above 3.10

Version: community version, enterprise version (including some charging services)

Official installation tutorial

Installation tutorial of the main edition of the Expo:

#   Install docker
yum install docker
#   Start docker 
systemctl start/status docker 
#   View docker startup status
docker version

Configure accelerator

Introduction: daocloud accelerator is a popular docker tool, which solves the problem of slow access to docker hub for domestic users. Combined with domestic CDN service and protocol layer optimization, daocloud accelerator has doubled the download speed.

Official website of daocloud:

#   A command to speed up (remember to restart docker)
curl -sSL | sh -s

3. Docker basic command

Docker — help

docker [OPTIONS] COMMAND [arg...]
       docker daemon [ --help | ... ]
       docker [ --help | -v | --version ]
self-sufficient runtime for containers.

  --config=~/.docker                Location   of   client   config   files   # Location of client profile
  -D,  -- debug=false                 Enable   debug   mode   # Enable debug mode
  -H,  -- host=[]                     Daemon   socket(s)   to   connect   to   # Socket connection of Daemons
  -h,  -- help=false                  Print   usage   # Print use
  -l,  -- log-level=info              Set   the   logging   level   # Set log level
  --tls=false                     Use TLS; implied by--tlsverify  #
  --tlscacert=~/.docker/ca.pem      Trust   certs   signed   only   by   this   CA   # Trust certificate signing CA
  --tlscert=~/.docker/cert.pem      Path   to   TLS   certificate   file   # TLS certificate file path
  --tlskey=~/.docker/key.pem        Path   to   TLS   key   file   # TLS key file path
  --tlsverify=false                 Use   TLS   and   verify   the   remote   # Remote authentication using TLS
  -v,  -- version=false               Print   version   information   and   quit   # Print version information and exit

    attach      Attach   to   a   running   container   # The attach connection in the current shell specifies the running image
    build       Build   an   image   from   a   Dockerfile   # Customizing image through dockerfile
    commit      Create   a   new   image   from   a   container's   changes   # Submit the current container as a new image
    cp      Copy   files/folders   from   a   container   to   a   HOSTDIR   or   to   STDOUT   # Copy the specified file or directory from the container to the host
    create      Create   a   new   container   # Create a new container, the same as run   But do not start the container
    diff      Inspect   changes   on   a   container's   filesystem   # View docker container changes
    events      Get   real   time   events   from   the   Server # gets container real-time events from docker service
    exec      Run   a   command   in   a   running   Container # run the command on an existing container
    export      Export   a   container's   filesystem   as   a   tar   archive   # Export the content stream of the container as a tar Archive (corresponding to import)
    history      Show   the   history   of   an   image   # Show the history of a mirror image
    images      List   images   # Lists the current image of the system
    import      Import   the   contents   from   a   tarball   to   create   a   filesystem   image   # Create a new file system image (corresponding to export) from the contents of the tar package
    info      Display   system-wide   information   # Display system related information
    inspect      Return   low-level   information   on   a   container   or   image   # View container details
    kill      Kill   a   running   container   # Kill specifies the docker container
    load      Load   an   image   from   a   tar   archive   or   STDIN   # Load an image from a tar package (corresponding to save)
    login      Register   or   log   in   to   a   Docker   Register? Register or log in to a docker source server
    logout      Log   out   from   a   Docker   registry   # From current docker   Registry exit
    logs      Fetch   the   logs   of   a   container   # Output current container log information
    pause      Pause   all   processes   within   a   Container # pause container
    port      List   port   mappings   or   a   specific   mapping   for   the   CONTAINER   # View the internal source port of the container corresponding to the mapping port
    ps      List   containers   # List containers
    pull      Pull   an   image   or   a   repository   from   a   registry   # Pull the specified image or library image from the docker image source server
    push      Push   an   image   or   a   repository   to   a   registry   # Push the specified image or library image to the docker source server
    rename      Rename   a   container   # Rename container
    restart      Restart   a   running   container   # Restart the running container
    rm      Remove   one   or   more   containers   # Remove one or more containers
    rmi      Remove   one   or   more   images   # Remove one or more images (if there is no container to use this image, you can delete it, otherwise you need to delete related containers to continue, or - f force deletion)
    run      Run   a   command   in   a   new   container   # Create a new container and run a command
    save      Save   an   image(s)   to   a   tar   Archive # save an image as a tar package (corresponding to load)
    search      Search   the   Docker   Hub   for   images   # In docker
Search image in hub
    start      Start   one   or   more   stopped   Containers? Start the container
    stats      Display   a   live   stream   of   container(s)   resource   usage   statistics   # Statistics container usage resources
    stop      Stop   a   running   container   # Stop container
    tag           Tag   an   image   into   a   repository   # Label image in source
    top         Display   the   running   processes   of   a   container  # View the process information running in the container
    unpause      Unpause   all   processes   within   a   container   # Unpause container
    version      Show   the   Docker   version   Information # view container version number
    wait           Block   until   a   container   stops,   then   print   its   exit   code   # Intercepts the exit state value when the container stops

Run  ' docker   COMMAND  -- help'   for   more   information   on   a   command.   # Run the docker command to get more information in help
docker   search    hello-docker   #  Search the image of Hello docker
docker   search   centos  #  Search CentOS image
docker   pull   hello-docker  #  Get CentOS image
docker   run    hello-world    # Run a docker image to generate a container instance (you can also run through the first three digits of the image ID)
docker   image   ls   #  View all local images
docker   images   #  View docker image
docker   image   rmi   hello-docker  #  Delete CentOS image
docker   ps   # List the running containers (if no process is running in the created container, the container will stop immediately)
docker   ps  - a   #  List all running container records
docker   save   centos  > / opt/centos.tar.gz   #  Export docker image to local
docker load

3.1 two ways to start the container

The container is used to run applications, so it must be based on an operating system

1. Create a new container based on the image and start it

#   one   Running a docker in the background
docker   run  - d   centos  / bin/sh  - c  " while   true; do   echo   Is running;   sleep   1; done"
    #  - d    Background run container
    #  / bin/sh    Specifies the bash interpreter using CentOS
    #  - c   Run a shell command
    #  " while   true; do   echo   Is running;   sleep   1; done"    In the background of Linux, printing once per second is running
docker   ps   #  Check container process
docker    logs   - f    Container ID / name   #  Continuous printing of container log information 
docker   stop   centos   #  Stop container

#   two   Start a bash terminal to allow users to interact
docker run --name mydocker -it centos /bin/bash  
    #  -- name    Define a name for the container
    #  - i    Leave the standard input of the container open
    #  - t   Let docker assign a pseudo terminal and bind it to the standard input of the container
    #  / bin/bash   Specify docker container and interact with shell interpreter

When using docker run to create a container, the steps of docker running in the background are as follows:

  1. Check whether the specified image exists locally. If it does not exist, download it from the public warehouse
  2. Create and start a container using the image
  3. Allocate a file system and hang a read-write layer outside the read-only image layer
  4. Bridge a virtual interface from the bridge interface configured by the host to the container
  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 container

[ [email protected]  ~]#  docker   ps  - a   #  Query records first
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                        PORTS                    NAMES
ee92fcf6f32d        centos              "/bin/bash"              4 days ago          Exited (137) 3 days ago                                kickass_raman

[ [email protected]  ~]#  docker   start   ee9   #  Restart the container

[ [email protected]  ~]#  docker   exec  - it    ee9  / bin/bash   #  Enter the container interactive interface
[ [email protected]  /]#   #  Note that the user name has become the container user name

3.2 submit and create custom image

#   1. We enter the interactive CentOS container and find that there is no VIM command
    docker run -it centos
#   2. Install a VIM in the current container
    yum install -y vim
#   3. After installing VIM, exit exits the container
#   4. Check the container record of vim just installed
    docker container ls -a
#   5. Submit the container and create a new image
    docker commit 059fdea031ba chaoyu/centos-vim
#   6. View the image file
    docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
chaoyu/centos-vim   latest              fd2685ae25fe        5 minutes ago

3.3 external access container

Network applications can be run in the container, but to make these applications accessible to the outside, you can specify the port mapping through the – P or – P parameter.

docker run -d -P training/webapp python
  #  - P   The parameter randomly maps the port to the open network port of the container

#   Check the mapped port
docker ps -l
CONTAINER ID        IMAGE               COMMAND             CREATED            STATUS              PORTS                     NAMES
cfd632821d7a        training/webapp     "python"     21 seconds ago      Up 20 seconds>5000/tcp   brave_fermi
#Host IP: 32768   Port 5000 of mapping container

#   View container log information
docker   logs  - f   cfd   # # Continuous display log

#   You can also specify the mapping port through the - P parameter
docker run -d -p 9000:5000 training/webapp python

Open the browser to access the 9000 port of the server, and the content shows Hello world! Indicates normal start

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

4. Using dockerfile to customize image

Image is the basis of container. Every time docker run is executed, which image will be specified as the basis of container running. Our previous examples all use images from docker hub. Direct use of these images can only meet certain requirements. When the images cannot meet our requirements, we have to customize these images.

The customization of image is to customize the configuration and files added to each layer. If you can write the commands of modification, installation, construction and operation of each layer to a script, and build and customize the image with script, this script is dockerfile.

Dockerfile is a text file, which contains instructions. Each instruction constructs a layer. Therefore, the content of each instruction describes how the layer should be constructed.

Parameter details

FROM   scratch  # Make base   image   Basic image, try to use the official image as the base   image
FROM   centos  # Using base   image
FROM   ubuntu:14.04  # Base with tag   image

LABEL   version=“1.0”  # Container meta information, help information, metadata, similar to code comments
LABEL maintainer=“[email protected]"

#For complex run commands, avoid useless layering, multiple commands with backslash line feed, synthesis of a command!
RUN yum update && yum install -y vim 
    Python-dev  # Backslash wrap
RUN /bin/bash -c "source $HOME/.bashrc;echo $HOME”

WORKDIR  / root  # Equivalent to the Linux CD command, change the directory, try to use the absolute path!!! Don't use run CD
WORKDIR  / test  #  If not, create it automatically
WORKDIR   demo  #  Then enter the demo folder
RUN   pwd      #  The print result should be / test / demo

ADD   hello  /  #  Add the local file to the image and copy the local Hello executable file to the / directory of the image
ADD   test.tar.gz  /  #  Add to the root and unzip

ADD   hello   test/   #  Enter / root/   Add the Hello executable command to the test directory, that is, / root / test / Hello   An absolute path
COPY   hello   test/   #  Equivalent to the above add effect

Add and copy
   -   The copy command is preferred
    -In addition to copy function, add also has decompression function
Adding remote files / directories using curl or WGet

ENV  #  Environment variables, as far as possible to use env to increase maintainability
ENV   MYSQL_ VERSION   five point six  #  Set a MySQL constant
RUN yum install -y mysql-server=“${MYSQL_VERSION}”

Advanced knowledge (understanding)

Storage and networking

Run: execute the command and create a new image layer
CMD: set the default commands and parameters 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 commands in shell format will read the $name instruction, while exec format only executes a command, not a shell instruction
cat Dockerfile
    FROM centos
    ENV name Docker
    ENTRYPOINT  [“/ bin/echo”,”hello  $ Name "] # this is just to execute the echo command, not to read shell variables
    ENTRYPOINT  [“/bin/bash”,”-c”,”echo hello $name"]

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

Let the container run as an application or service
It will not be ignored, it will be executed
Best practice: write a shell script as an entrypoint
COPY /usr/local/bin
EXPOSE 27017
CMD [“mongod”]

[[email protected] home]# more Dockerfile
FROm centos
ENV name Docker
#CMD ["/bin/bash","-c","echo hello $name"]
ENTRYPOINT ["/bin/bash","-c","echo hello $name”]

5. Publish to warehouse

5.1 common image publishing of docker hub

Docker provides a warehouse similar to GitHub, docker hub, official website (need to be registered)

#   Register docker   Then log in to dockerhub in Linux
    docker login

#   Note to ensure that the image tag is the account name. If the image name is wrong, you need to change the tag
    docker tag chaoyu/centos-vim peng104/centos-vim
    #   The syntax is: docker tag    Warehouse name     Peng104 / warehouse name

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

#   Check the image in dockerhub
#   Delete the local image first, and then test the download pull   Image file
    docker pull peng104/centos-entrypoint-exec

5.2 private warehouse

Docker hub is public and can be downloaded by other people, which is not secure. Therefore, you can also use the private warehouse officially provided by docker registry

Usage details:

#   1. Download a docker official private warehouse 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 operation 
    -p    Port mapping   5000 of host: 5000 in container
    -v    Data volume mount    Host's  / opt/data/registry  :/ var/lib/registry 
    registry    Image name
    /var/lib/registry    Location of private warehouse
#Docker does not allow images to be pushed in non HTTPS mode by default. We can remove this restriction through the configuration option of docker
#   3. Modify the configuration file of docker to support HTTP and upload private image
    vim /etc/docker/daemon.json 
    #   Write the following
        "registry-mirrors": [""],
#   4. Modify the service configuration file of docker
    vim /lib/systemd/system/docker.service
#   Find the code area block [service] and write the following parameters
#   5. Reload docker service
    systemctl daemon-reload
#   6. Restart docker service
    systemctl restart docker
    #   Note: restart the docker service and all containers will hang up

#   7. Modify the tag of the local image and push it to your private warehouse
    docker tag
    #   Browser access :5000/v2/_ Catalog view warehouse
#   8. Download the image of private warehouse
    docker pull

6. Example demonstration

Write dockerfile, build your own image, and run flash program.

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

#   1. Prepare the flash program of
    [[email protected] ~]# cat
    from flask import Flask
    def hello():
        return "hello docker"
    if __name__=="__main__":'',port=8080)
    [[email protected] home]# ls  Dockerfile

#   2. Write dockerfile
    [[email protected] ~]# cat Dockerfile
    FROM python:2.7
    LABEL   Maintainer = "warm and new"
    RUN pip install flask
    COPY /app/
    WORKDIR /app
    EXPOSE 8080
    CMD ["python",""]

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

#   4. View the created images
    docker image ls

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

#   6. Check the running container
    docker container ls

#   7. Push the image to the private warehouse
    docker tag  peng104/flask-hello-docker
    docker push

What’s the gain after reading this article? Please forward it to more people

Pay attention to the official account: Java treasure