Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Two-hour entry-level Docker tutorial practice

2025-03-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/02 Report--

1.0 introduction

What is 1.1Docker?

Docker, originally an intra-company project launched by dotCloud founder Solomon Hykes in France, was open source under the Apache 2.0 license agreement in March 2013, and the main project code is maintained on GitHub.

Docker is developed and implemented in Go language developed by Google Company.

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

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

Docker packages the application and program dependencies in a file. Running this file will generate a virtual container.

The program runs in a virtual container, just as it does on a real physical machine. With docker, you don't have to worry about the environment.

1.2 Application scenario

Automated packaging and distribution of web applications automated testing and continuous integration, deployment and tuning of databases or other applications in a service-oriented environment

1.3 differences

1, physical machine

Second, virtual machine

Third, docker container

Three Concepts and advantages of 1.4Docker

1. Mirror image

two。 Container container

3. Warehouse repository

Docker easy advantage

1. More efficient use of system resources

Because the container does not need additional overhead such as hardware virtualization and running a full operating system, Docker has a higher utilization of system resources.

Whether it is application execution speed, memory consumption 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.

two。 Faster startup time

The traditional virtual machine technology often takes several minutes to start the application service, while the Docker container application runs directly in the host kernel and does not need to start the complete operating system, so it can achieve seconds or even milliseconds startup time. It greatly saves the time of development, testing and deployment.

3. Consistent operating environment

A common problem in the development process is environmental consistency. Due to the inconsistency of development environment, test environment and production environment, some bug have not been found in the development process.

On the other hand, the Docker image provides a complete runtime environment except the kernel, ensuring the consistency of the application environment, so that there will be no more problems such as "this code is fine on my machine."

4. Continuous delivery and deployment

For developers and operators (DevOps), what they want most is to create or configure it all at once, which can run smoothly anywhere.

Using Docker, you can customize application images to achieve continuous integration, continuous delivery, and deployment. Developers can build images through Dockerfile and conduct integration testing with continuous integration (Continuous Integration) systems.

On the other hand, the operation and maintenance personnel can quickly deploy the image directly in the production environment, or even deploy automatically in combination with the continuous deployment (Continuous Delivery/Deployment) system.

And using Dockerfile to make the construction of the image transparent, not only can the development team understand the application running environment, but also facilitate the operation and maintenance team to understand the conditions needed for the application to run, and help 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's physical machines, virtual machines, public clouds, private clouds, or even laptops, and the results are consistent.

Therefore, users can easily migrate applications running on one platform to another without having to worry about the changes in the running environment that lead to the application not running properly.

2.0 Docker installation

System environment: docker supports minimum centos7 and kernel version above 3.10 on 64-bit platform

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

Official installation tutorial

Blogger installation tutorial:

# install dockeryum install docker# and start docker systemctl start/status docker# to 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, which increases the download speed exponentially.

DaoCloud official website

# one command acceleration (remember to restart docker) curl-sSL https://get.daocloud.io/daotools/set_mirror.sh | sh-s http://95822026.m.daocloud.io3.0 Docker basic command

Docker-help (Chinese Notes)

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 # location of client configuration file-- D,-- debug=false Enable debug mode # enable Debug debug mode-H,-- host= [] Daemon socket (s) to connect to # daemon socket (Socket) connection-h,-- help=false Print usage # print using-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 signature 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 # use TLS to verify remote-v -- version=false Print version information and quit # print version information and exit Commands: attach Attach to a running container # current shell connection specifies running image build Build an image from a Dockerfile # submit the current container to the 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 # to create a new container through Dockerfile custom image commit Create a new image from a container's changes # Same as run without starting 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 export Export a container's filesystem as a tar archive # export the container's content stream as an tar archive (corresponding to import) history Show the history of an image # show an image formation history images List images # list 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 specify docker container load Load an image from a tar archive or STDIN # load a mirror from a tar package (for Should save) login Register or login 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 container internal source port corresponding to the mapped port ps List containers # list container list pull Pull an image or a repository from a registry# Pull specified image from docker image source server or library image push Push an image or a repository to a registry # push specified image or library image to docker source server rename Rename a container # rename container restart Restart a running container # restart container rm Remove one or more containers # remove one or more container rmi Remove one or more images # remove one or more images (no container can delete this image only if it is used) Otherwise, you need to delete related containers before you can continue or-f force delete) 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# to save an image as a tar package (corresponding to load) search Search the Docker Hub for images # search dockerhub for image start Start one or more stopped containers# launch container stats Display a live stream of container (s) resource usage statistics # statistics capacity The server uses the resource stop Stop a running container # stop the container tag Tag an image into a repository # to tag the image in the source top Display the running processes of a container # to view the process information running in the container unpause Unpause all processes within a container # unpause the container version Show the Docker version information# to check the container version number wait Block until a container stops Then print its exit code # intercepts the exit status value Run 'docker COMMAND-- help' for more information on a command when the container stops. # run the docker command to get more information in help docker search hello-docker # search hello-docker image docker search centos # search centos image docker pull hello-docker # get centos image docker run hello-world # run a docker image Generate a container instance (you can also run it by mirroring the first three bits of id) docker image ls # View all local mirrors docker images # View docker images docker image rmi hello-docker # Delete centos images docker ps # list the containers that are running (if no process is running in the creation container The container will stop immediately) docker ps-a # lists all running container records docker save centos > / opt/centos.tar.gz # Export docker image to local docker load

