Build images based on Dockerfile

1. Dockerfile:source code for building Docker file

  • Docker can automatically build images by reading instructions from Dockerfile files
  • The Dockerfile is a text document that contains all the commands that the user can invoke on the command line to assemble the image
  • Using the Docker build command, users can automatically create images by executing several commands one at a time

2. Dockerfile syntax:

  • The first line must start with #
  • It is case insensitive, but the convention is to use all caps.
  • Docker runs the commands in the Dockerfile in order
  • The first directive must be “FROM” to specify the base image to build FROM

3. Environment variables (declared using ENV statements) can also be used in some directives as variables interpreted by dockerfiles.

  • In a Dockerfile, the environment variable can be
    v a r i a b l e n a m e or Variable_name or
    {variable_name}

    • The ${variable_name} syntax also supports some standard Bash modifiers
    • ${variable:-word} indicates that if a variable is set, the result will be that value. If the variable is not set, the result is Word.
    • ${variable:+word} means that if a variable is set, then the result will be word, otherwise the result will be an empty string.

4.. dockerignore file

  • If you have subdirectories in your working directory that you don’t want to reference, you can hide files with.dockerignore.
  • .dockerignore specifies files not to be referenced.

4. FROM

  • If the specified image does not exist, it will be downloaded from Docker Hub first
  • Grammar:
    • FROM [AS] #[AS] : alias
    • FROM [:] [AS] #tag
    • FROM [AS] #digest: Hash code

5. Docker build command

  • Build an image from a Dockerfile
  • Options
    • -t, –tag list Name and optionally a tag in the ‘name:tag’ format
    • -m, –memory bytes Memory limit
    • -c, –cpu-shares int CPU shares (relative weight)

6. LABEL

  • You can add the metadata of the image file multiple times. You are strongly advised to use only one command because each command will add one layer. The more layers, the lower the operating efficiency.
  • Syntax format:
    • LABEL = = =… You can specify multiple labels
    • LABEL # specifies only one LABEL, and anything after the first space is treated as a value

The example only modifies FROM and LABEL of one mirror

  1. Create the working directory image
[root@docker ~]# mkdir image
[root@docker ~]# cd image
Copy the code
  1. Edit the Dockerfile file and add the following:
[root@docker image]# vim Dockerfile
#Test Image Build
FROM alpine
LABEL maintainer="lixinkuan <[email protected]>"
Copy the code
  1. Making a mirror:
[root@docker image]# Docker build. Sending build context to docker daemon 2.048KB Step 1/2: FROM alpine ---> 3fd9065eaf02 Step 2/2 : LABEL maintainer="lixinkuan <[email protected]>" ---> Running in e1ce9acfc453 Removing intermediate container e1ce9acfc453 ---> 1deb17a1af32 Successfully built 1deb17a1af32Copy the code
  1. View: Empty REPOSITORY and TAG indicates the newly created image file
[root@docker image]# docker image ls REPOSITORY TAG IMAGE ID CREATED SIZE <none> <none> 1deb17a1af32 5 minutes ago 4.15MB Nginx Latest CD5239A0906a 3 weeks ago 109MB Busybox Latest 8c811b4aEC35 5 Weeks ago 1.15MB HTTPD 2.4fb2f3851a971 8 Weeks ago 178MB Alpine Latest 3FD9065eAF02 5 months ago 4.15MBCopy the code
  • When creating a Docker image, you can specify the tag using -t followed by ‘name:tag’
  • You can also add labels by using the following command:
[root@docker image]# docker image tag 1deb17a1af32 alpine:lxk
[root@docker image]# docker images
REPOSITORY                  TAG                 IMAGE ID            CREATED             SIZE
alpine                      lxk                 1deb17a1af32        5 minutes ago       4.41MB

Copy the code

7. COPY

  • Used to copy files from the Docker host to the new image file created
  • Grammar:
    • COPY …
    • COPY [“”,… “”]
      • : Indicates the source file or directory to be copied. Wildcard characters are supported
      • : destination path, that is, the file system path of the image being created; You are advised to use the absolute path. Otherwise, the start path of COPY is WORKDIR
      • Note: The second format is usually used when there are whitespace characters in the path
  • File replication guidelines:
    • Must be a path in the build context, not a file in its parent directory
    • If it is a directory, its internal files or subdirectories are recursively copied, but the directory itself is not copied
    • If more than one is specified, or a wildcard is used, it must be a directory and must end with a /
    • If it does not exist, it will be created automatically, including the parent directory path

Example: Copy a single file

  1. Add content for index.html in the image directory:
[root@docker image]# echo '<h1>hello,docker! </h1>' > index.htmlCopy the code
  1. Edit the Dockerfile file and add the following statement:
[root@docker image]# vim Dockerfile 
#Test Image Build
FROM alpine
LABEL maintainer="lixinkuan <[email protected]>"

COPY index.html /var/www/html/
Copy the code
  1. Start a container with Alpine and see if there is a /var/www/html directory
[root@docker image]# docker run -it --name a1 alpine / # ps aux PID USER TIME COMMAND 1 root 0:00 /bin/sh 7 root 0:00 ps  aux / # ls /var/www/html ls: /var/www/html: No such file or directoryCopy the code
  1. To make the mirror
