Docker basis

What is a Docker

Docker uses Go language launched by Google for development and implementation, and is based on cgroup, Namespace of Linux kernel and Union FS of AUFS class to encapsulate and isolate processes, which is a virtualization technology at the level of operating system. Since a quarantined process is independent of the host and other quarantined processes, it is also called a container.

Docker has further encapsulation on the basis of containers, from file system, network interconnection to process isolation and so on, which greatly simplifies the creation and maintenance of containers. Docker technology is lighter and faster than virtual machine technology.

The most important thing to remember is that Dokcer is actually a normal process on the host machine, which is the biggest difference between Dokcer and traditional virtualization technologies.

Why Docker

The most important thing to use Docker is that Docker can ensure the consistency of the operating environment, and there will not be various problems caused by inconsistent environment configuration in development, testing and production. One configuration can be run for many times. With Docker, applications can be packaged, tested, and deployed faster, and the cycle from writing to deploying running code can be reduced.

Docker installation

  • Docker requires a CentOS kernel version later than 3.10. Check the prerequisites on this page to verify that your CentOS version supports Docker.

    uname -r

  • Update YUM to the latest version

    yum update
  • Uninstall old Versions of Docker (if available)

    yum remove docker docker-common docker-selinux docker-engine

    This command only uninstalls the Docker itself, but does not delete Docker stored files, such as images, containers, volumes, and network files. These files are stored in the /var/lib/docker directory and need to be deleted manually.
  • Check yum repository to see if there is a Docker

    ll /etc/yum.repos.d/



    If the manufacturer’s server (Ali Cloud, Tencent Cloud) will generally have docker warehouse, if the virtual machine or company’s server will basically not.
  • Install package, yum-util provides yum-config-manager functionality, the other two are dependent on devicemapper driver

    yum install -y yum-utils device-mapper-persistent-data lvm2
  • Install the warehouse

    yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo

  • View the Docker version

    yum list docker-ce --showduplicates | sort -r

  • Install the docker

    yum install docker-ce

    The above statement is to install the latest version of Docker, you can also throughyum install docker-ce-<VERSION>Install the specified version
  • Start the docker

    systemctl start docker
  • Verify that the installation is correct

    dokcer run hello-world

Docker important commands

Image correlation

  • Search the mirrordocker search

    Such asdocker search nginxDocker searches the Docker Hub for mirror repositories that contain the keyword “nginx”

  • Download mirrordocker pull

    Such asdocker pull nginxDocker will download the image containing the latest version of “nginx” in Docker Hub

    Of course you can use itDocker pull reg.jianzh5.com/nginx:1.7.9Download the nginx image for the specified repository address label
  • List the mirrordocker images

  • Remove the mirrordocker rmi

    Such asdocker rmi hello-worldDelete what we just downloadedhello-worldThe mirror
  • Build the mirrordocker build

    Build the image from Dockerfile, which we’ll cover in more detail in a moment.

The container related

  • Creating a Boot Imagedocker run

    This command is our most commonly used command and uses the following options

    ① -d: indicates background running

    ② -p option (in uppercase) : indicates random port mapping

    ③ -p option (lowercase) : specifies the port mapping.The host port is preceded by the container port, such asdocker run nginx -p 8080:80, map port 80 of the container to port 8080 of the host, and then uselocalhost:8080You can view the nginx welcome page in the container

    ④ -v option: Mount the host directory.The host directory is preceded by the container directory, such asdocker run -d -p 80:80 -v /dockerData/nginx/conf/nginx.conf:/etc/nginx/nginx.conf nginxMounted to the host/dockerData/nginx/conf/nginx.confFile so that the host can pairnginxIf the host directory does not exist, it will be created automatically.

    ⑤–rm: Stop the container and delete it directlydocker run -d -p 80:80 --rm nginx

    ⑥–name: give the container a name, otherwise a long list of custom names will appeardocker run -name niginx -d -p 80:80 - nginx
  • List the containerdocker ps

    This command lists the currently running containers, using-aList all containers after the parameter (including stopped ones)

  • Stop the containerdocker stop

    docker stop 5d034c6ea010This is followed by the container ID, or you can use the container name
  • Start the stopped containerdocker start

    docker runCreate a new container and start it,docker startIs a container for starting and stopping, such asdocker start 5d034c6ea010
  • Restart the containerdocker restart

    This command is executed firstdocker stop, and then executedocker start, such asdocker restart 5d034c6ea010
  • Into the containerDocker exec -it Container ID /bin/bash

    Such asdocker exec -it 5d034c6ea010 /bin/bash, which is equivalent to accessing the operating system of the container itself
  • Remove the containerdocker rm

    Such asdocker rm 5d034c6ea010The container ID is followed by the need to stop the container before deleting it
  • Data copiesdocker cp

    This command is used to copy data between a container and a host, for exampledocker cp 5d034c6ea010:/etc/nginx/nginx.conf /dockerData/nginx/conf/nginx.confCopy the container directory file to the specified location on the host. The container ID can be replaced by the container name.

