Follow the wechat official account: CodingTechWork, learn and progress together.

The introduction

For the deployment of upper cloud and K8S, containerization is inevitably needed. In the face of containerization, Docker is inevitably used, and the production of Docker image has to be mentioned. This article mainly studies and summarizes the Dockerfile declaration details and common docker command.

Dockerfile

Document overview

Dockerfile is a text file used to customize the image, which contains multiple instructions, software dependencies and instructions required to build the image.

Instruction,

FROM

Specify base image

Format: FROM <image> FROM <image>:<tag> FROM <image>@<digest> Tag and digest This parameter is optional. If this parameter is not specified, the latest version is used. Digest indicates the addressable identifier of an image of V2 or later. Example: FROM centos:7Copy the code

MAINTAINER

Maintainer information

Format: MAINTAINER <name> Description: Name is MAINTAINER information, which can be customized as name and email address.  MAINTAINER andya MAINTAINER [email protected] MAINTAINER andya <[email protected]>Copy the code

ENV

Setting environment Variables

ENV <key> <value> ENV <key>=<value>... ENV <key>=<value> ENV <key>=<value> You can set multiple variables. If you encounter Spaces, use \ to escape them or "" to identify them. Example: ENV addressInfo Suzhou xiancheng ENV addressCity=suzhouCopy the code

VOLUME

Specify the persistent directory as an anonymous volume to prevent runtime users from mounting directories saved by dynamic files as volumes.

Format: VOLUME ["<dir01>", "<dir02>",... VOLUME <dir> Description: Specifies a persistent directory where the VOLUME can reside in one or more containers example: VOLUME ["/data/data01", "/data/data02"] VOLUME /dataCopy the code

COPY

Copy function, similar to ADD, but cannot automatically decompress files, and cannot access network resources

COPY [--chown=<user>:<group>] < SRC >... < dest > COPY [- chown = < user >, < group >] [" < SRC >, "... "< dest >"] description: 1) [- chown = < user >, < group >] for optional parameters, change file belongs and belongs to the group. 2) If the destination path does not exist, it is automatically created. Example: COPY demo.tar demo01.tar COPY --chown=user01:group01 demo.tar demo02.tarCopy the code

ADD

COPY function, similar to COPY, but will automatically decompress tar and other compressed files.

Format: ADD <sourceDir1>... <dest> ADD ["<sourceDir1>",... "<targetDir>"] 2) Basic functions and formats are the same as COPY. Example: ADD demo.jar /app.jar ADD *. Sh /shell ADD dir01 relativeDir/ ADD dir02 /absoluteDirCopy the code

RUN

Execute the command.

Format:	#The shell to perform
	RUN <command>
	# execperform1) The command of the Dockerfile creates a new layer on the docker every time it executes, so incorporate RUN as much as possible. 2) The exec execution format is a JSON array and must be described in double quotes. 3) Exec format does not call command line shell, shell format or path is required. Such as the RUN [" echo ", "$HOME"] is not effective, you need to use the RUN [" sh ", "- c", "echo $HOME"]. RUN yum install wget \ && tar -xvf demo.tar && chmod -r 777 /shell RUN /bin/bash -c 'source $HOME/.bashrc; \ echo $HOME' RUN /bin/bash -c 'source $HOME/.bashrc; echo $HOME' RUN ["/bin/bash", "-c", "echo hello"]Copy the code

EXPOSE

Specifies the port to interact with the outside world.

EXPOSE <port> [<port>/<protocol>...] Description: 1) The default TCP protocol. 2) EXPOSE is not the real release of the port, it needs to be published in docker run using -p, such as Docker run 80:80/ TCP -p 80:80/udp. Example: EXPOSE 8080 EXPOSE 10001/ TCP 10002/ UDPCopy the code

WROKDIR

Specify a working directory, similar to the CD command. The container root directory is/if not set by default

Description: 1) After setting the working directory, RUN, CMD, ENTRYPOINT, COPY, ADD and other commands after Dockerfile are RUN under this directory. 2) If it does not exist, it will be created automatically. 3) When docker run, you can override it with -wor --workdir. 4) It can be used multiple times in Dockerfile. When relative paths are used, they will be spliced into absolute paths based on the first one. Example:	#The working directory is the root directory /
	WROKDIR /
	#The working directory is /c
	WROKDIR c
Copy the code

ENTRYPOINT

  