< /opt/centos.tar.gz #导入本地镜像到docker镜像库docker stop `docker ps -aq` # 停止所有正在运行的容器docker rm `docker ps -aq` # 一次性删除所有容器记录docker rmi `docker images -aq` # 一次性删除所有本地的镜像记录 3.1 启动容器的两种方式 容器是运行应用程序的,所以必须得先有一个操作系统为基础 1. 基于镜像新建一个容器并启动 # 1. 后台运行一个dockerdocker run -d centos /bin/sh -c "while true;do echo 正在运行; sleep 1;done" # -d 后台运行容器 # /bin/sh 指定使用centos的bash解释器 # -c 运行一段shell命令 # "while true;do echo 正在运行; sleep 1;done" 在linux后台,每秒中打印一次正在运行docker ps # 检查容器进程docker logs -f 容器id/名称 # 不间断打印容器的日志信息 docker stop centos # 停止容器# 2. 启动一个bash终端,允许用户进行交互docker run --name mydocker -it centos /bin/bash # --name 给容器定义一个名称 # -i 让容器的标准输入保持打开 # -t 让Docker分配一个伪终端,并绑定到容器的标准输入上 # /bin/bash 指定docker容器,用shell解释器交互 当利用docker run来创建容器时,Docker在后台运行的步骤如下: # 1. 检查本地是否存在指定的镜像,不存在就从公有仓库下载 # 2. 利用镜像创建并启动一个容器 # 3. 分配一个文件系统,并在只读的镜像层外面挂在一层可读写层 # 4. 从宿主主机配置的网桥接口中桥接一个虚拟接口到容器中去 # 5. 从地址池配置一个ip地址给容器 # 6. 执行用户指定的应用程序 # 7. 执行完毕后容器被终止 2.将一个终止状态(stopped)的容器重新启动 [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 # 再启动这个容器ee9[root@localhost ~]# docker exec -it ee9 /bin/bash # 进入容器交互式界面[root@ee92fcf6f32d /]# # 注意看用户名,已经变成容器用户名 3.2提交创建自定义镜像 # 1.我们进入交互式的centos容器中,发现没有vim命令 docker run -it centos# 2.在当前容器中,安装一个vim yum install -y vim# 3.安装好vim之后,exit退出容器 exit# 4.查看刚才安装好vim的容器记录 docker container ls -a# 5.提交这个容器,创建新的image docker commit 059fdea031ba chaoyu/centos-vim# 6.查看镜像文件 docker imagesREPOSITORY TAG IMAGE ID CREATED SIZEchaoyu/centos-vim latest fd2685ae25fe 5 minutes ago 348MB 3.3外部访问容器 容器中可以运行网络应用,但是要让外部也可以访问这些应用,可以通过-p或-P参数指定端口映射。 docker run -d -P training/webapp python app.py # -P 参数会随机映射端口到容器开放的网络端口# 检查映射的端口docker ps -lCONTAINER ID IMAGE COMMAND 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 mapping container port 5000 # View container log information docker logs-f cfd # # continuous display log# can also specify the mapping port docker run-d-p 9000cfd 5000 training/webapp python app.py with the-p parameter

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

(if the access fails, check your firewall and the security group of the CVM)

4.0 customized image using dockerfile

The image is the basis of the container. Each time docker run is executed, which image is specified as the basis for the container to run. In our previous examples, we used images from docker hub. Using these images directly can only meet certain needs. When images can not meet our needs, we have to customize these images.

The customization of the image is to customize the configuration and files added by each layer. If you can modify, install, build, and operate commands for each layer into a script, build and customize the image with a script, the script is dockerfile.