Command of actual combat

If we need an Nginx container and need to modify the nginx configuration file and the default home page directly on the host machine, we can see the container’s nginx logs in real time on the host machine. We can do it step by step as follows.

  • Start the container with the –rm argument for easy deletion

    docker run -d -p 8081:80 --name nginx --rm nginx
  • Access the container and view the directory addresses of configuration files, project files, and log files in the container

    docker exec -it 9123b67e428e /bin/bash
  • Export the configuration file of a container

    docker cp nginx:/etc/nginx/nginx.conf /dockerData/nginx/conf/nginx.confExport the configuration file nginx.conf

    docker cp nginx:/etc/nginx/conf.d /dockerData/nginx/conf/conf.dExport the configuration directory conf.d
  • Stop the containerdocker stop 9123b67e428eThe container will be deleted automatically because the –rm parameter is added
  • Run the following command to start the container to mount the directory

    docker run -d -p 8081:80 --name nginx \ -v /dockerData/nginx/conf/nginx.conf:/etc/nginx/nginx.conf \ -v /dockerData/nginx/conf/conf.d:/etc/nginx/conf.d \ -v /dockerData/nginx/www:/usr/share/nginx/html \ -v /dockerData/nginx/logs:/var/log/nginx nginxCopy the code
  • Access Server Addresshttp://192.168.136.129:8081/



    Access error, this time to enter the host machine log directory/dockerData/nginx/logsSee the log

    2019/11/23 10:08:11 [error] 6#6: *1 directory index of “/usr/share/nginx/html/” is forbidden, client: Server: localhost, request: “GET/HTTP/1.1”, host: “192.168.136.129:8081”

    because/usr/share/nginx/html/It was mounted to the server/dockerData/nginx/wwwUnder the directory, the original welcome page is indockerData/nginx/wwwI don’t have any, so I’m going to get an error, so I’m going to make a random one here.
  • Create the default home page

    Open the project file
    cd /dockerData/nginx/www
    Create and edit files using vim
    vi index.html
    # At this point we will enter the Vim screen, press I to insert, then type
    <h1 align="center">Hello,Welcome to Docker World</h1>
    # After entering, press Esc and enter :wqCopy the code
  • Visit the browser address again

Dockerfile

We can build an image using Dockfile and run it directly in docker. Dockerfile file is a text file, which contains all the commands required to build the image. First of all, let’s look at the Dockerfile file in several important instructions.

Instruction,

  • FROM

    Select a base image and modify it, such as building a SpringBoot project image, to select the Java base image, FROM as the first instruction in the Dockerfile

    Such as:FROM openjdk:8-jdk-alpineThe base image should be alpine if possible, as the base image built with the Alpline version will be much smaller.
  • The RUN RUN command is used to RUN commands. It has the following two formats:

    • The shell format: RUN < command >, as if the command were typed directly on the command line.RUN echo '<h1>Hello, Docker! </h1>' > /usr/share/nginx/html/index.html
    • Exec format: RUN [” executable “, “parameter 1″,” parameter 2″], which is more like the format in function calls.
  • CMD

    This directive is used to specify the default start command for the container main process.

The CMD command format is similar to RUN in that it has two formats