Format:	# execformat
	ENTRYPOINT ["executable", "param1", "param2"]
	#Shell formatENTRYPOINT command param1 Param2 Description: 1) Shell format will reject any CMD or run command line parameters, will start with /bin/sh -c, only the exec format can use -- ENTRYPOINT in the command line. 2) Only the last ENTRYPOINT in the Dockerfile is valid. If ENTRYPOINT ["sh", "-c", "echo $HOME"] is set to ENTRYPOINT ["sh", "-c", "echo $HOME"]	# execformat
	ENTRYPOINT ["top", "-b"]
	CMD ["-c"]
	
	#Shell format
	ENTRYPOINT exec top -b
Copy the code

CMD

The primary purpose of CMD is to provide default values for an executing container. Includes executable files/programs.

Format:	# exec form, this is the preferred form
	CMD ["executable","param1","param2"] 
	# shell form
	CMD command param1 param2 
	# as default parameters to ENTRYPOINTCMD ["param1","param2"] description: 1) If there are multiple CMD in Dockerfile, only the last CMD is valid. 2) When CMD provides default parameters for ENTRYPOINT, both CMD and ENTRYPOINT need to be declared in JSON array format. CMD ["sh", "-c", "echo $HOME"]; CMD ["sh", "-c", "echo $HOME"]; CMD echo $HOME 4) Unlike RUN, RUN is the command executed when docker build builds docker image, which actually runs a command and submits the result of the RUN. CMD does not execute anything during build time and declares the expected commands for the image when Docker run executes the docker image to build the container. The ENTRYPOINT command is always executed and is generally used to execute scripts. Example:	# execformat
	CMD ["/usr/bin/wc","--help"]
	
	#Shell format
	CMD echo "This is a test." | wc -
	
Copy the code

LABEL

To add metadata to an image, LABEL is a bunch of key-value pairs.

Format: LABEL < key > = < value > < key > = < value > < key > = < value >... Description: An image can have one or more labels, and multiple labels can be set on a line, separated by Spaces. It is recommended to specify multiple LABEL pairs using a single LABEL directive. Example: LABEL "com.example.vendor"="ACME Incorporated" LABEL com.example.label-with-value="foo" LABEL version="1.0" LABEL description="This text illustrates \ that label-values can span multiple lines."Copy the code

USER

Set the user name (or UID) and optional user group (or GID) for running the image and the RUN, CMD, and ENTRYPOINT commands.

Format: USER < USER >[:<group>] USER <UID>[:<GID>] Description: 1) You can specify a USER name, a group name, or a UID or GID. 2) If a user group is specified for a user, the user has only the specified group relationship, and other group membership relationships are ignored. Example: USER userACopy the code

ARG

The user specifies the variables passed to the Build build runtime

ARG <name>[=<default value>] Description: 1) In the docker build command, the --build-arg <varname>=<value> is specified. If the ARG declaration does not exist in the Dockerfile, the warning is thrown. Example: FROM busybox ARG user1 ARG buildno	
	#Setting defaults
	FROM busybox
	ARG user1=someuser
	ARG buildno=1
Copy the code

RUN, ENTRYPOINT and CMD are different

  1. RUN is the command executed when docker builds docker images, actually running a command and submitting the results.
  2. CMD does not execute anything during Docker build time. When Docker run executes the docker image build container, it declares the expected commands for the image. When there are more than one CMD, only the last one is executed. When there is ENTRYPOINT, the CMD command is either used as a parameter (the exec format provides a default value) or overwritten. If ENTRYPOINT does not exist, you can dynamically overwrite or run commands.
  3. The ENTRYPOINT command is always executed and is generally used to execute scripts. ENTRYPOINT commands in shell format do not execute commands that are either CMD commands in Dockerfile or added in Docker run. An ENTRYPOINT command in the exec format, a command added to a CMD command, or a docker run command, will be executed as an ENTRYPOINT parameter.

Template sample

The base image Dockerfile

Write a Dockerfile for the base image

RUN yum install -y tar \ && yum install -y Java -1.8. 0-openjdk* \
    && yum install -y unzip \
    && yum install -y less \
    && yum install -y vi \
    && cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \
    && echo 'Asia/Shanghai'> /etc/timezone # ENV LANG en_us.utf -8
ENV LANGUAGE en_US:en
ENV LC_ALL en_US.UTF-8
Copy the code

