Docker Quick Start-create a docker Image

Source: Internet
Author: User
Tags docker ps dockerfile example docker cp
Docker Quick Start-docker image creation I. dockerfile Script 1. Introduction to dockerfile script

Dockerfile is a text file that contains an instruction. Each instruction creates a layer. Therefore, the content of each instruction describes how to build the layer.
Dockerfile example:

# Dockerfile format # This dockerfile uses the Ubuntu image # version 2-Edition 1 # Author: docker_user # Command Format: instruction [arguments/command] .. #1. The first line must specify the basic image information from centos #2. maintainer docker_user [email protected] #3. Image Operation Command run Yum install-y nginx #4. Container run Command CMD/usr/sbin/nginx

The dockerfile consists of the basic image information, maintainer information, image operation instructions, and container startup and execution commands. The first part must specify the basic image name. The second part usually describes the maintainer information. The third part is the image Operation Command, such as the Run Command. Each execution of a run command adds a new layer to the image, and submit the command. The fourth part is the CMD command, indicating the operation command when running the container.
Dockerfile official documentation:
Dockerfile best practices:
Docker official image dockerfile:

2. From command

The from command is used to specify the basic image. Therefore, the from command in the dockerfile must be the first command.
There are a lot of high-quality official images in docker store, and there are directly available service class images, such as nginx, redis, Mongo, MySQL, httpd, pH, and tomcat; images are available for convenient development, construction, and running of applications in various languages, such as node, openjdk, Python, Ruby, and golang. Basic Operating System images are available, such as Ubuntu, Debian, centos, fedora, and Alpine.
Docker has a special scratch image, which is a virtual concept and does not actually exist. It indicates a blank image.
If the scratch-based image is not based on any image, the subsequent commands will begin to exist as the first layer of the image. Without any system, you can directly copy executable files to images such as swarm, coreos/etcd. In Linux, static compilation programs do not need the operating system to provide runtime support. All the required libraries are already in the executable file. Therefore, direct from scratch will make the image smaller.
From syntax format:

FROM <image>FROM <image>:<tag>FROM <image>:<digest>

The from restrictions are as follows:
A. From must be the first non-Comment command in dockerfile
B. When multiple images are created in a dockerfile, The from can appear multiple times. You only need to record the ID of the last submitted image before each new command from.
C, Tag, or digest are optional. If these two values are not used, the basic image of the latest version is used.

3. Run Command

Execute specific commands during image building and generate an intermediate image. Format:

# Shell run <command> # exec run ["executable", "param1", "param2"]

The Run Command will execute any valid command in the current image and submit the execution result. After the command is submitted, the next command in dockerfile is automatically executed.
The intermediate image created by the Run Command is cached and used in the next build. If you do not want to use a cache image, you can specify the -- no-Cache parameter during the build, for example, docker build -- no-cache.

4. Copy command

Syntax format of the Copy command:

Copy <Source Path>... <target path> copy ["<Source Path 1>",... "<target path>"]

The Copy Command copies the <Source Path> file/directory from the build context directory to the <target path> location in the image on the new layer.
<Source Path> there can be multiple or even wildcard characters. The wildcard rule must meet the filepath. Match Rule of go, for example:

COPY hom* /mydir/COPY hom?.txt /mydir/

The target path can be an absolute path in the container or a relative path relative to the working directory (the working directory can be specified using the workdir command ). The target path does not need to be created in advance. If the directory does not exist, the missing directory will be created before the file is copied.
Using the Copy command, various metadata of the source file will be retained, such as read, write, execution permission, and file change time.

5. Add command

The add command adds some features based on copy. For example, if <Source Path> is a URL, the docker engine tries to download the URL link file and put it in the <target path>.
When creating an image, copy the file in the context to the image. format:

Add <Source Path>... <target path> Add ["<Source Path>",... "<target path>"]

If docker finds that the file content is changed, subsequent commands will no longer use the cache.

6. CMD commands

CMD is used to specify the command to be executed when the container is started. CMD has three formats:

CMD ["executable","param1","param2"]CMD ["param1","param2"]CMD command param1 param2

The exec format of the executable file is omitted, so that the parameter in cmd is used as the default parameter of entrypoint. In this case, entrypoint should be in Exec format.
If CMD is/bin/bash, when you use docker run-It Ubuntu to start the container, it will directly execute the command to enter bash. Docker run-It Ubuntu CAT/etc/OS-release will output the system version information when the container is started.
In the CMD command format, we recommend that you use the exec format. The exec format is parsed as a JSON array. Therefore, you must use double quotation marks instead of single quotation marks.
If the shell format is used, the CMD command is packaged as sh-C parameters for execution. For example:
CMD echo $ home will change it:
CMD ["sh", "-c", "Echo $ home"]

