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

What are the common command operations in docker

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

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces what docker commonly used command operations are, the article is very detailed, has a certain reference value, interested friends must read it!

1. Image correlation

1.1 list all local images

The later operations all take ubuntu as the goal of the exercise.

In addition: if you don't want some image files, you can delete them with the following command

1.2 Delete Mirror

Docker rmi mirror Id (i.e. IMAGE ID in figure 1.1)

Sometimes deletion will fail, for example, a container is using the image file. At this time, you can add the parameter-f to force deletion. If you are not sure which parameters can be added to each command, you can use the

Docker command-- help

View help, such as:

Bin docker rmi-helpUsage: docker rmi [OPTIONS] IMAGE [IMAGE...] Remove one or more images-f,-- force=false Force removal of the image-- help=false Print usage-- no-prune=false Do not delete untagged parents

Second, container correlation

2.1 the most basic startup

Docker run-it ubuntu

The meaning of parameter-it, which can be viewed with docker run-- help, will not be expanded.

2.2 execute commands after startup

Docker run-it ubuntu echo 'hello world'

2.3 specify the container name at startup

Docker run-it-- name 'myubuntu' ubuntu

The container name is a very interesting thing, which will be discussed in a moment. After the above command has been run, exit with exit first so that you can learn other commands later.

2.4 View all containers that have been run recently

Docker ps-a

As can be seen from the figure, if the specified container name is not displayed at startup, docker will automatically generate a funny name, and the style of the command is roughly like: what kind of _ who, such as the insane_lamarr in the picture, literally means "Crazy Lamar". From these details, we can feel that the creators of docker are a bunch of guys who love to play.

In addition to the container name, there are two very important columns: CONTAINER ID and STATUS, in which STATUS begins with Up, indicating that the container is running (Note: whether the container is running or not, excluding the factor of artificial docker stop, is largely determined by the last command parameters of docker run. If no command parameters are specified at startup, / bin/bash is executed by default, and commands like echo "hello world" are executed instantly. When run is up, it will be turned off immediately, because the command has been executed), and CONTAINER ID will be used in many scenarios (for example, delete container)

In addition, for the same image (such as ubuntu), if the container name is not specified by default, each time the container starts docker will generate a unique name, which is a bit like OOP programming. The image is equivalent to the Class class definition and is a read-only template, while the container is the running instance of the class. The hashcode of each instance that comes out of the new in java must be different, so the name of the docker container launched each time is also different. It's just that unlike OOP, the instance in OOP is dead, all the associated information is cleared, and even if the docker container stops, docker still remembers its last running state.

You can do a little experiment. We just created a container called myubuntu:

Docker run-it-- name 'myubuntu' ubuntu

If this line of command runs again, an error will be reported:

Error response from daemon: Conflict. The name "myubuntu" is already in use by container d1c261ad0b1e. You have to remove (or rename) that container to be able to reuse that name.

The main idea is that the container name mybutun has been occupied by another container (ID is d1c261ad0b1e). Either delete the original container or change its name.

The design idea can be carefully considered, and it is also very reasonable to think about it: for analogy, when we write code, there are multiple instances of the same class new, each of which will have its own different application scenarios. For example, it is also an Order instance, which can be used in the business scenario of order creation and in the returned results of order query. The same is true of the image of docker, the same ubuntu image file. Some people use it to create containers to install nginx as web server, others use it to create containers to learn hadoop..., in order to distinguish in a friendly way, so the names cannot conflict. Then, a container with the same name installs software A today, closes it after playing, and may continue to do other things on this container tomorrow, so every time the container stops, it cannot be like an instance in OOP. Discard all the information of the instance completely, otherwise you won't be able to play again tomorrow.

2.5 stop running containers

Docker stop Container name

2.6 Delete a container

Docker rm Container ID

If the container is running, the above operation will fail. You can add the-f parameter to force deletion.

2.7 in a running container, execute the command directly

Docker exec Container name command

For example:

Docker exec myubuntu apg-get update

2.8 attach to already running containers

Docker attach Container name

Note: after the command runs, there is no output on the mac screen, I thought it was stuck, this is an illusion, just continue to enter the command, such as pwd and so on, you can see the result.

Attach this command is not very easy to use, after entering the terminal, there is no way to exit without stopping the container, to exit can only enter exit, but this will stop the container, another disadvantage is that if multiple containers attach to the same container at the same time, the results of operation in one window will be displayed to all windows synchronously.

It is recommended that you use the following command instead:

Docker exec-it container name sh

Of course, there are other ways to enter the container, such as network port 22 mapping a local port, starting the ssh service in the container, and then ssh connection to enter, or using nsenter to enter with process id, but personally, I think these methods are too complex and far less simple than the above command.

2.9 Save changes to the container

After doing a lot of operations on the container, such as installing some software and deploying some applications on the basis of ubuntu, and hoping to distribute it to other machines, the easiest way is to generate a new image of the container, and then others can directly docker pull your new image.

Docker commit-an author name-m submission reason-p container ID image name: version number

For example:

Docker commit-a 'yjmyzz'-m' test commit'-p d1c261ad0b1e yjmyzz/ubuntu:V2

After the submission is complete, you can

Docker images View

As can be seen from the figure, based on the original ubuntu, generate a new image called yjmyzz/ubuntu, and then create a container with the new image.

Docker run-it-- name 'myubuntu2' yjmyzz/ubuntu:V2

Third, volume (volumn) related

In the process of using a computer, we often plug in some external storage devices through usb, such as a U disk. After plugging in, we will be able to access the external storage device like a regular hard disk directory. Volume actually means something similar to this. You can "insert" a directory on the host machine into the container, and then the files on the host machine can be accessed directly in the container. Even if the container is deleted, the data in the volume may still be persisted.

3.1 create Volum

Docker run-it-v / Users/yjmyzz/docker_volumn:/opt/webapp-- name myubuntu ubuntu / bin/bash

This command is slightly longer, but it is not complicated. Compared with the startup container mentioned earlier, there is only an extra part of-v / Users/yjmyzz/docker_volumn:/opt/webapp, which means mapping the native / Users/yjmyzz/docker_volumn directory to the / opt/webapp in the container. After starting successfully, you can keep the current window from exiting. You can open a new terminal container and enter the container to verify it.

You can try to modify the / Users/yjmyzz/docker_volumn/index.html file natively in host, and then cat the contents in the container, and you should see the latest content right away.

Three big pits:

One is:

The-v parameter can only write the first part before, and the startup of-v / Users/yjmyzz/docker_volumn will not report an error, but the effect of this will be that on the latest version of docker (1.9.1), only the local directory will be hung into the container, and no local files can be seen in the container, so be sure to write the latter part.

Second:

Permission problem. If a file is sent to the local computer from the online down (not the apple store official) on Mac, the file or even the directory permission to save the file will be set to special permission @, as shown in the screenshot below:

This was originally a security improvement made after mac 10.5. programs with this logo will be prompted when executed for the first time.

However, after directories or files with such special permissions are hung in the container, they cannot be seen in the docker container at all, that is, they do not have the right to read them. How to handle it:

Ll-l @-a

Use this to display the details of special permissions first:

Then use xattr-r-d details * to remove these special permissions (see the following figure), and then hang them back into the container to work normally.

Third:

The local directory mounted on mac must be a directory like / opt/www under ~ / (that is, the current user's directory). Even if it is given all permissions, after it is hung in the container, it can only see the directory and cannot read any files. There is no such problem on centOS.

In addition, you can use the command

Docker inspect myubuntu

Looking at all the status of the container at this time, you will see a long json output, similar to the following:

[{"Id": "21d15713166ae83b022eea8806bd466da9917422e487e874cc098a0f1329dd48", "Created": "2016-01-28T02:23:43.91086474Z", "Path": "/ bin/bash", "Args": [], "State": {"Status": "running", "Running": true, "Paused": false, "Restarting": false, "OOMKilled": false, "Dead": false, "Pid": 1843, "ExitCode": 0, "Error": "" "StartedAt": "2016-01-28T02:26:09.414485616Z", "FinishedAt": "2016-01-28T02:25:43.868883111Z"}, "Image": "8693db7e8a0084b8aacba184cfc4ff9891924ed2270c6dec6a9d99bdcff0d1aa", "ResolvConfPath": "/ mnt/sda1/var/lib/docker/containers/21d15713166ae83b022eea8806bd466da9917422e487e874cc098a0f1329dd48/resolv.conf", "HostnamePath": "/ mnt/sda1/var/lib/docker/containers/21d15713166ae83b022eea8806bd466da9917422e487e874cc098a0f1329dd48/hostname", "HostsPath": "/ mnt/sda1/var/lib/docker/containers/21d15713166ae83b022eea8806bd466da9917422e487e874cc098a0f1329dd48/hosts" "LogPath": "/ mnt/sda1/var/lib/docker/containers/21d15713166ae83b022eea8806bd466da9917422e487e874cc098a0f1329dd48/21d15713166ae83b022eea8806bd466da9917422e487e874cc098a0f1329dd48-json.log", "Name": "/ myubuntu", "RestartCount": 0, "Driver": "aufs", "ExecDriver": "native-0.2", "MountLabel": "", "ProcessLabel": "," AppArmorProfile ":", "ExecIDs": null "HostConfig": {"Binds": ["/ Users/yjmyzz/docker_volumn:/opt/webapp"], "ContainerIDFile": "," LxcConf ": []," Memory ": 0," MemoryReservation ": 0," MemorySwap ": 0," KernelMemory ": 0," CpuShares ": 0," CpuPeriod ": 0," CpusetCpus ":", "CpusetMems": "," CpuQuota ": 0," BlkioWeight ": 0 "OomKillDisable": false, "MemorySwappiness":-1, "Privileged": false, "PortBindings": {}, "Links": null, "PublishAllPorts": false, "Dns": [], "DnsOptions": [], "DnsSearch": [], "ExtraHosts": null, "VolumesFrom": null, "Devices": [], "NetworkMode": "default", "IpcMode": "," PidMode ":" "UTSMode": "," CapAdd ": null," CapDrop ": null," GroupAdd ": null," RestartPolicy ": {" Name ":" no "," MaximumRetryCount ": 0}," SecurityOpt ": null," ReadonlyRootfs ": false," Ulimits ": null," LogConfig ": {" Type ":" json-file "," Config ": {}," CgroupParent ":", "ConsoleSize": [0 " 0], "VolumeDriver": "}," GraphDriver ": {" Name ":" aufs "," Data ": null}," Mounts ": [{" Source ":" / Users/yjmyzz/docker_volumn "," Destination ":" / opt/webapp "," Mode ":", "RW": true}], "Config": {"Hostname": "21d15713166a", "Domainname": "" "IPPrefixLen": 16, "IPv6Gateway": "," GlobalIPv6Address ":", "GlobalIPv6PrefixLen": 0, "MacAddress": "02:42:ac:11:00:02"}]

Finally, it is pointed out that at present, docker only supports creating volumes using-v when creating run containers. For a container that has already been start, it is very difficult to add volumes dynamically. Although there are some awesome people abroad who have realized adding volumes dynamically after the container starts, the process is very tortuous and cannot be used. If you are interested, you can refer to the following article.

Http://jpetazzo.github.io/2015/01/13/docker-mount-dynamic-volumes/

3.2 list all volumes

Docker volume ls

3.3 Delete Volum

Docker volume rm Volume name

Note: when deleting a container, the volumes associated with the container are not deleted by default, so over time, there may be a large number of "zombie" volumes on the host, taking up hard disk space. It is recommended to add the parameter-v to each docker rm container, so that the corresponding volume will be deleted when the container is deleted, but it also has a side effect. If multiple containers are associated with the same volume at the same time, other containers may be affected. Therefore, you should plan clearly when using volumes, and it is best to have only one volume per container.

Tips: if you want to delete all volumes in batches, one rm is obviously too troublesome, and you can do it quickly in the following ways

A) enter the docker virtual machine defaut