[root@docker image]# docker build -t cpindex:latest. Sending build context to docker daemon 3.072kB Step 1: FROM alpine ---> 3fd9065eaf02 Step 2/3 : LABEL maintainer="lixinkuan <[email protected]>" ---> Running in 9d96e0655a82 Removing intermediate container 9d96e0655a82 ---> 56049399eb78 Step 3/3 : COPY index.html /var/www/html/ ---> bace8e55c97b Successfully built bace8e55c97b Successfully tagged cpindex:latestCopy the code
  1. View the created image:
[root@docker image]# docker image ls REPOSITORY TAG IMAGE ID CREATED SIZE cpindex latest bace8e55c97b 52 seconds ago 4.15 MBCopy the code
  1. Start a container with the created image and check to see if the file exists
[root@docker image]# docker run --name copyfile -it --rm cpindex:latest / # ls /var/www/html index.html / # cat /var/www/html/index.html <h1>hello,docker! </h1>Copy the code

Example: Copy multiple files in a directory to a directory

  1. Copy a directory to /root/image
[root@docker image]# cp -r /etc/default/ ./ 
[root@docker image]# ls
default  Dockerfile  index.html
[root@docker image]# ls default/
grub  kibana  nss  useradd
Copy the code
  1. Change the Dockerfile file to the following:
#Test Image Build
FROM alpine
LABEL maintainer="lixinkuan <[email protected]>"

COPY default /tmp/
Copy the code
  1. Making a mirror:
[root@docker image]# docker build -t cpdir:latest./ Sending build context to docker daemon 9.216kB Step 1: FROM alpine ---> 3fd9065eaf02 Step 2/3 : LABEL maintainer="lixinkuan <[email protected]>" ---> Using cache ---> 56049399eb78 Step 3/3 : COPY default /tmp/ ---> 18cacf50aef9 Successfully built 18cacf50aef9 Successfully tagged cpdir:latestCopy the code
  1. View and verify:
[root@docker image]# docker image ls REPOSITORY TAG IMAGE ID CREATED SIZE cpdir latest 18cacf50aef9 24 seconds ago 4.15MB [root@docker image]# docker run --name cpdir -it --rm cpdir:latest WARNING: 4.15MB [root@docker image]# docker run --name cpdir -it --rm cpdir:latest WARNING: IPv4 forwarding is disabled. Networking will not work. / # ls /tmp grub kibana nss useraddCopy the code

Example: Create a configuration file using an array format

  1. Modify the configuration file as follows:
#Test Image Build
FROM alpine
LABEL maintainer="lixinkuan <[email protected]>"

COPY ["default","/tmp/default"]
Copy the code
  1. Create an image and verify it
[root@docker image]# docker build -t cp:latest./ Sending build context to docker daemon 9.216KB Step 1: FROM alpine ---> 3fd9065eaf02 Step 2/3 : LABEL maintainer="lixinkuan <[email protected]>" ---> Using cache ---> 56049399eb78 Step 3/3 : COPY ["default","/tmp/default"] ---> bf0799319943 Successfully built bf0799319943 Successfully tagged cp:latest [root@docker image]# docker run --name cp -it --rm cp:latest / # cd /tmp /tmp # ls default /tmp # cd default/ /tmp/default # ls grub kibana nss useradd /tmp/default # exitCopy the code

8. ADD

  • ADD is similar to the COPY directive in that it supports tar files and URL paths
  • Syntax
    • ADD …
    • ADD [“”…””]
  • Operating criteria:
    • With the COPY instructions
    • If it is a URL and does not end with a /, the specified file will be downloaded and directly created as; If it ends with a /, the file specified by the file name URL will be downloaded directly and saved as a /
    • If it is a tar file in compressed format on the local system, it will be expanded into a directory that behaves like the “tar -x” command. However, tar files obtained through the URL will not automatically expand;
    • If there are more than one, or if wildcards are used indirectly or directly, it must be a directory path ending in /; If it does not end with a /, it is treated as a normal file and its contents are written directly to

Example: Download a file to an image file

  1. Write Dockerfile file in working directory (FTP protocol failed while using URL)
#Test Image Build
FROM alpine
LABEL maintainer="lixinkuan <[email protected]>"

COPY ["default","/tmp/default"]

ADD https://mirrors.aliyun.com/centos/7.5.1804/os/x86_64/Packages/zsh-5.0.2-28.el7.x86_64.rpm /tmp/
Copy the code
  1. Creating an Image File
[root@docker image]# docker build -t ZSH :latest./ Sending build context to docker daemon 9.216kB Step 1/4: FROM alpine ---> 3fd9065eaf02 Step 2/4 : LABEL maintainer="lixinkuan <[email protected]>" ---> Using cache ---> 56049399eb78 Step 3/4 : COPY ["default","/tmp/default"] ---> Using cache ---> bf0799319943 Step 4/4 : ADD https://mirrors.aliyun.com/centos/7.5.1804/os/x86_64/Packages/zsh-5.0.2-28.el7.x86_64.rpm/TMP/Downloading [= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = >] 2.494 MB / 2.494 MB - > 538 ab9c6983e Successfully built 538 ab9c6983e Successfully tagged zsh:latestCopy the code
  1. Create the container and view it
[root@docker image]# docker run-it --name ZSH --rm ZSH :latest / # CD/TMP/TMP # ls default zsh-5.0.2-28.el7.x86_64.rpmCopy the code