7. entrypoint command

The entrypoint command is used to configure an executable program for the container. Each time an image is used to create a container, the program specified by entrypoint is set as the default program. Entrypoint has two forms:

ENTRYPOINT ["executable", "param1", "param2"]ENTRYPOINT command param1 param2

Commands executed through docker run do not overwrite entrypoint, and any parameters specified in the docker run command are passed to entrypoint again as parameters. Only one entrypoint command is allowed in dockerfile. If multiple entrypoint commands are used, the preceding settings are overwritten and only the last entrypoint command is executed.
All the parameters specified when docker run runs the container are passed to entrypoint and will overwrite the parameters specified by the CMD command. When you run docker run image-D, the parameter specified by-D is passed to the entry point. You can also use docker run -- entrypoint to override the entrypoint entry point.
ENTRYPOINT ["/usr/bin/nginx"]

8. env command

The env command is used to set environment variables. Subsequent commands can be used directly.

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

An example of env is as follows:

ENV VERSION=1.0 DEBUG=on     NAME="Happy Feet"
9. Arg commands

The ARG command is used to specify the variables passed to the build runtime.

ARG <name>[=<default value>]

Use Arg to specify two variables:

ARG siteARG build_user=scorpio

The preceding command specifies the site and build_user variables. build_user specifies the default value. When using docker build to build an image, you can use

--build-arg <varname>=<value>

Option parameter to specify or reset the value of the corresponding variable.
docker build --build-arg -t baidu/test .
Use the default Scorpio value for the build_user variable.

10. Volume commands

The volume command is used to create a mount point, that is, to add a volume to the container created based on the built image:
VOLUME ["/data"]
A volume can exist in a specified directory of one or more containers. This directory can bypass the federated file system and has the following functions:
A. volumes can be shared and reused between containers.
B. containers do not have to share volumes with other containers.
C. The modified volume will take effect immediately.
D. Modifying the volume will not affect the image.
E. The volume will always exist until no container is using it.
Volume can add source code, data, or other content to the image without submitting it to the image, and share data among multiple containers.

11. Expose command

The expose command sets a listening port for the built image so that the container can listen at runtime. The format is as follows:

EXPOSE <port> [<port>...]

The expose command does not allow the container to listen to the host port. If you want the container to listen to the host port, you need to use? -P,-P? Parameter to publish the container port to a port of the host.

12. workdir command

The workdir command is used to set a working directory in the container.
WORKDIR /path/to/workdir
After setting the working directory through workdir, subsequent commands such as run, CMD, entrypoint, add, and copy in dockerfile will be executed in the working directory.


PWD will eventually be in? /A/B/C? Directory. When using docker run to run the container, You can overwrite the working directory set during the build with the-W parameter.

13. USER commands

The USER command is used to specify the user used to run the image.
USER daemon
When using user to specify a user, you can use the user name, uid, or GID, or a combination of the two.

USER userUSER user:groupUSER uidUSER uid:gidUSER user:gidUSER uid:group

After a user is specified, subsequent commands run, CMD, and entrypoint in dockerfile use this user. After the image is built, you can overwrite the specified user by using the-u parameter when running the container through docker run.

14. healthcheck command

Run an internal container command to check whether the container is healthy.
Disable health check for any basic image
-- Interval = duration? (Default :? 30 s)
-- Timeout = duration? (Default :? 30 s)
-- Retries = n? (Default :? 3)

15. onbuild commands

The onbuild command is used to set the image trigger.
When the created image is used as the basic image of another image, the trigger in the image will be triggered. When an image is used, some processing may be required:

[...]ONBUILD ADD . /app/srcONBUILD RUN /usr/local/bin/python-build --dir /app/src[...]
16. Label

The label command is used to add metadata to an image. The elements are specified as key-value pairs.

LABEL <key>=<value> <key>=<value> <key>=<value> ...

When you use label to specify metadata, one label can specify one or more metadata items. When multiple metadata items are specified, different metadata items are separated by spaces. We recommend that you specify all metadata using a label command to avoid generating too many intermediate images.
LABEL version="1.0" description="hello world" by="scorpio"
The metadata specified by the label can be viewed through docker inspect.

17. stopsignal

The stopsignal command is used to set the system call signal to be sent by the stop container.
The signal used must be a valid value in the kernel system call table, for example, sigkill.

18. Shell