Docker-machine ssh default

B) View the directory where volume is located

C) switch to sudo mode

Sudo-I

D) enter the root directory where volume is located

Cd / var/lib/docker/volumes/

The ls command in the picture above has shown that the so-called data volumes are actually directories, which once again confirms the famous saying in linux, "everything is a file." the rest is known to everyone on earth, evil.

Rm-rf *

Finally, restart the virtual machine and return to the mac host

Docker-machine restart default

3.4 data volume container

If multiple containers want to share a piece of data, in addition to the above, docker allows you to define a dedicated container that does nothing but holds data. This container is called a "data volume container".

Example:

Docker run-it-v / Users/yjmyzz/docker_volumn:/sites-- name site_files kitematic/hello-world-nginx echo 'only for nginx web files'

The above command is exactly the same as before to create a volume. Now we have a data volume container called site_files. Note: when creating a data volume container, the final command is usually something like echo. Anyway, it is just a container for storing data, you don't have to execute other commands, and it doesn't even need to be started.

Then, when other containers are created, you can use it:

Docker run-d-- volumes-from site_files-- name nginx1 kitematic/hello-world-nginx sh. / start.sh

Note the above-volumes-from site_files is the key to using the data volume container, and the other is exactly the same as before. Multiple containers can hang the same data volume container, and one container can also hang multiple data volume containers.

IV. Network-related

4.1 Port Mapping

-p IP:host_port:container_port

The above parameters indicate that the hostport on the native IP is mapped to the container_port of the container. For example:

Docker run-it-v / Users/yjmyzz/Documents/Kitematic/hello-world-nginx/website_files:/website_files-p 0.0.0.0 Users/yjmyzz/Documents/Kitematic/hello-world-nginx/website_files:/website_files 10080-- name my-nginx kitematic/hello-world-nginx sh / start.sh

This command is longer, combining all the previously learned parameters, and note the extra problem-p 0.0.0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0

Note: if you replace-p with an uppercase-P, the system will randomly map to an idle port number on the local computer.

4.2 specify hostname

When creating a container by default, hostname is a unique random string, which is difficult to remember and can be specified in the name of docker run-h hostname. This will not be demonstrated.

4.3 Network connections between containers

If you have two containers, mysql and appserver, usually you need to access the database in appserver, so you need appserver to access mysql directly. The following shows how to do this:

A) create a mysql container first

Docker run-it-h mysql-- name mysql ubuntu / bin/bash

B) create the appserver container again

Docker run-it-h appserver-name appserver-link mysql:mysqlserver ubuntu / bin/bash

Note that the-link mysql:mysqlserver is the container name before the colon and the container alias after the colon. After startup, you can directly ping the mysql container in appserver, as shown below:

Note: this connection is unidirectional, that is, appserver can ping the mysql container, but not vice versa. And when the latest version of docker is in ps, the Name column is no longer displayed in the format of A docker inspect B as mentioned on the Internet before. the most direct way to check whether a container is connected is the name of the container.

The above is all the contents of the article "what are the common command operations in docker?" Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

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