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

How to build a Docker image

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

Share

Shulou(Shulou.com)05/31 Report--

This article focuses on "how to build a Docker image". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to build a Docker image.

Introduction to Docker Image

Docker images are superimposed by file systems. At the bottom is a boot file system (bootfs), with little interaction between Docker users and the boot file system, which is unmounted and moved to memory when the container is started.

The second layer is the root file system (rootfs), which sits on top of the boot file system. Rootfs can be one or more operating systems. Rootfs is always read-only.

Docker uses joint load (union mount) technology to load more read-only file systems on the rootfs tier. Joint loading refers to loading multiple file systems at the same time, but externally it looks like one file system. Joint loading overlays the various layers of file systems so that the final file system contains all the underlying files and directories.

Docker mirrors such a file system. One image can be placed on top of another. The image below becomes the parent image, and the bottom image becomes the base image.

Finally, when the container is launched from an image, Docker loads a read-write file system at the top level of the image. Programs running in Docker are executed in this read-write layer.

When Docker starts a container for the first time, the initial read and write layer is empty. When the file system changes, these changes are applied to this layer. For example, if you want to modify a file, the file is first copied from the read-only layer below the read-write layer to the read-write layer. A read-only version of the file still exists, but has been hidden by a copy of the file in the read-write layer.

This mechanism is called write-time replication, which is one of the technologies that make Docker powerful. Each read-only mirror is read-only and will never change. When you create a container, Docker builds a mirror stack and adds a read-write layer at the top of the stack. This read-write layer, coupled with the mirror layer below it and some configuration data, forms a container.

List Mirror

Docker images

The local images are stored in the / var/lib/docker directory of the Docker host, and all the containers are stored in the / var/lib/docker/containers directory.

The image is downloaded from the warehouse. The image is stored in the repository, which is stored in the Registry. The default Registry is a public Registry service, or Docker Hub, operated by Docker. You can think of an image repository as something similar to a Git repository, which includes images, layers, and mirror metadata.

Each image repository can store many images. For example, the ubuntu repository contains Ubuntu12.04, 12.10,13.04, and so on. Use the following fame and fortune to pull all the images in the ubuntu repository locally:

Docker pull ubuntu

To distinguish between different images in a repository, Docker provides tags (functions), each with a tag. We can specify a certain image in the warehouse by adding a colon and tag name after the warehouse name:

Docker run-t-I-- name new_container ubuntu:12.0 / bin/bash

There are two types of repositories in Docker Hub: the user warehouse (user repository) and the top-level warehouse (top-level repository). The images of the user repository are created by the user, while the top-level repository is officially managed by Docker.

The naming of the user repository consists of a user name and a warehouse name, such as jamtur01/puppet. The first is the user name, followed by the warehouse name.

In contrast, the top-level warehouse contains only the warehouse name, such as the ubuntu warehouse.

Pull the image

When you launch a container from an image with the docker run command, if the image is not local, Docker downloads the image from Docker Hub first. If no specific image tag is specified, Docker automatically downloads the image of the latest tag.

You can also use the docker pull command to pull the image locally in advance. The following command pulls all the basic fedora images:

Docker pull fedora

Only view the contents of the fedora image after pulling:

Docker images fedora

If you want to pull only one, you can tag the image name, for example, pull only Fedora 20:

Docker pull fedora:20

Find Mirror

You can use the docker search command to find publicly available images on all Docker Hub:

Docker search puppet

The above command finds all images with puppet and returns the following information:

NAME Warehouse name

DESCRIPTION description

STARTS user evaluation

Is OFFICIAL official?

Whether AUTOMATED is created by the automatic build process of Docker Hub.

Build an image

There are two ways to build an image:

Use the docker commit command

Use the docker build command and the Dockerfile file.

Currently, the docker commit command is not officially recommended, but a more flexible and powerful Dockerfile should be used to build Docker images.