Example :ADD a compressed package to an image file

  1. Copy the compressed package to the working directory and edit the Dockerfile file in the working directory
[root@docker image]# cp /root/wordpress-4.8.1-zh_CN.tar.gz ./
[root@docker image]# vim Dockerfile 
#Test Image Build
FROM alpine
LABEL maintainer="lixinkuan <[email protected]>"

ADD wordpress-4.8.1-zh_CN.tar.gz /tmp/
Copy the code
  1. Creating an Image File
[root@docker image]# docker build -t wordpress:latest./ Sending build context to docker daemon 8.652MB Step 1: FROM alpine ---> 3fd9065eaf02 Step 2/3 : LABEL maintainer="lixinkuan <[email protected]>" ---> Using cache ---> 56049399eb78 Step 3/3 : ADD wordpress-4.8.1-zh_cn.tar. gz/TMP / --> 58c32caba31e Successfully built 58c32caba31e Successfully tagged wordpress:latestCopy the code
  1. Create the container and view it
[root@docker image]# docker run --name a1 -it --rm wordpress:latest / # ls /tmp/wordpress/ index.php wp-admin wp-content  wp-load.php wp-signup.php license.txt wp-blog-header.php wp-cron.php wp-login.php wp-trackback.php readme.html wp-comments-post.php wp-includes wp-mail.php xmlrpc.php wp-activate.php wp-config-sample.php wp-links-opml.php wp-settings.php / # exitCopy the code

9. WORKDIR

  • Use to specify a working directory for all RUN, CMD, ENTRYPOINT, COPY, and ADD in Dockerfile
  • Syntax
    • WORKDIR
      • The WORKDIR directive can appear multiple times in a Dockerfile, and its path can be relative, but it is relative to the path specified by a previous WORKDIR directive
      • In addition, WORKDIR can also call variables defined by ENV
    • Such as:
      • WORKDIR /var/log
      • WORKDIR $STATEPATH

The sample

  1. Edit the Dockerfile file in the working directory:
#Test Image Build FROM alpine LABEL maintainer="lixinkuan <[email protected]>" WORKDIR /tmp ADD WordPress - 4.8.1 - zh_CN. Tar. Gz SRCCopy the code
  1. Creating an image:
[root@docker image]# docker build-t wordpress:v0.1./ Sending build context to docker daemon 8.652MB Step 1/4: FROM alpine ---> 3fd9065eaf02 Step 2/4 : LABEL maintainer="lixinkuan <[email protected]>" ---> Using cache ---> 56049399eb78 Step 3/4 : WORKDIR /tmp Removing intermediate container 08bef4630472 ---> 54f97eda6b49 Step 4/4 : ADD wordpress-4.8.1-zh_cn.tar. gz SRC --> 0811aff4FA7d Successfully built 0811aff4FA7d Successfully tagged WordPress: v0.1Copy the code
  1. After the container is created, the default working path is/TMP as indicated by WORKDIR
[root@docker image]# docker run --name a1-it --rm wordpress:v0.1 / TMP # ls SRC/TMP # ls SRC/wordpress/TMP # ls src/wordpress/ index.php wp-admin wp-content wp-load.php wp-signup.php license.txt wp-blog-header.php wp-cron.php wp-login.php wp-trackback.php readme.html wp-comments-post.php wp-includes wp-mail.php xmlrpc.php wp-activate.php wp-config-sample.php wp-links-opml.php wp-settings.php /tmp # exitCopy the code

10. VOLUME

  • Use to create a mount point directory in image to mount volumes on Docker host or on other containers
  • Syntax
    • VOLUME
    • VOLUME [“”]
  • If a file exists in the mount point directory, the docker run command will hide the file.
  • If the mount point does not already exist, Docker will automatically create the directory.
  • All file changes under the mount point can be viewed on the host
    • View method:
      • Docker volume ls # Check all mounted directories on the host
      • Docker inspect -f {{.mounts}} A1 # Displays the mount point path by viewing specified container information

The sample

  1. Provide files in the directory you want to mount
[root@docker image]# echo "hello,test dockerfile" > /var/www/html/index.html
Copy the code
  1. Edit the Dockerfile file in your working directory
#Test Image Build FROM alpine LABEL maintainer="lixinkuan <[email protected]>" #WORKDIR /tmp #ADD WordPress - 4.8.1 - zh_CN. Tar. Gz SRC/VOLUME/var/WWW/HTMLCopy the code
  1. Creating an Image File
[root@docker image]# docker build -t file:v0.1./ Sending build context to docker daemon 8.651MB Step 1/3: FROM alpine ---> 3fd9065eaf02 Step 2/3 : LABEL maintainer="lixinkuan <[email protected]>" ---> Using cache ---> 56049399eb78 Step 3/3 : VOLUME /var/www/html ---> [Warning] IPv4 forwarding is disabled. Networking will not work. ---> Running in da84d9f4ca1e Removing intermediate container da84d9f4ca1e ---> b26c2d7ea64c Successfully built b26c2d7ea64c Successfully tagged File: v0.1Copy the code
  1. Create a container:
[root@docker image]# docker run --name a1 -it --rm file
/ # cd /var/www/html/
/var/www/html # echo abc > index.html
/var/www/html # cat index.html
abc
Copy the code
  1. To view files on the host:
[root@docker ~]# docker volume ls # Check the directory to which all the local containers are mounted 6368d0a0b462f5329a4b3bdcb7030e0d6f724bf9f801386f87fdac7660cd1735 [root@docker ~]# docker inspect -f {{.Mounts}} a1 # see a1 container mounting the file path [{6368 d0a0b462f5329a4b3bdcb7030e0d6f724bf9f801386f87fdac7660cd1735 volume /var/lib/docker/volumes/6368d0a0b462f5329a4b3bdcb7030e0d6f724bf9f801386f87fdac7660cd1735/_data /var/www/html local true }] [root@docker ~]# cd /var/lib/docker/volumes/6368d0a0b462f5329a4b3bdcb7030e0d6f724bf9f801386f87fdac7660cd1735/_data/ [root@docker _data]# ls index. HTML [root@docker _data]# cat index. HTML ABC # This content is the same as the index. HTML content in the containerCopy the code

11. EXPOSE

  • Used to open the specified port for the container to listen on for external communication
  • The essence is to add DNAT rules through iptables to forward the requests from the extranet host to the host to the specified container.
  • The core forwarding function must be enabled on the host.
  • You can run the iptables -t nat-nvL command to view the added rules.
  • If you do not specify the port to be exposed when creating an image using Dockerfile, you can use the following two methods to EXPOSE the port:
    • After the container runs, add DNAT rules to realize port exposure.
    • Docker run uses the -p option to specify the exposed port.
    • The -p option is used when docker run to expose all ports listening in containers.
  • When docker run, the -p option is used to specify a higher priority than the port to be exposed when Dockerfile is mirrored.
  • Syntax
    • EXPOSE [/] [[/] …]
      • The transport layer protocol can be TCP or UDP. The default is TCP
  • The EXPOSE directive can specify more than one port at a time, for example
    • EXPOSE 11211/udp 11211/tcp

When a container inside a host machine is to be accessed by an external host without exposing it

  1. Download redis: 4 – alpine
[root@docker ~]# docker pull redis:4-alpine 4-alpine: Pulling from library/redis ff3a5c916c92: Pull complete 5fbab8756652: Pull complete ff7d4663b06c: Pull complete 0b5cf71258c2: Pull complete 54bbb9bad8ba: Pull complete 8fe9a341d124: Pull complete Digest: sha256:686ab026fae07b3b99a8e74210c361714a80311ecc55f23b349ae930ed2f5a95 Status: Downloaded newer image for redis:4-alpine [root@docker ~]# docker images REPOSITORY TAG IMAGE ID CREATED SIZE redis 4- Alpine Caaeda72BF8f 12 days ago 27.8MBCopy the code
  1. Run the Redis image
[root@docker ~]# docker run --name db1 -d --rm -p 6379 redis:4-alpine 881d5648c7388449a39c67024206c5710b1538f4c941039fa3905bb601b09699 [root@docker ~]# docker exec -it db1 ifconfig eth0 Link Encap :Ethernet HWaddr 02:42:AC:11:00:02 INET ADDR :172.17.0.2 Bcast:172.17.255.255 Mask:255.255.0.0 UP BROADCAST RUNNING  MULTICAST MTU:1500 Metric:1 RX packets:8 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 Overruns :0 Carrier :0 Collisions :0 TxQueuelen :0 RX bytes:648 (648.0b) TX bytes:0 (0.0b) LO Link encap:Local Loopback Inet addr:127.0.0.1 Mask:255.0.0.0 UP LOOPBACK RUNNING MTU:65536 Metric:1 RX packets:0 errors:0 dropped:0 Overruns :0 Frame :0 TX packets:0 errors:0 dropped:0 Overruns :0 Carrier :0 Collisions :0 TxQueuelen :1 RX bytes:0 (0.0b) TX bytes:0 (0.0b) [root@docker ~]# docker exec -it db1 /bin/sh /data # netstat -tnl Active Internet connections (only servers) Proto Recv -q Send -q Local Address Foreign Address State TCP 0 0 0.0.0.0:6379 0.0.0.0:* LISTEN TCP 0 0: :6379 :::* LISTEN /data #Copy the code
  1. View the mapped ports
[root@docker ~]# Docker Container port db1 6379/ TCP -> 0.0.0.0:32768Copy the code
  1. An extranet host accesses the local host container
[root@node1 tmp]# redis-cli -h 192.168.1.106 -p 32768
192.168.1.106:32768> select 1
OK
192.168.1.106:32768[1]> set mykey hi
OK
192.168.1.106:32768[1]> keys *
1) "mykey"
192.168.1.106:32768[1]> exit
Copy the code
  1. Check whether data exists in the local container
[root@docker ~]# docker exec -it db1 /bin/sh
/data # redis-cli 
127.0.0.1:6379> select 1
OK
127.0.0.1:6379[1]> keys *
1) "mykey"
127.0.0.1:6379[1]> exit
/data # exit
Copy the code

Enable automatic port exposure

  1. Write a Dockerfile file in your working directory
#Test Image Build
FROM redis:4-alpine
LABEL maintainer="lixinkuan <[email protected]>"
EXPOSE 6379/tcp 26379/tcp
Copy the code
  1. Creating an Image File
