(Add stars to Linux fans to improve Linux skills)
Source: Warm and New
www.cnblogs.com/peng104/p/10296717.html
1, the introduction
1.1 What is a Docker
Docker was originally an internal project initiated by dotCloud founder Solomon Hykes while he was in France. Docker was opened under the Apache 2.0 license in March 2013, and the main project code is maintained on GitHub.
Docker uses the Go language launched by Google for development and implementation.
Docker is a Linux container wrapper that provides an easy-to-use interface for using containers. It is the most popular Linux container solution.
Docker interface is quite simple, users can easily create and destroy containers.
Docker packages the application and its dependencies in a single file. Running this file generates a virtual container.
Applications run in virtual containers as if they were running on a physical machine, but with Docker, there are no environmental concerns.
1.2 Application Scenarios
-
Automated packaging and distribution of Web applications
-
Automated testing and continuous integration, release
-
Deploy and tune databases or other applications in a service environment
1.3 the difference between
1. Physical machine
2. Virtual machines
Docker container
1.4 Three concepts and advantages of Docker
-
The mirror image
-
Container, the container
-
Warehouse repository
Advantages of docker containers
# 1. Use system resources more efficiently
Docker has a higher utilization of system resources because the container does not require additional overhead such as hardware virtualization and running a full operating system.
Whether it is application execution speed, memory consumption or file storage speed, it is more efficient than legacy VIRTUAL machine technology. Therefore, a host with the same configuration can often run more applications than virtual machine technology.
# 2. Faster startup time
Traditional VIRTUAL machine technology usually takes several minutes to start application services, while Docker container applications can be started in seconds or even milliseconds because they run directly in the host kernel and do not need to start the complete operating system. Greatly saving the development, testing, deployment time.
# 3. Consistent operating environment
A common problem in development is environmental consistency. Because the development environment, test environment and production environment are not consistent, some bugs are not found in the development process.
The image of Docker provides a complete runtime environment in addition to the inner core, ensuring the consistency of the application running environment, so that there will no longer be “this code is ok on my machine” such problems.
# 4. Continuous delivery and deployment
The most desirable thing for development and operations (DevOps) people is a single build or configuration that can run anywhere.
With Docker, continuous integration, continuous delivery and deployment can be achieved by customizing application images. Dockerfile allows developers to build images and test Integration with the Continuous Integration system, while operations can quickly deploy the image directly into production. Even automatic Deployment with Continuous Delivery/Deployment systems.
Moreover, using Dockerfile to make image construction transparent, not only the development team can understand the application operation environment, but also facilitate the operation and maintenance team to understand the conditions required for application operation, helping to better deploy the image in the production environment.
# 5. Easier migration
Docker ensures the consistency of execution environment, making application migration easier. Docker can run on many platforms, no matter physical machine, virtual machine, public cloud, private cloud, or even notebook, and its operation results are consistent.
Therefore, users can easily migrate an application running on one platform to another without worrying that the application will not run properly due to the change of the operating environment.
2, 0Docker installation
System environment: Docker supports Centos7 at least and is on 64-bit platform with kernel version above 3.10
Version: Community edition, Enterprise Edition (includes some paid services)
Official Installation Tutorial (English)
https://docs.docker.com/install/linux/docker-ce/centos/#upgrade-docker-after-using-the-convenience-script
Blogger version installation tutorial:
# install dockeryum install docker# install docker systemctl start/status docker# install docker systemctl start/status
Copy the code
Configuration accelerator
DaoCloud Accelerator is a popular Docker tool that solves the problem of slow Docker Hub access for domestic users. DaoCloud Accelerator combines domestic CDN service and protocol layer optimization to double the download speed.
DaoCloud website:
https://www.daocloud.io/mirror#accelerator-doc
# a command acceleration (remember to restart the docker) curl - sSL https://get.daocloud.io/daotools/set_mirror.sh http://95822026.m.daocloud.io | sh - s
Copy the code
3, 0Docker basic command
Docker –help
Usage:docker [OPTIONS] COMMAND [arg...] docker daemon [ --help | ... ] docker [ --help | -v | --version ]Aself-sufficient runtime for containers.Options: --config=~/. Docker Location of client config files -d, --debug=false Enable debug mode --host=[] Daemon socket(s) to connect to # --help=false Print usage # --log-level=info Set the logging level -- TLS =false Use TLS; Implied by-- TLsVerify # -- TLSCacert =~/.docker/ca.pem Trust certs signed only by this CA # --tlscert=~/.docker/cert.pem Path to TLS certificate file # TLskey =~/.docker/key.pem Path to TLS key file Tlsverify =false Use TLS and verify the remote --version=false Print version information and quit Build build an image from a Dockerfile # Attach attach to a running container # Cp Copy files/folders from a container to a HOSTDIR or To STDOUT # to copy a specified file or directory from the container to the host Diff Inspect changes on a container's filesystem Exec Run a command in a running container# Export export a container's filesystem # Show the history of an image # Show the history of an image # Show the history of an image Import import the contents from a tarball to create a filesystem image create a new filesystem image (corresponding to export) info Inspect Return low-level information on a container or image inspect to Display system-wide information kill Kill a running container # Kill docker container load load an image from a tar archive or STDIN # The current Docker registry can be logged out of the current Docker registry Pause Pause all processes within a container# Pause the container port List port mappings Ps List containers # Pull an image or a repository Push an image or a repository to a registry # Push an image or a repository to a registry Restart restart a container rm Remove one or more containers Rmi Remove one or more images. Run run a command in a new container # Create a new container and run a command save save an image(s) to a tar Search the Docker Hub for images start start one or more stopped Stats Display a live stream of container(s) Resource Usage statistics # Stop stop a running Container tag tag an image into a repository top Display the running processes of a container Unpause Unpause all processes within a container # Unpause container version Show the Docker version Information# Wait Block until a container stops Then print its exit code # Run 'docker COMMAND --help' for more information on a COMMAND. Run the docker command in the help to get more information
Copy the code
Docker search hello-docker # search centos # pull hello-docker # Docker run hello-world Docker image rmi Hello -docker # docker image rmI hello-docker # Docker ps # list the containers that are currently running. Docker save centos > /opt/centos.tar.gz docker load < / opt/centos. Tar. Gz # import local mirror to docker image libraries docker stop ` docker ps - aq ` # stop all running container docker rm ` docker ps - aq ` # Rmi 'docker images -aq' # delete all local images at once
Copy the code
3.1 Two ways to start containers
Containers run applications, so they must be based on an operating system
1. Create a container based on the image and start it
Run -d centos /bin/sh -c "while true; Do Echo is running; sleep 1; Done "# -d -d bash interpreter # /bin/sh Do Echo is running; sleep 1; Docker logs -f docker logs -f docker logs -f docker logs -f docker logs Docker run --name mydocker -it centos /bin/bash # --name Define a name for the container # -i keep the container's standard input open # -t Have Docker assign a dummy terminal and bind it to the container's standard input # /bin/bash to specify the Docker container and interact with the shell interpreter
Copy the code
When docker run is used to create containers, the steps of docker run in the background are as follows:
Check whether the specified image exists locally. If not, download # 2 from the public repository. Create and start a container with an image # 3. Allocate a file system and hang it on a read-write layer outside the read-only image layer # 4. Bridge a virtual interface from the host's configured bridge interface to the container. Configure an IP address from the address pool to container # 6. Execute user-specified application # 7. The container is terminated after execution
Copy the code
2. Restart a container in the stopped state
[root@localhost ~]# docker ps a # CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMESee92fcf6f32d centos "/bin/bash" 4 days ago Exited (137) 3 days ago kickass_raman[root@localhost ~]# docker start ee9 # [root@localhost ~]# docker exec -it ee9 /bin/bash [root@ee92fcf6f32d /]#
Copy the code
3.2 Submitting a User-defined Mirror
Docker run -it centos# 2 In the current container, install a vim yum install -y vim# 3. Docker container ls -a# 5 Commit 059fDEA031ba Chaoyu /centos # 6 to create a new Image Docker Docker imagesREPOSITORY TAG IMAGE ID CREATED SIZEchaoyu/centos-vim latest FD2685AE25fe 5 minutes ago 348MB
Copy the code
3.3 External Access containers
Network applications can run in the container, but to make them externally accessible, you can specify port mappings with either the -p or -p arguments.
Docker run -d -p training/ webApp python app.py # -p randomly maps the port to the open network port of the container CREATED STATUS PORTS NAMEScfd632821d7a training/webapp "python app.py" 21 seconds ago Up 20 seconds 0.0.0.0:32768->5000/tcp brave_fermi# host IP :32768 # docker logs -f CFD # Docker run -d -p 9000:5000 training/ webApp Python app.py can also be specified by using the -p parameter
Copy the code
Open a browser and access port 9000 of the server. The message “Hello World! Indicates normal startup.
(If access fails, check your firewall and the cloud server’s security group)
4. Customize the image using Dockerfile
The image is the basis of the container. Each time a Docker run is executed, the image is specified as the basis for the container to run. Our previous examples used images from docker Hub. Using these images directly only meets certain requirements. When the images do not meet our requirements, we have to customize the images.
Image customization is to customize the configuration and files added to each layer. If you can write each layer of modification, installation, build, operation commands into a script, with the script to build, customize the image, this script is dockerFile. # Dockerfile is a text file containing instructions. Each Instruction builds a layer, so the content of each Instruction describes how the layer should be built.
Copy the code
Parameters,
FROM scratch # create a base image Centos # use base imageFROM Ubuntu :14.04 # Tag base imageLABEL version= "1.0" # Metadata, similar to code note LABEL Maintainer = "[email protected]"# For complex RUN commands, avoid useless hierarchical, multiple commands with a backslash line, composite command! RUN yum update && yum install -y vim \ Python-dev # RUN /bin/bash -c "source $HOME/. Bashrc; Echo $HOME "WORKDIR /root" RUN PWD = /test/demoADD and COPY ADD hello / # Add local files to the image, ADD test.tar.gz / # ADD hello test to the root directory and unpack WORKDIR /rootADD hello test/ # Use curl or wgetENV # to ADD a remote file/directory RUN yum install -y mysql-server= "${MYSQL_VERSION}"
Copy the code
Advanced knowledge (understanding)
VOLUME and EXPOSE Storage and network RUN and CMD and ENTRYPOINTRUN: RUN and CMD and ENTRYPOINTRUN: RUN and CMD and ENTRYPOINTRUN: RUN and CMD and ENTRYPOINTRUN: RUN and CMD and ENTRYPOINTRUN: RUN and CMD and ENTRYPOINTRUN: RUN and CMD and ENTRYPOINTRUN: RUN and CMD and ENTRYPOINT: RUN yum install -y vimCMD 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 "] reads the $name directive in shell format, while exec format only executes a command. Cat Dockerfile FROM centos ENV name Docker ENTRYPOINT [" /bin/echo "," ENTRYPOINT [" /bin/bash ", "-c"," Echo hello $name"] echo hello $name"] if docker run specifies another command (docker run -it [image] /bin/bash) Only the last execution of ENTRYPOINT to let the container run as an application or service is not ignored, and best practices must be implemented: Write a shell script as entrypointCOPY docker-entrypoint.sh /usr/local/binentrypoint [" docker-entrypoint.sh]EXPOSE 27017CMD [" mongod "][root@master home]# more DockerfileFROm centosENV name Docker#CMD ["/bin/bash","-c","echo hello" ENTRYPOINT $name "] ["/bin/bash ", "- c", "echo" hello $name]
Copy the code
5. Release to the warehouse
5.1 Docker Hub Shared Images are published
Docker provides a repository similar to Github docker Hub, official website (registration required)
https://hub.docker.com/
Dockerhub docker login = dockerhub docker login = dockerhub docker login Docker Tag Chaoyu /centos-vim peng104/centos-vim # Docker push a docker image to a dockerhub docker push a docker image to a dockerhub docker push a peng104/ centps-cd-exec Docker pull peng104/centos-entrypoint-exec docker pull peng104/centos-entrypoint-exec
Copy the code
5.2 Private Warehouse
Docker Hub is public and other people can download it, which is not secure, so you can also use the private repository provided by Docker Registry
Usage:
https://yeasy.gitbooks.io/docker_practice/repository/registry.html
Docker pull registration # 2 Run a docker private container warehouse docker run - d - p 5000:5000 - v/opt/data/registry: / var/lib/registry registry - d background - p port mapping /opt/data/registry :/var/lib/registry :/var/lib/registry By default, non-HTTPS image pushing is not allowed. We can remove this restriction # 3 with Docker configuration options. {"registry-mirrors": enter the following information: vim /etc/dock/daemon. json (" http://f1361db2.m.daocloud.io "), "insecure - registries" : [192.168.11.37:5000 ""]} # 4. Modify the docker service configuration file vim/lib/systemd/system/docker. Service# find [service] this is an area of the code block, Write [Service] EnvironmentFile=- /etc/dock/daemon.json # 5. Reload the docker service systemctl daemon-reload# 6. Docker systemctl restart docker systemctl restart docker Modify the tag of the local mirror. IO /peng104/hello-world-docker 192.168.11.37:5000/peng-hello # The browser to http://192.168.119.10:5000/v2/_catalog to check the warehouse # 8. Docker pull 192.168.11.37:5000/peng-hello
Copy the code
6. Example demonstration
Write dockerFile, build your own image, and run flask.
Make sure app.py and dockerfile are in the same directory!
[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. 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. Docker build -t peng104/flask-hello-docker.# 4 View the created images docker image ls# 5. Start this 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. Docker Tag Peng104 / flask-hello-Docker 192.168.11.37:5000/ PENG-flaskWeb Docker push this image to private repository Docker tag Peng104 / flask-Hello-Docker 192.168.11.37:5000/ peng-FlaskWeb Docker push 192.168.11.37:5000 / peng - flaskweb
Copy the code
Recommended reading
(Click on the title to jump to read)
Docker tutorial
Important Docker command description prepared for xiaobai
Use Docker images as desktop systems
Have you learned anything after reading this article? Please share it with more people
Pay attention to the “Linux enthusiast” star to improve Linux skills
If you like, click “good-looking” bai ~