* shellFormat: CMD < command >* exec format:CMD ["Executable file".Parameters of "1"."Parameter 2". ]* Parameter list format:CMD [Parameters of "1"."Parameter 2". ] . After specifying the ENTRYPOINT directive, use CMD to specify the specific parameters.Copy the code
  • ENTRYPOINT The format of ENTRYPOINT is the same as that of the RUN command, including exec and shell formats. The purpose of ENTRYPOINT, like CMD, is to specify the container launcher and parameters. ENTRYPOINT can also be substituted at runtime, but is a little more verbose than CMD and is specified by the ENTRYPOINT parameter of Docker Run. When ENTRYPOINT is specified, the meaning of CMD is changed. Instead of running the command directly, the content of CMD is passed to the ENTRYPOINT command as a parameter. In other words, the actual execution will become:

    <ENTRYPOINT> "<CMD>"Copy the code
  • COPY & ADD

    Both instructions are copy files, which copy files/directories from the < source path > in the build context directory to the < destination path > location in the new layer image. Such as:COPY demo-test.jar app.jarADD demo-test.jar app.jar.

    ADDInstruction thanCOPYAdvanced, you can specify a URL, so that the Docker engine will download the URL file, ifADDAnd then there’s atarThe Dokcer engine also decompresses the file.

    We use it whenever possible when building the imageCOPYBecause theCOPYIs just copying files, andADDContains more complex functionality, and its behavior is not always clear.
  • EXPOSE

    Declare the container’s runtime port. This is only a declaration, and the application does not enable the port at runtime because of this declaration. Writing such a declaration in a Dockerfile has two benefits. One is to help the mirror user understand the daemon port of the mirror service to facilitate the configuration of the mapping. Another use is when random port mapping is used at run time, i.edocker run -PAutomatically maps the EXPOSE ports randomly.

    willEXPOSEAnd used at run time-p < host port >:< container port >Distinguish.-p, is to map host port and container port, in other words, is to expose the corresponding port service of the container to external access, andEXPOSESimply declaring what port the container intends to use does not automatically map ports to the host.
  • ENV is a very simple directive to set environment variables that can be used directly by any subsequent directive, such as RUN, or by any application at runtime. It is available in the following two formats:

    • ENV <key> <value>
    • ENV <key1>=<value1> <key2>=<value2>...
  • VOLUME

    This directive enables persistent storage for a directory in a container that can be used by the container itself or shared with other containers. This directive can be used in a Dockerfile when the application in the container needs to persist data. Such asVOLUME /tmp

    The/TMP directory is automatically mounted as an anonymous volume at runtime, and any information written to/TMP is not recorded in the container storage layer, thus ensuring the stateless container storage layer. Of course, the runtime can override this mount setting. Such as:

    docker run -d -v mydata:/tmp xxxx
  • LABEL You can add labels to your images, organize them, record version descriptions, or other reasons, add lines starting with LABEL, and one or more key-value pairs for each LABEL. As follows:

    LABEL version="1.0"
    LABEL description="test"Copy the code

Dockerfile of actual combat

Let’s take a simple SpringBoot project as an example to build an image based on a SpringBoot application. The function is very simple. It only provides a SAY interface. When entering this method, a line of logs is printed and written to a log file.

@SpringBootApplication @RestController @Log4j2 public class DockerApplication { public static void main(String[] args) {  SpringApplication.run(DockerApplication.class, args); } @GetMapping("/say")
    public String say(){
        log.info("get say request...");
        return "Hello,Java Newsletter"; }}Copy the code

We use Maven to package it into a JAR file, place it in a separate folder, and then follow the steps below to build the image and execute it

  • Create a Dockerfile file in the current folder with the following contents:

    FROM openjdk:8-jdk-alpine
    The/TMP directory in the container will be the persistent directory
    VOLUME /tmp
    # Exposed port
    EXPOSE 8080
    # copy file
    COPY docker-demo.jar app.jar
    Configure the commands to be executed after the container is started
    ENTRYPOINT ["java"."-Djava.security.egd=file:/dev/./urandom"."-jar"."/app.jar"]Copy the code
  • Run the following command to build the image

    Docker Built-in Springboot: V1.0.



    -t Specifies the image name and version number.At the end.
  • Viewing an Image File

  • Run the built image

    Docker run -v /app/docker/logs:/logs -p 8080:8080 --rm --name Springboot Springboot :v1.0
  • Browser accesshttp://192.168.136.129:8080/say

  • View logs on the host in real time

    tail -100f /app/docker/logs/docker-demo-info.log

Link: https://segmentfault.com/a/1190000021098609

Source: Si Fu