The shell command is used to set the default shell type used to execute the command (Shell.
SHELL ["executable", "parameters"]
Shell is useful in windows. In Windows, there are usually two types of shells: CMD and powershell. You can use shell to specify the shell type.

Ii. dockerfile Image Construction 1. Introduction to dockerfile Construction

The docker build command constructs a new docker Image Based on the dockerfile file and context. The build context refers to the local path or a URL (GIT repository address) of the dockerfile ). The build context environment will be recursively processed, so the path specified for the build also includes sub-directories, and the URL also includes the specified sub-modules.
The build will be executed in the docker daemon, rather than in the CLI. Before building, the build process sends all content (recursively) to the daemon. Generally, an empty directory should be used as the context for building and the dockerfile file should be placed under this directory.
The dockerfile used in the build context is a build command file. To improve the construction capability, you can use the. Doc kerignore file to exclude unnecessary files and directories in the context directory.
In the first step of building an image in docker, The docker client will first search for the .dockerignorefile in the upper and lower directories. Doc kerignore? Exclude some files and directories in the context directory, and then pass the remaining files and directories to the docker service.
The dockerfile is generally located in the root directory of the build context. You can also use-F to specify the location of the dockerfile:
docker build -f /path/to/a/Dockerfile .
You can also use the-t parameter to specify the repository and tag for building the image. If multiple repositories exist or multiple image tags are used, you can use multiple-T parameters:
docker build -t nginx/v3:1.0.2 -t nginx/v3:latest .
The docker daemon checks the syntax of dockerfile before executing the commands in dockerfile. If a syntax error occurs, an error message is returned.

FROM ubuntu:14.04  ADD /  VOLUME /data  CMD ["./"]  

The Container built by the dockerfile file is as follows:

2. homogeneous image Construction

Homogeneous image building means that the image building environment is compatible with the running environment.
Homogeneous Image Construction generally requires that the compiling environment be compatible with the base image used by the image. For example, you can compile the application on Ubuntu 14.04 and import the application to the Image Based on the Ubuntu Series base image. Because the application compilation environment is compatible with the environment where it is deployed and run, the applications compiled under Ubuntu 14.04 can be basically seamlessly deployed on Ubuntu: 14.04 and later versions run in the base image. However, in an incompatible base image, for example, centos may fail to run.

package main import (         "net/http"         "log"         "fmt" ) func home(w http.ResponseWriter, req *http.Request) {         w.Write([]byte("Welcome to this website!\n")) } func main() {         http.HandleFunc("/", home)         fmt.Println("Webserver start")         fmt.Println("  -> listen on port:1111")         err := http.ListenAndServe(":1111", nil)         if err != nil {                 log.Fatal("ListenAndServe:", err)         } } 


From ubuntu:14.04 COPY ./httpserver /root/httpserver RUN chmod +x /root/httpserver WORKDIR /root ENTRYPOINT ["/root/httpserver"] 

Build an httpserver service image:
Start the httpserver service container:
The application image built based on the Basic Ubuntu image is too bloated, so it is necessary to build your own dedicated golang-builder Image Based on golang: Latest. dockerfile. Build can be used to build golang-builder image:

FROM golang:latest WORKDIR /go/src COPY httpserver.go . RUN go build -o httpserver ./httpserver.go 

Create a golang-builder image:
Create a container appsource from golang-Builder
docker create --name appsource golang-builder:latest
Copy httpserver from the appsource container to the current host directory
docker cp appsource:/go/src/httpserver ./
Delete the appsource container
docker rm -f appsource
Delete A golang-builder Image
docker rmi golang-builder:latest
Build an httpserver image from the current directory
docker build -t httpserver:latest .
The size of the httpserver image is still 200 MB. To reduce the size of the httpserver image, you must use a smaller base image, that is, Alpine. The size of the Alpine image is less than 4 MB, and the size of the application can be reduced to 20 mb.
Dockerfile. Alpine? File:

From alpine:latest COPY ./httpserver /root/httpserver RUN chmod +x /root/httpserver WORKDIR /root ENTRYPOINT ["/root/httpserver"] 

Create an Alpine application image:
docker build -t httpserver-alpine:latest -f Dockerfile.alpine .
Starting the httpserver-Alpine container fails because Alpine image is not the homogeneous image of the Ubuntu environment.

3. Heterogeneous Image Construction

Heterogeneous image building means that the building environment is incompatible with the running environment.
Go overrides the C code in runtime with go, which minimizes the libc dependency. However, it provides two versions of implementation: C implementation and go implementation. By default, when cgo_enabled = 1, both programs and pre-compiled standard libraries adopt C. Therefore, Debian and alpine systems implemented using different libc are naturally incompatible. To create a heterogeneous image, you must first construct the go program statically, and then put the statically constructed go application into the Alpine image.
The dockerfile. Build File is as follows:

FROM golang:alpine WORKDIR /go/src COPY httpserver.go . RUN go build -o httpserver ./httpserver.go 

Build a builder image:

docker?build?-t?myrepo/golang-static-builder:latest?-f? create --name appsource golang-static-builder:latest docker cp appsource:/go/src/httpserver ./ docker rm -f appsource docker rmi golang-static-builder:latest docker build -t httpserver-alpine:latest -f Dockerfile.alpine . 

Run the httpserver service container:
Alpine golang builder image dockerfile:

FROM golang:alpine WORKDIR /go/src COPY httpserver.go . RUN go build -o httpserver ./httpserver.go 
Iii. docker multi-phase build 1. dockerfile multi-phase build

Released in May 2017? Docker 172.165.0-ce? Docker officially provides a simple multi-stage build solution.
For multi-phase building, multiple from statements can be used in dockerfile. Each from instruction can use different basic images as one build phase, multiple? From? Multi-Stage building. Although the final generated image can only be the result of the last stage, the file in the pre-stage can be copied to the later stage.
The biggest Application Scenario for multi-stage building is to separate the compiling environment from the running environment.

# Compilation phase from golang: 1.10.3copy server. go/build/workdir/buildrun cgo_enabled = 0 GOOS = Linux goarch = amd64 goarm = 6 go build-ldflags '-w-S'-O Server # Run stage from scratch # compile copy the compilation result in the phase to the current image. Copy -- from = 0/build/Server/entrypoint ["/Server"]

The Copy command of dockerfile -- from = 0 parameter. When multiple from statements exist, 0 indicates the first stage. In addition to numbers, you can also name stages, such:

# Compilation phase from golang: 1.10.3 as buildercopy server. go/build/workdir/buildrun cgo_enabled = 0 GOOS = Linux goarch = amd64 goarm = 6 go build-ldflags '-w-S'-O Server # Run stage from scratch # compile copy the compilation result in the phase to the current image. Copy -- from = Builder/build/Server/entrypoint ["/Server"]

The copy-from command is copied from a separate image, using the local image name, the tag or tag ID available in the local or docker image repository .?

2. Stop at a specific build Stage

When building an image, you do not need to build each stage of the entire dockerfile file. You can specify the target build phase. Build with dockerfile and stop at the builder stage:
docker build --target builder -t builder:latest .
The following scenarios are suitable for stopping at a specific build phase:
A. debug a specific build phase
B. Enable all debugging or tools in the debug stage, while streamlining the production stage as much as possible
C. In the testing stage, the application fills in the test data, but in the production stage, the production data is used.

3. dockerfile multi-project construction

Multi-phase build allows you to build binary files of multiple projects and publish them in an image.

from debian as build-essentialarg APT_MIRRORworkdir /srcfrom build-essential as Acopy srcA .run makefrom build-essential as Bcopy srcB .run makefrom alpinecopy --from=A binA .copy --from=B binB .cmd ...
IV. C ++ image creation 1. c ++ Application Development

The hellodocker. cpp file is as follows:

#include <iostream>int main(){    std::cout << "Hello, Docker!" << std::endl;    return 1;}
2. Search for a c ++ Image

docker search gcc

Includes multiple versions of GCC, including the embedded version of GCC-arm-embedded-docker

3. Download the C ++ Image

docker pull gcc

4. View GCC Images

docker images

5. Use a GCC image to create an image


FROM gcc:latestRUN  mkdir -p /home/user/docker/src/HelloDockerCOPY HelloDocker.cpp /home/user/docker/src/HelloDockerWORKDIR /home/user/docker/src/HelloDockerRUN  g++ HelloDocker.cpp -o HelloDockerCMD ["./HelloDocker"]

Use the dockerfile to create an image:
docker build -t hellodocker:v1 .

View images:
docker images
Start image:
docker run -d hellodocker:v1
View container running status
docker ps

6. Use an executable program to create an image


FROM gcc:latestRUN  mkdir -p /home/user/docker/HelloDockerCOPY HelloDocker /home/user/docker/HelloDockerWORKDIR /home/user/docker/HelloDocker#RUN  g++ HelloDocker.cpp -o HelloDockerCMD ["./HelloDocker"]

Build an image:
docker build -t hellodocker:v1 .
Start container:
docker run -d hellodocker:v1

Docker Quick Start-create a docker Image

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.