Making basic images

$Docker build -t centos-BASIC :v1.0
Copy the code

Service image Dockerfile

With the basic image above, declare FROM centos-BASIC :v1.0 in the service Dockerfile.

# base images FROM centos-basic:v1. 0# Maintainer: Maintainer information Maintainer andya # env config: Environment variable Settings env JAVA_HOME /usr/local/jdk18.. 0 _170ENV PATH $JAVA_HOME/bin:$PATH # volume volume/NFS # copy: COPY --chown=userA:groupA demo.tar demo01.tar # add :groupA demo.tar Copy a directory or file (automatically decompress the tar package) ADD config /config ADD SQL/SQL ADD micro-service01-1.0Jar /app.jar # run: Run chmod -r777/ SQL # run: Run the command to change the access time of the file to the current time without changing the content of the file run bash -c'touch /app.jar'# expose: Exposes the port expose8001WROKDIR / # entrypoint: set the first command and parameter to run when the container is started."java"."-Djava.security.egd=file:/dev/./urandom"."-jar"."/app.jar"]
Copy the code

mirror

  1. Docker build build mirror docker build -t mirror warehouse IP: port/service/micro01: v1.0. Note the end of the command.

  2. Docker Login Login to the image repository DOCker login IP address of the image repository :port

  3. Docker images inspection docker imgaes | grep micro01

  4. Mirror mirror to mirror the warehouse docker docker push push push warehouse IP: port/service/micro01: v1.0

  5. Docker save Save image tar package docker save Container ID > name.tar

Common docker commands

Run the container

  1. Docker load Loading image docker load -i name. tar

  2. Docker images fuzzy view mirror iddocker images | grep “XXX”

  3. Docker run starts the container docker run image_id to get container_id

  4. Docker logs -f

  5. Docker exec -it

    /bin/bash

Other commands

  1. Docker cp


    :/dir01/dir02

  2. Docker restart

  3. Docker commit


    :


Usage: docker [OPTIONS] COMMAND A self-sufficient runtime for containers Options: --config string Location of client config files (default "/root/.docker") -D, --debug Enable debug mode -H, --host list Daemon socket(s) to connect to -l, --log-level string Set the logging level ("debug"|"info"|"warn"|"error"|"fatal") (default "info") --tls Use TLS; implied by --tlsverify --tlscacert string Trust certs signed only by this CA (default "/root/.docker/ca.pem") --tlscert string Path to TLS certificate file (default "/root/.docker/cert.pem") --tlskey string Path to TLS key file (default "/root/.docker/key.pem") --tlsverify Use TLS and verify the remote -v, --version Print version information and quit Management Commands: builder Manage builds config Manage Docker configs container Manage containers engine Manage the docker engine image Manage images network Manage networks node Manage Swarm nodes plugin Manage plugins secret Manage Docker secrets service  Manage services stack Manage Docker stacks swarm Manage Swarm system Manage Docker trust Manage trust on Docker images volume Manage volumes Commands: attach Attach local standard input, output, and error streams to a running container build Build an image from a Dockerfile commit Create a new image from a container's changes cp Copy files/folders between a container and the local filesystem create Create a new container diff Inspect changes to files or directories on a container's filesystem events Get real time events from the server exec Run a command in a running container export Export a container's filesystem as a tar archive history Show the history of an image images List images import Import the contents from a tarball to create a filesystem image info Display system-wide information inspect Return low-level information on Docker objects kill Kill one or more running containers load Load an image from a tar archive or STDIN login Log in to a Docker registry logout Log out from a Docker  registry logs Fetch the logs of a container pause Pause all processes within one or more containers port List port mappings or a specific mapping for the container ps List containers pull Pull an image or a repository from a registry push Push an image or a repository to a registry rename Rename a container restart Restart one or more containers rm Remove one or more containers rmi Remove one or more images run Run a command in a new container save Save one or more images to a tar archive (streamed to STDOUT by default) search Search the Docker Hub for images start Start one or more stopped containers stats Display a live stream of container(s) resource usage statistics stop Stop one or more running containers tag Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE top Display the running processes of a container unpause Unpause all processes within one or more containers update Update configuration of one or more containers version Show the Docker version information wait Block until one or more containers stop, then print their exit codes Run 'docker COMMAND --help' for more information on a command.Copy the code

Refer to docs.docker.com/engine/refe…