Generally speaking, instead of actually creating a new image, we build an image based on an existing basic image, such as ubuntu, fedora, etc.

(1) create and log in a Docker Hub account

After signing up for a Docker Hub account, log in:

Docker login

After successfully logging in, the authentication information is saved in the ~ / .dockercfg file for later use. The ~ / .dockercfg file was not found in my test environment.

(2) create an image with docker commit command

First create a new container:

Docker run-I-t ubuntu / bin/bash

Next, install Apache:

Apt-get-yqq updateapt-get-y install apache2

Use exti to exit from the container and submit:

Docker commit Container ID ivan/apache2

The command specifies the container ID to commit the changes and the name of a target image repository.

You can also specify more data (including tags) when submitting the image to describe it in detail:

Docker commit-m = "A new custom image"-- author= "Ivan" container ID ivan/apache2:webserver

In this command, you specify the submission information of the image with-m,-author lists the author information of the image, and finally adds the: webserver tag to the image.

You can use the docker inspect command to view the details of the mirror:

Docker inspect ivan/apache2:webserver

(3) use Dockerfile to build an image

It is officially recommended to use Dockerfile definition files and docker build commands to build images. Dockerfile uses basic instructions based on DSL syntax (declarative programming language) to build a Docker image, and then uses the docker build command to build a new image based on the instructions in the Dockerfile.

First you need to create a folder, and then create the initial Dockerfile in this folder.

Mkdir static_webcd static_webtouch Dockerfile

The above code creates a directory of static_web to hold the Dockerfile, which is the build environment, which Docker calls context or build context. Docker uploads the build context and the files and directories in that context to the Docker daemon when building the image. This gives the Docker daemon direct access to code, files, or other data that you want to store in the process.

Let's add something to the Dockerfile:

# Version: 0.0.1FROM ubuntu:14.04MAINTAINER James Turnbull "james@example.com" RUN apt-get updateRUN apt-get install-y nginxRUN echo "Hi, I am in your container' > / user/share/nginx/html/index.htmlEXPOSE 80

The Dockerfile consists of a series of instructions and parameters. Each instruction, such as FROM, must be in uppercase and followed by an argument. Instructions in Dockerfile are executed sequentially from top to bottom.

Each instruction creates a new mirror layer and commits the mirror. Docker roughly follows the following process to execute the instructions in Dockerfile:

Docker runs a container from the integration image

Execute an instruction to make changes to the container

Perform an operation of type docker commit to submit a new mirror layer

Docker runs a new container based on the image you just submitted

Executes the next instruction in Dockerfile until all assignments have been executed.

If the Dockerfile does not end properly for some reason (such as an instruction that fails), you will get a usable image. This is helpful for debugging: you can run an interactive container based on the image and use the last created image to debug why the instruction failed.

Dockerfile also supports comments, and lines developed with # are considered comments.

The first instruction of each Dockerfile should be FROM. The FROM instruction specifies an existing image, and subsequent instructions will run based on this image, which is called the base image.

The MAINTAINER instruction is then written, which tells Docker the author of the image and the e-mail address of the author.

After that, three RUN instructions are specified. The RUN command runs the specified command in the current image. In this example, the installed APT repository is updated with the RUN directive, the nginx package is installed, and the / usr/share/nginx/html/index.html file is created.

By default, RUN instructions are executed in shell using the command wrapper / bin/sh-c. If you run on a platform that does not support shell or do not want to run in shell, you can also use RUN instructions in exec format, such as:

RUN ["apt-get", "install", "- y", "nginx"]

The EXPOSE directive is then used, which tells Docker that the application in the container will use the specified port of the container. Note that this does not mean that the port can be accessed automatically. For security reasons, Docker does not automatically open the port, but needs to specify which ports need to be opened when running the container using docker run.

Multiple EXPOSE instructions can be specified to expose multiple ports to the outside world.

(4) build a new image based on Dockerfile

Execute the docker build command, and all instructions in Dockerfile are executed and committed, and a new image is returned after the command ends successfully.

