1. Introduction
1.1 what is docker
Docker was originally an internal project launched by Solomon Hykes, the founder of dotCloud company, during his stay in France. It was open-source under the Apache 2.0 license agreement in March 2013. The main project code is maintained on GitHub.
Docker is developed and implemented in Go language launched by Google.
docker is an 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 applications and program dependencies in a file. Running this file will generate a virtual container.
The program runs in a virtual container, just as it runs 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 and release
Deploy and adjust 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
- Mirror image
- container
- Warehouse repository
Advantages of docker container
1. More efficient use of system resources
Because the container does not need additional overhead such as hardware virtualization and running a complete operating system, Docker has a 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
The traditional virtual machine technology often takes several minutes to start the application service, while the Docker container application can achieve the start-up time of seconds or even milliseconds because it runs directly in the host kernel and does not need to start the complete operating system. It greatly saves the time of development, testing and deployment.
3. Consistent operating environment
A common problem in the development process is the consistency of the environment. Because the development environment, test environment and production environment are inconsistent, some bug s have not been found in the development process.
The Docker image provides a complete runtime environment other than the kernel, ensuring the consistency of the application running environment, so that there will be no problems such as "this code is OK on my machine".
4. Continuous delivery and deployment
For development and operation and maintenance (DevOps) personnel, what they want most is to create or configure it at one time, and it can run normally anywhere.
Using Docker, continuous integration, continuous delivery and deployment can be realized by customizing application images. Developers can build the image through Dockerfile and conduct integration test in combination with continuous integration system, while operation and maintenance personnel can quickly deploy the image directly in the production environment, or even automatically deploy it in combination with continuous delivery / deployment system.
Moreover, the use of Dockerfile makes the image construction transparent, which 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 application running, and helps deploy the image in a better production environment.
5. Easier migration
Because docker ensures the consistency of the execution environment, it makes the migration of applications easier. Docker can run on many platforms, whether it is physical machine, virtual machine, public cloud, private cloud or even notebook, and its running results are consistent.
Therefore, users can easily migrate applications running on one platform to another platform without worrying about the failure of applications to run normally due to changes in the operating environment.
2. Docker installation
System environment: docker supports CentOS 7 at least and is on 64 bit platform with kernel version above 3.10
Version: community version, enterprise version (including some paid services)
Official installation tutorial (English)
Blog master installation tutorial:
#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 by domestic users. DaoCloud accelerator combines domestic CDN service and protocol layer optimization to double the download speed.
DaoCloud official website:
https://www.daocloud.io/mirror#accelerator-doc
#A command accelerates (remember to restart docker) curl -sSL https://get.daocloud.io/daotools/set_mirror.sh | sh -s http://95822026.m.daocloud.io
3. Docker basic command
docker --help (Chinese annotation)
Usage: docker [OPTIONS] COMMAND [arg...] docker daemon [ --help | ... ] docker [ --help | -v | --version ] A self-sufficient runtime for containers. Options: --config=~/.docker Location of client config files #Location of client profile -D, --debug=false Enable debug mode #Enable Debug debug mode -H, --host=[] Daemon socket(s) to connect to #Socket connection of daemon -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 Commands: attach Attach to a running container #The attach connection under the current shell specifies the running image build Build an image from a Dockerfile #Customized image through Dockerfile commit Create a new image from a container's changes #Commit 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#Get 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 a mirror formation history 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 from the contents of the tar package (corresponding to export) 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 registry#Register or log in to a docker source server logout Log out from a Docker registry #Exit from the current Docker registry 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 mapped 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 (the image can be deleted only if there is no container. Otherwise, you need to delete the relevant container to continue or -f force the 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 hub Search for images in start Start one or more stopped containers#Start 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 the image in the source top Display the running processes of a container #View the process information running in the container unpause Unpause all processes within a container #Unsuspend container version Show the Docker version information#View container version number wait Block until a container stops, then print its exit code #Intercept the exit status value when the container stops Run 'docker COMMAND --help' for more information on a command. #Run the docker command to get more information in the 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 mirrors 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 container records that have been run docker save centos > /opt/centos.tar.gz #Export docker image to local docker load < /opt/centos.tar.gz #Import local image to docker image library docker stop `docker ps -aq` #Stop all running containers docker rm `docker ps -aq` #Delete all container records at once docker rmi `docker images -aq` #Delete all local mirror records at once
3.1 two ways to start the container
Containers run applications, so they must be based on an operating system
1. Create a new container based on the image and start it
# 1. Running a docker in the background docker run -d centos /bin/sh -c "while true;do echo Running; sleep 1;done" #- d) background running container #/ bin/sh , specifies the bash interpreter using centos #- c) run a shell command #"while , true;do , echo , running; sleep , 1;done" in the linux background, printing is running once a second docker ps #Check container process docker logs -f container id/name #Continuously print the log information of the container docker stop centos #Stop container # 2. 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) keep 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 the docker container and interact with the shell interpreter
When using docker run to create a container, the steps of Docker running in the background are as follows:
- Check whether the specified image exists locally. If it does not exist, download it from the public warehouse
- Create and start a container using the image
- Allocate a file system and hang it on a read-write layer outside the read-only image layer
- Bridge a virtual interface from the bridge interface configured by the host to the container
- Configure an ip address from the address pool to the container
- Execute user specified applications
- The container is terminated after execution
2. Restart a stopped container
[root@localhost ~]# 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 [root@localhost ~]# docker start ee9 #Restart the container ee9 [root@localhost ~]# docker exec -it ee9 /bin/bash #Enter the container interactive interface [root@ee92fcf6f32d /]# #Note that the user name has become the container user name
3.2 submit and create custom image
# 1. We entered the interactive centos container and found that there was 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. Check the container record of vim just installed docker container ls -a # 5. Submit this container and create a new image docker commit 059fdea031ba chaoyu/centos-vim # 6. View mirrored files 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 allow external access to these applications, you can specify the port mapping through the - P or - P parameter.
docker run -d -P training/webapp python app.py #The - P # parameter randomly maps the port to the open network port of the container #Check mapped ports docker ps -l CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES cfd632821d7a training/webapp "python app.py" 21 seconds ago Up 20 seconds 0.0.0.0:32768->5000/tcp brave_fermi #Host ip:32768 # mapping the 5000 port of the container #View container log information docker logs -f cfd # #Continuous display of log #You can also specify the mapping port through the - p parameter docker run -d -p 9000:5000 training/webapp python app.py
Open the browser to access the 9000 port of the server, and the content displays Hello world! Indicates normal startup
(if the access fails, check your firewall and the security group of ECS)
4. Using dockerfile to customize image
The image is the basis of the container. Each time docker run is executed, which image will be specified as the basis for the container to run. Our previous examples used images from docker hub. Using these images directly can only meet certain needs. When the images can not meet our needs, we have to customize these images.
Image customization is to customize the configuration and files added by each layer. If you can write the commands of modification, installation, construction and operation of each layer into a script, and use the script to build and customize the image. This script is dockerfile.
Dockerfile is a text file containing instructions. Each instruction builds a layer. Therefore, the content of each instruction is to describe how the layer should be built.
Detailed explanation of parameters
FROM scratch #Make base image basic image and try to use official image as base image FROM centos #Using base image FROM ubuntu:14.04 #base image with tag LABEL version="1.0" #Container meta information, help information, Metadata, similar to code comments LABEL maintainer="yc_uuu@163.com" #For complex RUN commands, avoid useless layering. Multiple commands wrap with backslashes to synthesize one 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 cd command of linux, change the directory and try to use the absolute path!!! Do not use RUN cd WORKDIR /test #If not, it will be created automatically WORKDIR demo #Then enter the demo folder RUN pwd #The print result should be / test/demo ADD and COPY 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 directory and unzip WORKDIR /root ADD hello test/ #Enter / root / and add the hello executable command to the test directory, which is an absolute path of / root/test/hello COPY hello test/ #Equivalent to the above ADD effect ADD And COPY - priority of use COPY command -ADD except COPY Function and decompression function Add remote file/Directory usage curl or wget ENV #Environment variables, use ENV as much as possible to increase maintainability ENV MYSQL_VERSION 5.6 #Set a mysql constant RUN yum install -y mysql-server="${MYSQL_VERSION}"
Advanced knowledge (understanding)
VOLUME and EXPOSE Storage and networking RUN and CMD and ENTRYPOINT RUN: Execute the command and create a new Image Layer CMD: Set the commands and parameters to be executed by default after the container is started ENTRYPOINT: Sets 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"] adopt shell Format to run the command, will read $name Command, and exec The format is to execute only one command, not shell instructions cat Dockerfile FROM centos ENV name Docker ENTRYPOINT ["/bin/echo","hello $name"]#This is only to execute echo command and cannot read shell variables ENTRYPOINT ["/bin/bash","-c","echo hello $name"] CMD The default command to execute when the container starts If docker run Other commands specified(docker run -it [image] /bin/bash ),CMD Command ignored If you define more than one CMD,Only the last execution ENTRYPOINT Let the container run as an application or service It will not be ignored and will be implemented Best practice: write a shell Script as 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. Publish to warehouse
5.1 common image publishing of docker hub
docker provides a repository similar to github, which is the official website (registration is required)
#After registering docker # id, log in to dockerhub in linux docker login #Pay attention to ensure that the tag of the image 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 #First delete the local image, and then test and download the pull# image file docker pull peng104/centos-entrypoint-exec
5.2 private warehouse
docker hub is public and can be downloaded by others. It is not safe. Therefore, you can also use the private warehouse officially provided by docker registry
Detailed usage:
https://yeasy.gitbooks.io/docker_practice/repository/registry.html
# 1. Download an official private warehouse image of docker 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 /opt/data/registry :/var/lib/registry registry Image name /var/lib/registry Location of private warehouse # Docker does not allow non HTTPS image push by default. We can cancel this restriction through docker configuration options # 3. Modify the configuration file of docker to support http mode and upload private images vim /etc/docker/daemon.json #Write the following { "registry-mirrors": ["http://f1361db2.m.daocloud.io"], "insecure-registries":["192.168.11.37:5000"] } # 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 [Service] EnvironmentFile=-/etc/docker/daemon.json # 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 tag of the local image and push it to your own private warehouse docker tag docker.io/peng104/hello-world-docker 192.168.11.37:5000/peng-hello #Browser access http://192.168.119.10:5000/v2/_catalog View warehouse # 8. Download Image of private warehouse docker pull 192.168.11.37:5000/peng-hello
6. Example demonstration
Write dockerfile, build your own image and run flash program.
Make sure the app Py and dockerfile are in the same directory!
# 1. Get the app ready Flash program of PY [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="Wen Erxin" RUN pip install flask COPY app.py /app/ WORKDIR /app EXPOSE 8080 CMD ["python","app.py"] # 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 flask Hello docker container and map a port for external access docker run -d -p 8080:8080 peng104/flask-hello-docker # 6. Check running containers docker container ls # 7. Push this image to the private warehouse docker tag peng104/flask-hello-docker 192.168.11.37:5000/peng-flaskweb docker push 192.168.11.37:5000/peng-flaskweb
What are the gains after reading this article? Please forward and share with more people
Follow official account: java classic