[root@docker images]# docker build -t expose_db:latest./ Sending build context to docker daemon 8.645MB Step 1/3: FROM redis:4-alpine ---> caaeda72bf8f Step 2/3 : LABEL maintainer="lixinkuan <[email protected]>" ---> Running in f43f9e43b27a Removing intermediate container f43f9e43b27a ---> e98bb940a8a2 Step 3/3 : EXPOSE 6379/tcp 26379/tcp ---> Running in f53a9be4f661 Removing intermediate container f53a9be4f661 ---> ea40417716a0 Successfully built ea40417716a0 Successfully tagged expose_db:latestCopy the code
  1. Run and see the effect
[root@docker images]# docker run --name a1 -d --rm -P redis_expose:latest ad1225390f8f246cc5bde693ea99b120ee3a2f474416603b0797cda94787cc03 [root@docker images]# docker container port a1 6379/tcp - > 0.0.0.0:32772Copy the code
  1. Connect to the database on another host
[root@node1 ~]# redis-cli -h 192.168.200.45 -p 32772 192.168.200.45:32772> select 1 OK 192.168.200.45:32772[1]> keys * (empty list or set) 192.168.200.45:32772[1]> set test dockerfile OK 192.168.200.45:32772[1]> keys * 1) "test" 192.168.200.45:32772 [1] > get the test "dockerfile"Copy the code
  1. View on a1 container:
[root@docker images]# docker exec -it a1 /bin/sh
/data # redis-cli 
127.0.0.1:6379> select 1
OK
127.0.0.1:6379[1]> get test
"dockerfile"
Copy the code

Example: the priority of -p when verifying Dockerfile and docker run

  1. Edit Dockerfile
[root@docker images]# cat Dockerfile 
#Test Image Build
FROM redis:4-alpine
LABEL maintainer="lixinkuan <[email protected]>"
EXPOSE 6379/tcp 80/tcp
Copy the code
  1. Making a mirror:
[root@docker images]# docker build-t expose_port. Sending build context to docker daemon 8.645MB Step 1/3: FROM redis:4-alpine ---> caaeda72bf8f Step 2/3 : LABEL maintainer="lixinkuan <[email protected]>" ---> Using cache ---> 188775dd2e3e Step 3/3 : EXPOSE 6379/tcp 80/tcp ---> Running in b0f5bfbaafae Removing intermediate container b0f5bfbaafae ---> 165e707c2b23 Successfully built 165e707c2b23 Successfully tagged expose_port:latestCopy the code
  1. Specify the ports to expose when running the container:
[root@docker images]# docker run --name db1 -d --rm -p 25 expose_port e00f3e304103954c00651d44b00ae9961608900e0d5688eee4c08f140340f480 [root@docker images]# docker container port db1 25/tcp - > 0.0.0.0:32779Copy the code
  1. Check the firewall rules. Only the DNAT rules of port 25 are exposed
[root@docker images]# iptables -t nat -nvL Chain DOCKER (2 references) pkts bytes target prot opt in out source Destination 0 0 RETURN all -- docker0 * 0.0.0.0/0 0.0.0.0/0 0 0 DNAT TCP --! Docker0 * 0.0.0.0/0 0.0.0.0/0 TCP DPT :32779 to:172.17.0.2:25Copy the code

12. ENV

  • This is used to define the environment variables required for the image and can be called by other directives (ENV, ADD, COPY, etc.) following in the Dockerfile file
  • Call format variablename or variable_NAME or variablename or {variable_NAME}
  • Syntax
    • ENV
    • ENV = …
  • In the first format, everything that follows is considered part of it, so only one variable can be set at a time
  • In the second format, you can set more than one variable at a time. Each variable is a “=” key-value pair. If it contains Spaces, it can be escaped with a backslash () or marked with quotes. In addition, backslashes can be used to continue lines
  • When defining multiple variables, the second approach is recommended so that all functionality can be done in the same layer

The sample

  1. Edit the Dockerfile file
FROM busybox
LABEL maintainer="lixinkuan <[email protected]>"

ENV DOCROOT="/data/web/html/"

COPY index.html ${DOCROOT}

VOLUME ${DOCROOT}
Copy the code
  1. Provide index and desired mount directory:
[root@docker bbox]# mkdir -pv /data/web/ HTML mkdir: created directory '/data' Created the directory '/ data/web' mkdir: Created Directory '/data/web/ HTML' [root@docker bbox]# echo hello Docker > index.html [root@docker bbox]# cat index.html  hello DockerCopy the code
  1. Making a mirror:
[root@docker bbox]# docker build -t bbox_file:latest./ Sending build context to docker daemon 3.072kB Step 1/5: FROM busybox latest: Pulling from library/busybox 07a152489297: Pull complete Digest: sha256:141c253bc4c3fd0a201d32dc1f493bcf3fff003b6df416dea4f41046e0f37d47 Status: Downloaded newer image for busybox:latest ---> 8c811b4aec35 Step 2/5 : LABEL maintainer="lixinkuan <[email protected]>" ---> Running in 87a1f2c22ad6 Removing intermediate container 87a1f2c22ad6 ---> 56f723d6220c Step 3/5 : ENV DOCROOT="/data/web/html/" ---> Running in 21fd1fcb0474 Removing intermediate container 21fd1fcb0474 ---> c095f8dd8418 Step 4/5 : COPY index.html ${DOCROOT} ---> ee77cd16629a Step 5/5 : VOLUME ${DOCROOT} ---> Running in 00474fde8b85 Removing intermediate container 00474fde8b85 ---> d51ea735fdd3 Successfully built d51ea735fdd3 Successfully tagged bbox_file:latestCopy the code
  1. Run the container and see