Cd static_webdocker build-t = "ivan/static_web".

The-t parameter sets the repository for the new image, or you can label the image at build time.

Docker build-t = "ivan/static_web:v1".

Of the above two commands. Tell Docker to go to the local current directory to find the Dockerfile file. You can also specify the location of the Dockerfile by specifying the source address of an Git repository.

Docker build-t = "ivan/static_web:v1" git@github.com:ivan/docker-static_web

During the build process, the build context is uploaded to the Docker daemon. If a .dockerkeeper file exists in the root directory of the build context, the contents of the file are split by lines, each of which is a file filter matching rule. Files that match are not uploaded to the Docker daemon. The matching rules of patterns in this file adopt filepath in Go language.

(5) instruction failed

If the instruction fails and returns the image built before the failure, we can start the container to load the image to check the cause of the failure.

(6) built cache

Because the result is submitted as a mirror at each step of the build process, the previous mirror layer is treated as a cache. For example, there is an error in the fourth step of the construction, and the fourth step is modified and then rebuilt. Since steps 1 to 3 have not been modified, the Docker will start to build from the fourth step. If some changes are made between steps 1 and 3, the Docker will build from the first instruction that changes.

Sometimes when building, you don't want to take advantage of the cache to add the-- no-cache flag:

Docker build-no-chace-t-"inva/static_web"

(7) Dockerfile template based on construction cache

The same instruction set template is usually used at the beginning of a Dockerfile file, such as

FROM ubuntu:14.04MAINTAINER James Turnbull "james@example.com" ENV REPERESHED_AT 2016-07-08RUN apt-get-qq update

The results of the first two instructions will not change, and the third instruction uses ENV to create a REFRESHED_AT environment variable that indicates the last update time of the image template. Finally, use the RUN instruction to run the apt-get-qq update instruction. When this directive runs, it flushes the cache of APT packages to ensure that each package to be installed is updated to the latest version.

For this template, if you want to refresh a build, you only need to modify the date in the ENV directive.

(8) View the new image

You can use docker images to view the newly built image.

Use the docker history command to learn more about how the image is built:

Docker history Mirror ID

(9) start the container from the new image

A nginx image has been built in the above example, so start it now to see if it works:

Docker run-d-p 80-- name static_web ivan/static_web nginx-g "daemon off"

The parameter-d in the command indicates that the container runs in daemon mode, and nginx-g "daemon off" is the command that needs to be run in the container.

The new parameter-p controls which network ports the Docker should expose to the host at run time. When running a container, Docker can allocate ports on the host machine in two ways:

Docker can randomly select a larger port number located at 49153 / 65535 on the host machine to map to the specified port in the container (80 in the example)

You can specify a specific port number in the Docker host to map to the specified port in the container (80 in the example).

Use the docker ps command to view port assignments.

You can also view the port mapping of the container through docker port:

Docker port Container ID 80

The fame and fortune above specifies the container ID and the container port number to view the mapping, and the port number mapped in the host will be returned.

The-p option of docker run can flexibly specify the port mapping relationship between the container and the host. For example, specify that the port in the container is mapped to a specific port of the Docker host:

Docker run-d-p 80:80-name static_web ivan/static_web nginx-g "daemon off"

Page can bind a port within a container to a port of a specific IP:

Docker run-d-p 127.0.0.1 daemon off 80-- name static_web ivan/static_web nginx-g "daemon off"

Bind port 80 in the container to port 80 of the host 127.0.0.1 IP.

You can also bind to a random port of a specific IP of a host:

Docker run-d-p 127.0.0.1-name static_web ivan/static_web nginx-g "daemon off"

Using the-P parameter, you can bind the port set by the EXPOSE directive in Dockerfile to the random port of the host:

Docker run-d-P-- name static_web ivan/static_web nginx-g "daemon off"

Use the / udp suffix to specify the UPD port binding when the port is bound.