Dockerfile is a text file that contains Instruction, each of which builds a layer, so 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, try to use official image as base imageFROM centos # use base imageFROM ubuntu:14.04 # base imageLABEL version= "1.0" # container meta-information, help information, Metadata with tag, similar to code comments LABEL maintainer= "yc_uuu@163.com" # for complex RUN commands, avoid useless layering, multiple commands use backslash line feeds, synthesize a command! RUN yum update & & yum install-y vim\ Python-dev # backslash wrap RUN / bin/bash-c "source $HOME/.bashrc;echo $HOME" WORKDIR / root # is equivalent to linux's cd command, change the directory and try to use the absolute path! Do not use RUN cdWORKDIR / test # if not automatically create WORKDIR demo # and then enter the demo folder RUN pwd # print result should be / test/demoADD and COPY ADD hello / # add the local hello executable file to the image, copy the local hello executable file to the image / directory ADD test.tar.gz / # add to the root directory and extract WORKDIR / rootADD hello test/ # enter / root/ add hello executable command to the test directory That is, / root/test/hello an absolute path COPY hello test/ # is equivalent to the above ADD effects ADD and COPY-priority to use the COPY command-ADD in addition to the COPY function to add remote files / directories using curl or wgetENV # environment variables, as far as possible to increase maintainability using ENV ENV MYSQL_VERSION 5.6 # set a mysql constant RUN yum install-y mysql-server= "${MYSQL_VERSION}"

Advance is just (understand)

VOLUME and EXPOSE

Storage and networking

RUN and CMD and ENTRYPOINT

RUN: execute the command and create a new Image Layer

CMD: sets the commands and parameters that are executed by default after the container starts

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"]

To run a command in shell format, the $name instruction is read, while the exec format only executes a command, not a shell instruction

Cat Dockerfile

FROM centos

ENV name Docker

ENTRYPOINT ["/ bin/echo", "hello $name"] # this only executes the echo command and cannot read the shell variable

ENTRYPOINT ["/ bin/bash", "- c", "echo hello $name"]

CMD

Commands that are executed by default when the container starts

If docker run specifies another command (docker run-it [image] / bin/bash), the CMD command is ignored

If you define multiple CMD, only the last one executes

ENTRYPOINT

Let the container run as an application or service

It will not be ignored and will be carried out.

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.0 release to warehouse

1Docker hub shared image release

Docker provides a warehouse docker hub similar to github

Official website (need to register for use)

After  # registers docker id, log in to dockerhub docker login# in linux. Make sure that the tag of image is the account name. If the image name is incorrect, you need to change the tag docker tag chaoyu/centos-vim peng104/centos-vim # syntax is: docker tag warehouse name peng104/ warehouse name # push docker image to dockerhub docker push peng104/centps-cmd-exec:latest# to check the image in dockerhub # delete the local image first Then test and download the pull image file docker pull peng104/centos-entrypoint-exec

2, private warehouse

Docker hub is public, and others can download it, so it is not secure, so you can also use the private warehouse provided by docker registry officially.

Explain the usage to me in detail.

# 1. Download an official private repository image of docker docker pull registry# 2. Run a docker private container warehouse docker run-d-p 5000 opt/data/registry:/var/lib/registry registry 5000-v / opt/data/registry:/var/lib/registry registry-d backend run-p port maps 5000 of the host: 5000-v data volumes in the container mount the host's / opt/data/registry:/var/lib/registry registry image name / var/lib/registry stores the private warehouse location # Docker does not allow images to be pushed in non-HTTPS mode by default. We can remove this restriction # 3 through the configuration option of Docker. Modify the configuration file of docker to make it support http mode. Upload private image vim / etc/docker/daemon.json # and write the following content {"registry-mirrors": ["http://f1361db2.m.daocloud.io"]," insecure-registries ": [" 192.168.11.37 http 5000 "]} # 4. Modify docker's service configuration file vim / lib/systemd/system/docker.service# to find the code area block [service] and write the following parameter [Service] EnvironmentFile=-/etc/docker/daemon.json# 5. Reload the docker service systemctl daemon-reload# 6. Restart the docker service systemctl restart docker # Note: restart the docker service and all containers will die # 7. Modify the tag tag of the local image and push docker tag docker.io/peng104/hello-world-docker 192.168.11.37:5000/peng-hello # browser to your private repository to visit http://192.168.119.10:5000/v2/_catalog to view the repository # 8. Download the demo of the mirror docker pull 192.168.11.37:5000/peng-hello6.0 instance of the private repository

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

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

# 1. Prepare app.py 's 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= "Wen Erxin" RUN pip install flask COPY app.py / app/ WORKDIR / app EXPOSE 8080 CMD ["python", "app.py"] # 3. Build the mirror image, find the Dockerfile of the current directory, and start building docker build-t peng104/flask-hello-docker. # 4. Check out the created images docker image ls# 5. Launch this flask-hello-docker container and map a port for external access to docker run-d-p 808080 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-flaskweb docker push 192.168.11.37:5000/peng-flaskweb

The above is the whole content of this article, I hope it will be helpful to your study, and I also hope that you will support it.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report