[root@docker bbox]# docker run --name a1 -it --rm bbox_file:latest
/ # ls /data/web/html
index.html
/ # cat /data/web/html/index.html
hello Docker
Copy the code
  1. Open another terminal to view the attached volume:
[root@docker ~]# docker volume ls
DRIVER              VOLUME NAME
local               1dcd37d2c4f2e6a71e0b96a385714ff01cad5d578e396c9b012922e9993aecbf
local               b2df5fcd0e1aa58c403d2e8f0ec880feb7dcb1a80a688697e76122adec55e789
[root@docker ~]# docker inspect -f {{.Mounts}} a1
[{volume 1dcd37d2c4f2e6a71e0b96a385714ff01cad5d578e396c9b012922e9993aecbf /var/lib/docker/volumes/1dcd37d2c4f2e6a71e0b96a385714ff01cad5d578e396c9b012922e9993aecbf/_data /data/web/html local  true }]
Copy the code

13. CMD and RUN

  1. CMD
  • Defines the application that runs by default when an image is started as a container.
  • Like the RUN directive, the CMD directive can be used to RUN any command or application, but at a different point in time
    • The RUN directive runs during the build of the image file, and the CMD directive runs when a container is started from a new image built from Dockerfile
    • The primary purpose of the CMD directive is to specify the default program to run for the started container, and when that program runs, the container terminates. However, commands specified by CMD can be overridden by docker Run command-line options
    • Multiple CMD directives can exist in a Dockerfile, but only the last one will take effect
  • Syntax
    • CMD
    • CMD/” “, “”,” “
    • CMD [“”,””]
  • The first two syntax forms have the same meaning as RUN
  • The third is used to provide default parameters for the ENTRYPOINT directive
  1. RUN
  • Specifies the program to run during the Docker build procedure. The command must exist in the mirror.
  • Syntax
    • RUN
    • RUN [“”, “”, “”]
  • In the first format, it is usually a shell command, and it is run as “/bin/sh -c”, which means that the process in the container PID is not 1 and cannot receive Unix signals. Therefore, when the container is stopped by the docker stop command, the process does not receive SIGTERM signals.
  • In the second syntax, the arguments are a JSON-formatted array of the command to run, followed by the options or arguments passed to the command. However, commands specified in this format are not initiated with “/bin/sh -c”, so common shell operations such as variable substitution and wildcard characters (? ,*, etc.) replacement will not take place; However, if the command you want to run depends on this shell feature, you can replace it with something like the following.
    • Example :RUN [“/bin/bash”, “-c”, “”, “”]

Example 1: Create an image to run nginx based on the centos base image

  1. Edit the Dockerfile file:
FROM centos
LABEL maintainer="lixinkuan <[email protected]>"

COPY base.repo epel.repo /etc/yum.repos.d/

RUN yum -y install nginx \
        && yum clean all \
        && rm -rf /var/cache/yum
Copy the code
  1. To provide the base. Repo epel.repo file:
[root@docker nginx]# wget lixinkuan.top/base.repo --2018-06-30 11:29:08-- http://lixinkuan.top/base.repo Resolving lixinkuan.top (lixinkuan.top)... 47.94.102.99 Connecting to lixinkuan. Top (lixinkuan. Top) | 47.94.102.99 | : 80... connected. HTTP request sent, awaiting response... 200 OK Length: 630 Saving to: 'base.' '100% [= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = >] 630 -. - K/s in 0 s 2018-06-30 11:29:08 (87.9 MB/s) - 'base.repo' saved [630/630] [root@docker nginx]# wget lixinkuan.top/epel.repo --2018-06-30 11:29:16-- http://lixinkuan.top/epel.repo Resolving lixinkuan.top (lixinkuan.top)... 47.94.102.99 Connecting to lixinkuan. Top (lixinkuan. Top) | 47.94.102.99 | : 80... connected. HTTP request sent, awaiting response... 200 OK Length: 214 Saving to: 'epel.' '100% [= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = >] 214 -. - K/s in 0 s 2018-06-30 11:29:16 (44.2 MB/s) - 'epel.repo' saved [214/214] [root@docker nginx]# ls base. Repo Dockerfile epel.repoCopy the code
  1. Creating an image:
[root@docker nginx]# docker build -t nginx:v0.1./ Sending build context to docker daemon 4.608kB FROM centos latest: Pulling from library/centos 7dc0dca2b151: Pull complete Digest: sha256:b67d21dfe609ddacf404589e04631d90a342921e81c40aeaf3391f6717fa5322 Status: Downloaded newer image for centos:latest ---> 49f7960eb7e4 Step 2/4 : LABEL maintainer="lixinkuan <[email protected]>" ---> Running in 6b16128ed7ca Removing intermediate container 6b16128ed7ca ---> b6ef19a3311f Step 3/4 : COPY base.repo epel.repo /etc/yum.repos.d/ ---> e571c2837442 Step 4/4 : RUN yum -y install nginx && yum clean all && rm -rf /var/cache/yum ---> Running in 445372de8e8d Loaded plugins: fastestmirror, ovl ..... Perform the installation process omit... Cleaning repos: base epel extras updates Cleaning up everything Maybe you want: rm -rf /var/cache/yum, to also free up space taken by orphaned data from disabled or removed repos Cleaning up list of fastest mirrors Removing Intermediate Container 445372de8E8D --> 5CF6E8E3517E Successfully built 5CF6E8E3517e Successfully tagged nginx:v0.1Copy the code
  1. Create a container and view:
[root@docker nginx]# docker run --name web nginx:v0.1 [root@5e7adf4282c1 /]# RPM -q nginx nginx-1.12.2-2.el7.x86_64 #nginx installed [root@5e7adf4282c1 /]#Copy the code

Example 2: Use BusyBox to create an image that mounts the local /data/web/ HTML directory and automatically runs HTTPD

  1. Edit the Dockerfile file in the working directory
FROM busybox
LABEL maintainer="lixinkuan <[email protected]>"

ENV DOCROOT="/data/web/html/"

COPY index.html ${DOCROOT}

VOLUME ${DOCROOT}

CMD /bin/httpd -f -h ${DOCROOT}
Copy the code
  1. Provide index. HTML and create the directory to mount
[root@docker bbox]# echo hello Docker > index.html
[root@docker bbox]# cat index.html
hello Docker
Copy the code
  1. Creating an image file:
[root@docker bbox]# Docker build-t web:v0.1./ Sending build context to docker daemon 3.072kB Step 1/6: FROM busybox ---> 8c811b4aec35 Step 2/6 : LABEL maintainer="lixinkuan <[email protected]>" ---> Using cache ---> 56f723d6220c Step 3/6 : ENV DOCROOT="/data/web/html/" ---> Using cache ---> c095f8dd8418 Step 4/6 : COPY index.html ${DOCROOT} ---> Using cache ---> ee77cd16629a Step 5/6 : VOLUME ${DOCROOT} ---> Using cache ---> d51ea735fdd3 Step 6/6 : CMD /bin/httpd -f -h ${DOCROOT} ---> Running in f2fa2b284306 Removing intermediate container f2fa2b284306 ---> B8613217ad3c Successfully built b8613217ad3c Successfully tagged web:v0.1Copy the code
  1. Run the container with the newly created image file and view it
[root@docker bbox]# docker run --name web -d --rm web:v0.1
7b71084ebd922728ebf21d22a4e5ff3462443761c82bc22c640764c6d4925b2a
[root@docker bbox]# docker container inspect -f {{.Config.Cmd}} web
[/bin/sh -c /bin/httpd -f -h ${DOCROOT}]
[root@docker bbox]# docker exec -it web /bin/sh
/ # ps aux
PID   USER     TIME  COMMAND
    1 root      0:00 /bin/httpd -f -h /data/web/html/
    7 root      0:00 /bin/sh
   13 root      0:00 ps aux
/ # netstat -tnl
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       
tcp        0      0 :::80                   :::*                    LISTEN      
Copy the code

Example 3: Docker run does not run the image default process, run the specified directive

  1. View the current image file:
[root@docker bbox]# Docker Images REPOSITORY TAG ID CREATED SIZE Web v0.1b8613217ad3c 2 hours ago 1.15MBCopy the code
  1. Create the container using web:v0.1 without running the default command
[root@docker bbox]# docker run --name web -it --rm web:v0.1 /bin/sh
/ # netstat -tnl
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       
/ # ps aux
PID   USER     TIME  COMMAND
    1 root      0:00 /bin/sh
    7 root      0:00 ps aux
Copy the code

14. ENTRYPOINT

  • A cmds-like function is used to specify the default program to run for the container, making it look like a separate executable program
  • Unlike CMD, programs started by ENTRYPOINT are not overwritten by the arguments specified by the Docker Run command line, and these command line arguments are passed as arguments to the programs specified by ENTRYPOINT
    • However, the argument to the — entryPoint option of the Docker run command overwrites the program specified by the entryPoint directive
  • Syntax
    • ENTRYPOINT
    • ENTRYPOINT [“”, “”, “”]
  • The command arguments passed to the Docker run command overwrite the contents of the CMD directive and are appended to the ENTRYPOINT command and used as its arguments
  • There can also be multiple ENTRYPOINT directives in a Dockerfile, but only the last one will take effect

Example 1:

  1. Edit the Dockerfile file
FROM busybox
LABEL maintainer="lixinkuan <[email protected]>"

VOLUME /data/web/html/

COPY index.html /data/web/html/

EXPOSE 80/tcp

ENTRYPOINT ["/bin/httpd","-f","-h","/data/web/html"]
Copy the code
  1. Create a mirror image
[root@docker bbox]# Docker build-t web:v0.2./ Send build context to docker daemon 3.072kB Step 1/6: FROM busybox ---> 8c811b4aec35 Step 2/6 : LABEL maintainer="lixinkuan <[email protected]>" ---> Using cache ---> 56f723d6220c Step 3/6 : VOLUME /data/web/html/ ---> Running in 3095065d0ebb Removing intermediate container 3095065d0ebb ---> 36dc68fabc6f Step 4/6 : COPY index.html /data/web/html/ ---> e47f81ec7728 Step 5/6 : EXPOSE 80/tcp ---> Running in f86f957ec882 Removing intermediate container f86f957ec882 ---> 01a005644fe6 Step 6/6 : ENTRYPOINT ["/bin/httpd","-f","-h","/data/web/html"] ---> Running in 7a5f8b4f4acf Removing intermediate container 7a5f8b4f4ACf --> 43d514096d34 Successfully built 43d514096d34 Successfully tagged Web :v0.2Copy the code
  1. Create a container to run and view:
[root@docker bbox]# docker exec -it web /bin/sh / # ps aux PID USER TIME COMMAND 1 root 0:00 /bin/httpd -f -h /data/web/html 7 root 0:00 /bin/sh 13 root 0:00 ps aux / # netstat -tnl Active Internet connections (only servers) Proto  Recv-Q Send-Q Local Address Foreign Address State tcp 0 0 :::80 :::* LISTEN / #Copy the code
  1. The /bin/sh command is specified when the container is run
[root@docker bbox]# docker run --name web-it --rm web:v0.2 /bin/shCopy the code
  1. Switch to another tty
[root@docker bbox]# docker exec -it web /bin/sh
/ # ps aux
PID   USER     TIME  COMMAND
    1 root      0:00 /bin/httpd -f -h /data/web/html /bin/sh
    7 root      0:00 /bin/sh
   13 root      0:00 ps aux
Copy the code

Instead of executing /bin/sh, the default program is executed, and /bin/sh is passed as an argument to /bin/httpd

Example: Change the default running program when using entryPoint in Docker run

  • –entrypoint string Overwrite the default ENTRYPOINT of the image
  1. Add the — entryPoint option at run time when creating containers using mirror Web: V0.2
[root@docker bbox]# docker run --name web -it --rm --entrypoint /bin/sh web:v0.2
/ # ps aux
PID   USER     TIME  COMMAND
    1 root      0:00 /bin/sh
    7 root      0:00 ps aux
/ # netstat -tnl
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       
/ # 
Copy the code

The sample

  1. Edit the Dockerfile file
FROM busybox
LABEL maintainer="lixinkuan <[email protected]>"

ENV DOCROOT="/data/web/html/" MYPORT="80"

COPY index.html ${DOCROOT} 
COPY entrypoint.sh /bin/
COPY test.conf /etc/

VOLUME ${DOCROOT}

EXPOSE 80/tcp

#CMD /bin/httpd -f -h ${DOCROOT}

#CMD ["/bin/sh","-c","/bin/httpd","-f","-h","${DOCROOT}"]
ENTRYPOINT ["/bin/entrypoint.sh"]

CMD ["/bin/httpd","-f","-h","/data/web/html/"]
Copy the code
  1. Provide required files (script files need execute permission)
[root@docker bbox]# cat entrypoint.sh #! /bin/sh sed -i "s@^PORT=.*@PORT=${MYPORT}@g" /etc/test.conf exec "$@" [root@docker bbox]# cat test.conf PORT=8080Copy the code
  1. Making a mirror:
[root@docker bbox]# docker build-t web:v0.3./ Sending build context to docker daemon 5.12kB Step 1/10: FROM busybox ---> 8c811b4aec35 Step 2/10 : LABEL maintainer="lixinkuan <[email protected]>" ---> Using cache ---> 56f723d6220c Step 3/10 : ENV DOCROOT="/data/web/html/" MYPORT="80" ---> Running in f237100ec645 Removing intermediate container f237100ec645 --->  f754b5dcea84 Step 4/10 : COPY index.html ${DOCROOT} ---> 3c31424c9b3d Step 5/10 : COPY entrypoint.sh /bin/ ---> 46ec2f5ede8c Step 6/10 : COPY test.conf /etc/ ---> 7db53e00338a Step 7/10 : VOLUME ${DOCROOT} ---> Running in 5ae02469f585 Removing intermediate container 5ae02469f585 ---> 0e1e3e966318 Step 8/10 : EXPOSE 80/tcp ---> Running in ae76bcf870ca Removing intermediate container ae76bcf870ca ---> dea89896460d Step 9/10 : ENTRYPOINT ["/bin/entrypoint.sh"] ---> Running in 6862bf4a336e Removing intermediate container 6862bf4a336e ---> ca568e1ff983 Step 10/10 : CMD ["/bin/httpd","-f","-h","/data/web/html/"] ---> Running in 2aa5dea11848 Removing intermediate container 2aa5dea11848 --> 26bb44795880 Successfully built 26bb44795880 Successfully tagged Web :v0.3Copy the code
  1. Run the container and see if the configuration file has been modified
[root@docker bbox]# docker run --name web-d --rm web:v0.3 6ec1f5a008e6a08047e8666f6ed3ad4673360805148789faf780baf335ee5637 [root@docker bbox]# docker exec -it web /bin/sh / # netstat -tnl Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State tcp 0 0 :::80 :::* LISTEN / # cat /etc/test.conf PORT=80 / # exitCopy the code

Example: How to change a configuration file by passing variables: [root@docker bbox]# docker run –name web1 -d –rm -e MYPORT=10080 web:v0.3 7e3b353e423839d598ee9423e881673066cf99626940b6590e78f34b7622834d [root@docker bbox]# docker exec -it web1 /bin/sh / # cat /etc/test.conf PORT=10080 / #

# # # 15. -Copy the code