After obtaining the binding IP and port of the host, you can use curl to test the nginx:

Curl 127.0.0.1: Port number

(10) Dockerfile instruction

CMD

Lets you specify a command to run when a container starts. Similar to the RUN directive, but the RUN directive is the command to run when the specified image is built, and CMD is the command to run when the specified container is started. This is the same as the docker run command that starts the container to specify the command to run.

CMD ["/ bin/bash", "- l]

The command to be run in the example is stored in an array structure. This tells Docker to run the command as specified. You can also skip arrays, where Docker adds / bin/sh-c before the specified command. This can lead to unexpected behavior when executing the command, so Docker recommends always using array syntax to set the command to be executed.

Specifying parameters when using the docker run command overrides the CMD command in Dockerfile.

Only one CMD instruction can be specified in Dockerfile. If more than one is specified, only the last CMD instruction will be used. If you want to run multiple processes or commands when starting the container, consider using a service management tool like Supervisor.

ENTRYPOINT

Similar to CMD, it also specifies some commands to run. If the ENTRYPOINT,CMD instruction or the command parameters specified by docker run are specified in Dockerfile, they are passed as arguments to the command specified by ENTRYPOIN again.

For example

ENTRYPOINT ["/ user/bin/nginx"]

Start after rebuilding the image:

Docker run-t-I ivan/static_web-g "daemon off;"

This way-g "daemon off;" is passed to ENTRYPOINT to form a command.

You can also use a combination of ENTRYPOINT and CMD instructions:

ENTRYPOINT ["/ user/bin/nginx"] CMD ["- h"]

When a container is started at this point, specifying the-g "daemon off;" parameter will cause the Nginx daemon to run in the foreground mode. If no parameters are specified when the container is started, the-h in CMD is passed to / user/bin/nginx, displaying help for Nginx.

This allows us to build an image that either runs a default command or allows you to specify overridden options or flags for the command through docker run.

You can also specify in docker run-- the entrypoint flag overrides the ENTRYPOINT directive.

WORKDIR

Used to set the working directory for a series of subsequent instructions in Dockerfile, or for the final container:

WORKDIR / opt/webapp/dbRUN bundle installWORKDIR / opt/webappENTRYPOINT ["rackup"]

In the example, the bundle install command is run after changing the working directory to / opt/webapp/db, then setting the working directory to / opt/webapp, and finally setting ENTRYPOINT.

The docker run command can override WORKDIR with-w.

ENV

Used to specify environment variables during image build:

ENV RVM_PATH / home/rvm/

This new environment variable can be used in any subsequent RUN instruction.

You can also use these environment variables directly in other instructions:

ENV TARGET_DIR / opt/appWORKDIR $TARGET_DIR

You can escape by adding a backslash to the environment variable if necessary.

These environment variables are persisted to any container created from our image.

You can also use docker run-e to pass environment variables, but these environment variables are only valid at run time:

Docker run-ti-e "WEB-PORT=8080" ubuntu env

USER

Used to specify which user to run the image under. You can specify a user name or UID, a group or GID, or a combination of the two:

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

You can also override the value specified by USER with the-u option in the docker run command.

If not specified, the default user is root.

VOLUME

Used to add volumes to containers created based on mirrors. A volume is a specific directory that can exist in one or more containers. This directory bypasses the federated file system and provides the following features:

Volumes can be shared and reused between containers

A container may not have to share volumes with other containers

Changes to the volume are effective immediately

Changes to the volume will not affect the update of the mirror

The volume will exist until no container uses it.

VOLUMN ["/ opt/project", "/ data"]

This directive will create two mount points for any container created based on this image.

ADD

Used to copy files and directories from the build environment to the image.

ADD software.lic / opt/application/software.lic

The ADD directive copies the software.lic file in the build directory to the image.

The location of the source file can be a URL, or a file name or directory in the build context. You cannot ADD files outside the build directory.

In ADD files, Docker determines whether the file source is a directory or a file by the characters at the end of the destination address parameter. If the destination address ends with /, then Docker thinks the source location points to the directory; if the destination address doesn't end with /, then Docker thinks the source location points to the file.

If the source file is a local archive (legitimate archive files include gzip, bzip2, and xz), Docker automatically unlocks the archive file:

ADD lastest.tar.gz / var/www/wordpress/

The above example unzips the archive file to the / var/www/wordpress/ directory. Docker unlocks the archive file in the same way as using the tar command with the-x option: what already exists in the original directory plus the contents in the archive file. If a file or directory with the same name as the archive file already exists in the directory of the destination, the file or directory in the destination will not be overwritten.

As of version 1.0.0, the archive files made by URL cannot be unzipped.

If the destination location does not exist, Docker will create the full path for us, including any directories in the path. The newly created files and directories have a schema of 0755, and UID and GID are 0. 0.

The ADD command invalidates the build cache.

COPY

Similar to ADD, it only copies files and does not extract or extract them.

COPY conf.d / etc/apache2/

This instruction copies the files from the local conf.d directory to the / etc/apache2/ directory.

The file source path must be in the build directory.

The UID and GID of any file or directory created by this directive will be set to 0. 0.

If the destination directory does not exist, Docker automatically creates all the required directory structures.

ONBUILD

Add a trigger to the mirror. When a mirror is used as a base mirror for other mirrors, triggers in that mirror are executed.

Triggers insert new instructions during the build process, which can be considered to be specified immediately after the FROM. Triggers can be any build instruction:

ONBUILD ADD. / app/srcONBUILD RUN cd / app/src & & make

However, FROM, MAINTAINER, and ONBUILD cannot be used for ONBUILD instructions to prevent recursive calls during Dockerfile construction.

Use the docker inspect container ID to view the ONBUILD instruction information of the images used by the container.

ONBUILD triggers are executed in the order specified in the parent image and can only be inherited once (that is, they can only be executed in the child image, not in the descendant image).

Push the image to Docker Hub

Docker push ivan/static_web

You can also build automatically, simply by connecting the repository that contains Dockerfile files in Github or BitBucket to Docker Hub. When the code is pushed to this code repository, an image build activity is triggered and a new image is created.

Click Create Automated Build under Create in the upper right corner of the Dockr Hub website, associate an Github account, and then confirm authorization on the Github website. After success, go back to Docker Hub, click "Create Auto-build", select a Github Repository and enter a description to create it.

Delete Mirror

Docker rmi ivan/static_web

From the output of the delete command, you can see the hierarchical file system of Docker, and each Deleted line represents a mirror layer being deleted.

The above operation will only delete the local image. If the image has been previously pushed to Docker Hub, it will still exist on Docker Hub. If you want to delete the image repository on Docker Hub, you need to log in to Docker Hub to delete it.

You can also specify a list of image names to delete multiple images:

Docker rmi ivan/apache2 ivan/static_web

Tips for deleting all mirrors:

Docker rmi 'docker images-a-Q'

Run your own Docker Registry

There are two options:

Take advantage of the private warehouse on Docker Hub

Run your own Registry.

Docker has open source the code to run Docker Registry, based on which you can run your own Registry.

(1) run Registry from the container

Docker run-p 5000Suzhou 5000 registry

Start a container for Registry applications and bind to port 5000 of the host.

After the completion of the run, enter the address in the browser: host IP:5000; to see the message: "docker-registry server", indicating that Registry Server started successfully.

(2) submit the image to your own Registry

The Registry container ran successfully, but could not be committed because I didn't know the hostname and I thought the localhost was incorrect.

It is OK to use 127.0.0.1 after testing.

First of all, label the existing images with a new Registry tag.

Docker tag Mirror ID 127.0.0.1:5000/ivan/static_web

Finally, submit the image.

Docker push 127.0.0.1:5000/ivan/static_web so far, I believe you have a deeper understanding of "how to build a Docker image". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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