docker installation and common commands

Centos installation docker

  • Install dependent packages
sudo yum install -y yum-utils device-mapper-persistent-data lvm2 
  • Set alicloud image source
sudo yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo 
  • Install docker CE
sudo yum install docker-ce
  • report errors
--> Processing Conflict: 1:docker-ce-cli-18.09.6-3.el7.x86_64 conflicts docker
--> Processing Conflict: 1:docker-ce-cli-18.09.6-3.el7.x86_64 conflicts docker-io
--> Processing Conflict: 3:docker-ce-18.09.6-3.el7.x86_64 conflicts docker
--> Processing Conflict: 3:docker-ce-18.09.6-3.el7.x86_64 conflicts docker-io
--> Finished Dependency Resolution
Error: docker-ce conflicts with 2:docker-1.13.1-96.gitb2f74b2.el7.centos.x86_64
Error: docker-ce-cli conflicts with 2:docker-1.13.1-96.gitb2f74b2.el7.centos.x86_64
 You could try using --skip-broken to work around the problem
 You could try running: rpm -Va --nofiles --nodigest
  • terms of settlement
# 1. To view installed docker s:
yum list installed | grep docker
docker.x86_64                           2:1.13.1-74.git6e3bb8e.el7.centos
docker-client.x86_64                    2:1.13.1-74.git6e3bb8e.el7.centos
docker-common.x86_64                    2:1.13.1-74.git6e3bb8e.el7.centos
# 2. Uninstall docker:
sudo yum remove -y docker-ce.x86_64 docker-client.x86_64 docker-common.x86_64
# 3. To delete a container image:
sudo rm -rf /var/lib/docker
# 4. Reinstall docker
sudo yum install docker-ce
  • Start docker
# Start and start automatically
sudo systemctl enable docker 
# Start docker service  
sudo systemctl start docker
  • Add docker user group (optional)
# 1. Establish Docker user group
sudo groupadd docker
# 2. Add current user to docker group
sudo usermod -aG docker $USER
  • Image acceleration configuration
# Accelerator address:
# Alibaba cloud console search container image service
# Enter the container image service and copy the accelerator address in the container image service at the bottom of the left
sudo mkdir -p /etc/docker
sudo tee /etc/docker/daemon.json <<-'EOF'
{
  "registry-mirrors": ["Your accelerator address"]
}
EOF
# Restart docker
sudo systemctl daemon-reload
sudo systemctl restart docker

Pull image

  • Image pull address:

    dockerhub

# Download Image: docker pull < image name: tag > for example: Download centos image
docker pull centos
docker pull sameersbn/redmine:latest
# View downloaded images
docker images
# Delete container
docker rm <Container name or ID>
# View container log
docker logs -f <Container name or ID>
# View running containers
docker ps
# View all containers, including those that have been stopped.
docker ps -a 
# Delete all containers
docker rm $(docker ps -a -q)
# Stop, start, kill specified container
docker start <Container name or ID> # Start container
docker stop <Container name or ID> # Start container
docker kill <Container name or ID> # Kill container
# Run docker run - d < other parameters > in the background
docker run -d -p 127.0.0.1:33301:22 centos6-ssh
# Exposed port: there are three forms of port mapping
docker -p ip:hostPort:containerPort # Map the host port of the specified address to the container port
# For example: docker -p 127.0.0.1:3306:3306 maps the native 3306 port to the container's 3306 port
docker -p ip::containerPort # Maps any available port of the specified address to the container port
# For example: docker -p 127.0.0.1::3306 maps the random available port of the machine to port 3306 of the container
docer -p hostPort:containerPort # Map the specified port of the native to the specified port of the container
# For example: docker -p 3306:3306 # Map the 3306 port of the native to the 3306 port of the container
# Mapping data volumes
docker -v /home/data:/opt/data # Here, / home/data refers to the directory address of the host, while the latter refers to the directory address of the container

GUI management

It is recommended to use portal as the GUI management scheme of container.
Official address: https://portainer.io/install.html
Installation command:

docker volume create portainer_data
docker run -d -p 9000:9000 -v /var/run/docker.sock:/var/run/docker.sock -v portainer_data:/data portainer/portainer

Visit your IP:9000 to enter the container management page.

docker common commands

This article only records the use of the docker command in most situations. If you want to know the details of each option, please refer to the official documents, which will only be recorded as your own notes in the future.

According to my own understanding, it is generally divided into the following categories:

  • Docker environment information - docker [info|version]
  • Container lifecycle management - docker [create|exec|run|start|stop|restart|kill|rm|pause|unpause]
  • Container | export ๐ž“œ
  • Container rootfs command - docker [commit|cp|diff]
  • Image warehouse - docker [login|pull|push|search]
  • Local image management - docker [build|images|rmi|tag|save|import|load]
  • Container resource management - docker [volume|network]
  • System log information - docker [events history logs]

``Starting from the use of docker command, sort out the following command structure diagram:

-Docker environment information

– info command

It is used to check whether Docker is installed correctly. It is generally used in combination with docker version command.

[](javascript:void(0)๐Ÿ˜‰

[devadmin@swarm1 ~]$ docker info
Containers: 43
 Running: 9
 Paused: 0
 Stopped: 34
Images: 140
Server Version: 17.09.0-ce
Storage Driver: overlay
 Backing Filesystem: xfs
 Supports d_type: false
Logging Driver: json-file
Cgroup Driver: cgroupfs
...

[](javascript:void(0)๐Ÿ˜‰

– version command

[](javascript:void(0)๐Ÿ˜‰

[devadmin@swarm1 ~]$ docker version
Client:
 Version:      17.09.0-ce
 API version:  1.32
 Go version:   go1.8.3
 Git commit:   afdb6d4
 Built:        Tue Sep 26 22:41:23 2017
 OS/Arch:      linux/amd64

Server:
 Version:      17.09.0-ce
 API version:  1.32 (minimum version 1.12)
 Go version:   go1.8.3
 Git commit:   afdb6d4
 Built:        Tue Sep 26 22:42:49 2017
 OS/Arch:      linux/amd64
 Experimental: false
[devadmin@swarm1 ~]$

[](javascript:void(0)๐Ÿ˜‰

Container operation and maintenance

– attach command

The docker attach command is very useful for developers. You can connect to the running container, observe the running status of the container, or interact with the main process of the container.

– inspect command

It is used to view the details of images and containers. By default, all information will be listed. You can specify the template format of output through the – format parameter to output specific information.

View container information (ps)

The docker ps command can view the CONTAINER ID, NAME, IMAGE NAME, port opening and binding, and COMMNAD executed after the container is started. The most common function is to find the container through ps_ ID to operate on a specific container.
docker ps displays the currently running container by default
docker ps -a view includes all containers that have been stopped
docker ps -l displays the latest container started (including those stopped)

Examples

[devadmin@swarm1 ~]$ docker ps -l
CONTAINER ID        IMAGE                                            COMMAND              CREATED             STATUS              PORTS                      NAMES
1cfb8ad8642e        regloc.com/test/settlequery:201711271708   "sh entrypoint.sh"   22 hours ago        Up 22 hours         0.0.0.0:18182->18182/tcp   settlequery.z4taavbos34np74za1bu674az.ncj2uocqbh15ljxhui0yccd9t
[devadmin@swarm1 ~]$ 

– list the images on the machine

# docker images 
REPOSITORY               TAG             IMAGE ID        CREATED         VIRTUAL SIZE
ubuntu                   14.10           2185fd50e2ca    13 days ago     236.9 MB
...

Among them, we can judge which server the image comes from according to the REPOSITORY. If there is no /, it means the official image, similar to username/repos_name refers to Github's personal public library, similar to regsistory example. com:5000/repos_ Name means private server.
The IMAGE ID column is actually an abbreviation. To display it completely, bring the -- no TRUNC option

2. Search image in docker index (search)

Usage: docker search TERM
# docker search seanlo
NAME                DESCRIPTION           STARS     OFFICIAL   AUTOMATED
seanloook/centos6   sean's docker repos         0

The search scope is the official image and all personal public images. The NAME column is followed by the NAME of the warehouse.

3. Drop down image or repository (pull) from docker registry server

Usage: docker pull [OPTIONS] NAME[:TAG]
# docker pull centos

The above command should be noted in docker v1 Before version 2, all images in the centos warehouse of the official image will be downloaded, but from v.13, the description in the official document has changed: will pull the centos:latest image, its intermediate layers and any aliases of the same id, that is, only images with a tag of latest (and other tags of the same images id) will be downloaded.
You can also specify a specific image:

# docker pull centos:centos6

Of course, it can also be pulled from someone's public warehouse (including his own private warehouse), such as docker pull username / repository <: tag_ name> :

# docker pull seanlook/centos:centos6

If you don't have a network or get images from other private servers, such as docker pull registry domain. com:5000/repos:<tag_ name>

# docker pull dl.dockerpool.com:5000/mongo:latest

4. Push an image or repository to the registry (push)

Corresponding to the pull above, it can be pushed to the Public, Private and Private servers of Docker Hub, but not to the Top Level Repository.

# docker push seanlook/mongo
# docker push registry.tp-link.net:5000/mongo:2014-10-27

registry.tp-link.net can also be written as IP, 172.29.88.222.
When the repository does not exist, the one push ed on the command line will be created as a private library for us, but the one created through the browser will be a public library by default.

5. Start a container (run) from the image

The docker run command will first create a writable container from a specific image, and then start it through the start command. The stopped container can be restarted and keep the original changes. There are many startup parameters of the run command. The following are some general instructions. Please refer to more parts http://www.cnphp6.com/archives/24899
When using docker run to create containers, the standard operations of Docker running in the background include:

  • Check whether the specified image exists locally. If it does not exist, download it from the public warehouse
  • Create and start a container using the image
  • Allocate a file system and mount a read-write layer outside the read-only image layer
  • Bridge a virtual interface from the bridge interface configured by the host to the container
  • Configure an ip address from the address pool to the container
  • Execute user specified applications
  • The container is terminated after execution
Usage: docker run [OPTIONS] IMAGE [COMMAND] [ARG...]

5.1 create a container using image and execute the corresponding command, and then stop

# docker run ubuntu echo "hello world"
hello word

This is the simplest way. It is almost no different from directly executing echo 'hello world' locally. In fact, it will start from the local ubuntu:latest image to a container and exit after executing the print command (docker ps -l can be viewed). It should be noted that there is a -- rm=true parameter by default, that is, stop the container and remove it from the file system after the operation is completed. Because Docker containers are too lightweight, users often delete and create new containers at any time.
After the container is started, a CONTAINER ID will be automatically generated randomly. This ID can be changed into IMAGE ID after the subsequent commit command

Use image to create container and enter interactive mode. The login shell is / bin/bash

# docker run -i -t --name mytest centos:centos6 /bin/bash
bash-4.1#

The -- name parameter above can specify the name of the container after startup. If it is not specified, docker will give us a name. Image CentOS: CentOS 6 can also be replaced by IMAGE ID (68edf809afe7), and a pseudo terminal will be started, but we can only see one or two processes through ps or top command, because the core of the container is the executed application, and the required resources are necessary for the operation of the application. In addition, there are no other resources, which shows that docker has a very high utilization of resources. At this time, after exiting with exit or Ctrl+D, the container will disappear (the disappeared container has not been completely deleted?)
(then, which TAG will be used to start images with different tags and the same IMAGE ID run

5.2 run a container and put it in the background

# docker run -d ubuntu /bin/sh -c "while true; do echo hello world; sleep 2; done"
ae60c4b642058fefcc61ada85a610914bed9f5df0e2aa147100eab85cea785dc

It will directly suspend the started container and run it in the background (this is called saas), and will output a CONTAINER ID. you can see the information of the container through docker ps, view its output docker logs ae60c4b64205 outside the container, or connect to the running terminal through docker attach ae60c4b64205. At this time, exit the container at Ctrl+C and disappear. Press ctrl-p ctrl-q to exit to the host, Keep the container running
In addition, if - d starts but the following commands end after execution, such as / bin/bash and echo test, the container will still terminate when it finishes doing so. And - D cannot be used with - rm at the same time
You can run memcached, apache, and so on in this way.

5.3 port and directory mapping from host to container

It is useful to map the port from the host to the container. For example, running memcached in the container, the port is 11211, and the host running the container can connect to the container's Internet_ IP: 11211 access. If you need to access memcached from other hosts, you can use the - p option, such as - p < host_ port:contain_ Port >, which can be written in the following ways:

-p 11211:11211 This is to bind all network cards (0) of the host by default.0.0.0)Port 11211 of the container to port 11211 of the container
-p 127.0.0.1:11211:11211 Bind only localhost Port 11211 of this interface
-p 127.0.0.1::5000
-p 127.0.0.1:80:8080

In fact, directory mapping is to "bind and mount" the path of the host to the directory of the container, which is more convenient for internal and external transmission of files. In the section of building a private server, in order to prevent the saved images from being deleted after the private server container stops, the submitted images should be saved to the mounted host directory. Easy to use, - v < host_ path:container_ Path >, add - v when binding multiple directories.

-v /tmp/docker:/tmp/docker

In addition, to establish a connection between two container s, you can use -- link. See the advanced section or Official documents.
Here is an example:

# docker run --name nginx_test \
> -v /tmp/docker:/usr/share/nginx/html:ro \
> -p 80:80 -d \
> nginx:1.7.6

Set up index. In / tmp/docker of the host HTML, you can http://localhost:80/ or http://host-ip:80 Visited.

6. Solidify a container into a new image (commit)

When we are making our own image, we will install some tools and modify the configuration in the container. If we don't commit and save it, the container will stop and start again, and these changes will disappear.
docker commit <container> [repo:tag]
The following repo:tag is optional
Only running containers can be submitted, that is, containers visible through docker ps,

View containers that have just run
# docker ps -l
CONTAINER ID   IMAGE     COMMAND      CREATED       STATUS        PORTS   NAMES
c9fdf26326c9   nginx:1   nginx -g..   3 hours ago   Exited (0)..     nginx_test

Start an existing container( run Is from image Create a new container and then start it). The following can also be used docker start nginx_test replace  
[root@hostname docker]# docker start c9fdf26326c9
c9fdf26326c9


docker run -i -t --sig-proxy=false 21ffe545748baf /bin/bash
nginx Service not started


# docker commit -m "some tools installed" fcbd0a5348ca seanlook/ubuntu:14.10_tutorial
fe022762070b09866eaab47bc943ccb796e53f3f416abf3f2327481b446a9503

-a "seanlook7@gmail.com"
Please note that when you commit a container repeatedly, you will get a new IMAGE ID every time. If the following repository:tag does not change, you can see through docker images that the repository:tag of the previously submitted image will become < none >: < none >, so try to avoid repeated submission.
In addition, observe the following points:

  • The commit container will only pause the container to ensure the consistency of the container file system, but it will not stop. If you want to make other changes to this container:
    • You can resubmit to get a new image2 and delete a new image1
    • You can also close the container, start with a new image1, continue to modify, and delete image1 after submitting image2
    • Of course, this will be very painful, so Dockerfile is generally used to build the final image. Refer to []
  • Although a new image is generated and you can see that it has a size of 100MB, you can quickly know from the commit process that it does not independently occupy 100MB of hard disk space, but only modifies it on the basis of the old image. They share most of the common "pieces".

lower

1. start/stop/restart the container (start/stop/restart)

A container can be run by creating a new one through run, or it can restart the container that has been stopped. However, start can no longer specify the instructions to run when the container is started, because docker can only have one foreground process.
When the container stop s (or Ctrl+D), it will exit after saving the status of the current container. The next time it starts, it will keep the changes it made when it was last closed. Moreover, the interface of each time you enter the attach is the same, which is the same as the first time you start run or commit.

CONTAINER_ID=$(docker start <containner_id>)
docker stop $CONTAINER_ID
docker restart $CONTAINER_ID

These commands can be used through a complete example: How does docker create a container to run background processes and provide shell terminals at the same time.

2. Connect to the running container (attach)

The container to be attached must be running. You can connect the same container to share the screen at the same time (similar to the attachment of the screen command).
The official document says that you can use CTRL-C to detach after attach, but in fact, after my test, if the container is currently running bash, CTRL-C is naturally the input of the current line and does not exit; If the container is currently running a process in the foreground, such as the access of nginx Log, CTRL-C will not only cause the container to exit, but also stop. This is not what we want. Detach means to leave the container terminal, but the container is still running. Fortunately, attach can bring -- sig proxy = false to ensure that CTRL-D or CTRL-C will not close the container.

# docker attach --sig-proxy=false $CONTAINER_ID

3. View the underlying information of image or container (inspect)

The object of inspect can be image, running container and stopped container.

View the inside of the container IP
# docker inspect --format='{{.NetworkSettings.IPAddress}}' $CONTAINER_ID
172.17.42.35

4. Delete one or more container s and image s (rm, rmi)

You may build or commit many images during use, and useless images need to be deleted. However, there are some conditions for deleting these images:

  • The same IMAGE ID may have multiple tags (possibly in different warehouses). First, you should delete the tags according to these image names. When the last tag is deleted, the image will be automatically deleted;
  • If multiple image names to be deleted are in the same REPOSITORY, you can use docker RMI < image_ ID > to delete the remaining tags at the same time; If you are in different repos, you still need to manually delete tags one by one;
  • When there is a container started by this image (even if it has been stopped), the image cannot be deleted;

TO-DO
How to view the dependency between image and container

Delete container
docker rm <container_id/contaner_name>

Delete all stopped containers
docker rm $(docker ps -a -q)

delete mirror
docker rmi <image_id/image_name ...>
Here is a complete example:

# docker images            <==
ubuntu            13.10        195eb90b5349       4 months ago       184.6 MB
ubuntu            saucy        195eb90b5349       4 months ago       184.6 MB
seanlook/ubuntu   rm_test      195eb90b5349       4 months ago       184.6 MB

Use 195 eb90b5349 After starting and stopping a container, delete the image
# docker rmi 195eb90b5349
Error response from daemon: Conflict, cannot delete image 195eb90b5349 because it is 
tagged in multiple repositories, use -f to force
2014/11/04 14:19:00 Error: failed to remove one or more images

delete seanlook In the warehouse tag     <==
# docker rmi seanlook/ubuntu:rm_test
Untagged: seanlook/ubuntu:rm_test

If you delete the image now, it will also be due to container The existence of cannot rmi
# docker rmi 195eb90b5349
Error response from daemon: Conflict, cannot delete 195eb90b5349 because the 
 container eef3648a6e77 is using it, use -f to force
2014/11/04 14:24:15 Error: failed to remove one or more images

First delete the container started by this image    <==
# docker rm eef3648a6e77

delete mirror                    <==
# docker rmi 195eb90b5349
Deleted: 195eb90b534950d334188c3627f860fbdf898e224d8a0a11ec54ff453175e081
Deleted: 209ea56fda6dc2fb013e4d1e40cb678b2af91d1b54a71529f7df0bd867adc961
Deleted: 0f4aac48388f5d65a725ccf8e7caada42f136026c566528a5ee9b02467dac90a
Deleted: fae16849ebe23b48f2bedcc08aaabd45408c62b531ffd8d3088592043d5e7364
Deleted: f127542f0b6191e99bb015b672f5cf48fa79d974784ac8090b11aeac184eaaff

Note that the above deletion process is a special example - the image is tag ged in mu lt iple warehouses and there are also started containers. Just follow the order indicated by < = = to proceed.

5. docker build uses this configuration to generate a new image

The build command can create images from Dockerfile and context:
docker build [OPTIONS] PATH | URL | -
The files in the above PATH or URL are called context. The process of building image will first transfer these files to the server of docker.
If the PATH is a separate Dockerfile directly, no context is required; If the URL is a Git warehouse address, a copy of git clone will be automatically sent to the local temporary directory during the process of creating the image, which will become the context of this build. No matter what the specified PATH is, Dockerfile is crucial. Please refer to Dockerfile Reference.
Take the following example:

# cat Dockerfile 
FROM seanlook/nginx:bash_vim
EXPOSE 80
ENTRYPOINT /usr/sbin/nginx -c /etc/nginx/nginx.conf && /bin/bash

# docker build -t seanlook/nginx:bash_vim_Df .
Sending build context to Docker daemon 73.45 MB
Sending build context to Docker daemon 
Step 0 : FROM seanlook/nginx:bash_vim
 ---> aa8516fa0bb7
Step 1 : EXPOSE 80
 ---> Using cache
 ---> fece07e2b515
Step 2 : ENTRYPOINT /usr/sbin/nginx -c /etc/nginx/nginx.conf && /bin/bash
 ---> Running in e08963fd5afb
 ---> d9bbd13f5066
Removing intermediate container e08963fd5afb
Successfully built d9bbd13f5066

The PATH above is, Therefore, all files in the current directory (excluding those in. Dockeignore) will be tar packaged and transferred to docker daemon (usually on the local machine). From the output, we can send build context, Finally, there is a process of Removing intermediate container. You can retain the container by -- rm=false.
TO-DO
docker build github. COM / cracker / docker Firefox failed.

6. tag the image

Tag has two main functions: one is to give an easy to understand name for the image, and the other is to re specify the warehouse of the image through docker tag, so that it can be automatically submitted to the warehouse when push ing.

Will be the same IMAGE_ID All tag๏ผŒMerge into a new
# docker tag 195eb90b5349 seanlook/ubuntu:rm_test

Create a new one tag๏ผŒKeep the old record
# docker tag Registry/Repos:Tag New_Registry/New_Repos:New_Tag

7. Check the container information (ps)

The docker ps command can view the CONTAINER ID, NAME, IMAGE NAME, port opening and binding, and COMMNAD executed after the container is started. Often find container through ps_ ID.
docker ps displays the currently running container by default
docker ps -a view includes all containers that have been stopped
docker ps -l displays the latest container started (including those stopped)

8. View the running processes in the container (top)

The < top / bin / container command is not necessarily running in the container, and the < top / bin command is not necessarily running in the container_ id/container_ Name > is very useful. In fact, using ps -ef|grep docker on the host can also see a group of similar process information. It is right to regard the process in the container as the child process that starts docker on the host.

9. Other orders

docker also has some commands that are not commonly used, such as login, cp, logs, export, import, load, kill, etc. they are relatively simple. Please refer to the official website.

events, history, and logs commands

These three commands are used to view the system log information of Docker. The events command will print out real-time system events; The history command will print the historical version information of the specified image, that is, the command record of constructing each layer of the image; The logs command prints out the running logs of the processes in the container.

docker events [options]: get real-time events from the server.

OPTIONS Description:

  • **-f: * * filter events according to conditions;
  • **– since: * * display all events after the specified timestamp;
  • **– until: * * the running time is displayed until the specified time;

docker history [options] image: view the creation history of the specified image.

OPTIONS Description:

  • **-H ๐Ÿ˜—* Print the image size and date in a readable format. The default is true;
  • **–no-trunc ๐Ÿ˜—* Display complete submission records;
  • **-q ๐Ÿ˜—* Only submit record ID s are listed.

docker logs [options] container

Options:
        --details        Show more information
    -f, --follow         Trace log output. The last line is the log with the current timestamp
        --since string   Displays logs from a specific time or period
        --tail string    How many lines of logs are displayed from the end of the log? The default is all
    -t, --timestamps     presentation time stamp 

Tags: Linux Docker

Posted by csxpcm on Wed, 25 May 2022 16:53:53 +0300