Docker learning (4) some common operations

Abstract: Continue the learning journey of docker and practice some commonly used commands today: 1. Image related 1.1 List all the mirroring docker images of the machine The following operations are all based on ubuntu as the goal of the exercise. In addition: if some image files are no longer wanted, you can delete them with the following commands .

Continue the learning journey of docker, and practice some common commands today:

1. Image related

1.1 List all the operations behind the

docker images of the local machine


, all of which take ubuntu as the goal of the exercise.

In addition: if some image files are not wanted, you can delete them with the following

command . At this time, you can add the parameter -f to force deletion. If you don't know which parameters can be added to each command, you can use the docker command --help to view the help, such as:   bin docker rmi --help Usage: 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


2. Container-related

2.1 The most basic startup

docker run -it The meaning of the ubuntu
parameter -it can be viewed with docker run --help, not expanded

2.2 Execute the command after startup

docker run -it ubuntu echo 'hello world'
2.3 Specify the container name

at startup docker run -it --name 'myubuntu' The ubuntu
container name is a very interesting thing, which will be discussed later. After the above command is 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 fun name. The style of the command is roughly: what kind of _ who and who, such as The insane_lamarr in the picture literally means "crazy Lamarr". From these details, we can feel that the creators of docker are a bunch of fun-loving guys.

In addition to the container name, there are two more important columns: CONTAINER ID and STATUS, among which STATUS starts with Up, indicating that the container is running (Note: Whether the container is running, excluding the factors of human docker stop, it is very procedurally It is determined by the last command parameters of docker run. If no command parameters are specified at startup, /bin/bash is executed by default. If a command similar to echo "hello world" is specified that is executed in an instant, it will run immediately after running. Turn off, because the command has been executed), and the CONTAINER ID is used in many scenarios (for example: delete the container).

In addition, for the same image (such as ubuntu), if the container name is not specified by default, every time the container starts docker A unique name will be generated, which is a bit like OOP programming. The image is equivalent to the Class class definition, which is a read-only template, and the container is the running instance of the class. The hashcode of each new instance in java must be different. Therefore, the name of the docker container that is started each time is different, but the difference from OOP is that the instance in OOP dies, and all associated information is cleared. Even if the docker container is stopped, docker will still remember its last operating status.

A small experiment can be done. We have created a container named myubuntu just now:

docker run -it --name 'myubuntu' ubuntu If
this line of command is run again, it will report an error:

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 general idea is that the container name mybutun has been occupied by another container (ID is d1c261ad0b1e), either delete the original container or change the name.

The design ideas in this can be carefully pondered, and it is very reasonable to think about it: by analogy, when we write code, there are multiple instances of the same class new, and each instance will have its own different application scenarios, such as: the same An Order instance can be used in the business scenario of order creation, or in the return result of order query... The same is true for the docker image, the same ubuntu image file, some people use it to create a container to install nginx as a web server, some people use it to create a container to learn hadoop... In order to distinguish in a friendly way, so the names cannot conflict, and then, the container with the same name, installed software A today, after the game Turn it off, and you may continue to toss other things on this container tomorrow, so every time the container stops, it is impossible to completely discard all the information of the instance like the instance in OOP, otherwise it will be impossible to continue playing tomorrow.

2.5 Stop the running container

docker stop container name
2.6 Delete 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 the running container, directly execute the command

docker exec container Name command
For example   :

docker exec myubuntu apg-get update
2.8 Attach to the running container

docker attach container name
Note : After the command is run, there is no output on the screen on the mac, and I thought it was stuck, this is an illusion, just continue to enter the command directly , such as pwd and the like, you can see the results.

The attach command is not very easy to use. After entering the terminal, there is no way to exit without stopping the container. To exit, you can only enter exit, but this stops the container. Another disadvantage is that if multiple containers are attached to the same container at the same time , the result of operation in one window will be displayed to all windows synchronously.

It is recommended to use the following command instead:

docker exec -it container name sh
Of course, there are other ways to enter the container, such as mapping the network port 22 to a port on the local machine, start the ssh service in the container, and then enter the ssh connection, or use nsenter to combine the process id enters, but I personally think that these methods are too complicated to operate, far less simple than the above command

2.9 Save the changes made to

the container After doing a bunch of operations on the container, such as installing some software and deploying on the basis of ubuntu If you want to distribute some applications to other machines, the easiest way is to regenerate a new image for the container, and then others can directly docker pull your new image.

docker commit -a 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

view it in docker images

As can be seen from the figure, based on the original ubuntu, a new image named yjmyzz/ubuntu is generated, and then use the new image to create a container and try

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


3. volume (volume) related

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

3.1 Create a volume

docker run -it -v /Users/yjmyzz/docker_volumn:/opt/webapp --name myubuntu ubuntu /bin/bash
This command is slightly longer, but not complicated. Compared with the aforementioned startup container, it is only There is an extra part of -v /Users/yjmyzz/docker_volumn:/opt/webapp, which means to map the local /Users/yjmyzz/docker_volumn directory to /opt/webapp in the container. After the startup is successful, keep the current window not Exit, you can open a new terminal container, enter the container to verify,



you can try to modify the file /Users/yjmyzz/docker_volumn/index.html on the host machine, and then cat in the container to see the content, you should be able to see it immediately latest content.

Three big pits:

One:

The -v parameter can only write the first part of the front, -v /Users/yjmyzz/docker_volumn will not report an error, but the effect of this is on the latest version of docker (1.9.1) , only the local directory will be hung in the container, and any files of the local machine cannot be seen in the container, so be sure to remember to write the part after :

Second :

Permission problem, if you download a file from the Internet (not official from apple store) to this machine on the mac machine, the file and even the directory permission of the saved file will be set to special permission@, see the screenshot below:



this was originally after mac 10.5 A security improvement made, a program with this logo will be prompted when it is executed for the first time,



but a directory or file with such special permissions can not be seen in the docker container after it is hung in the container, that is, it has no right to read Pick. Solution:

ll -l@ -a
First use this to display the details of special permissions:



then use xattr -r -d details * to remove these special permissions (refer to the figure below), and then re-hook into the container, it will be normal



The third one is used:

The local directory mounted on the mac must be under ~/ (ie: the directory of the current user), a directory like /opt/www, even if it is given all permissions, after hanging in the container, I can only see the directory, but cannot read any files. There is no such problem on centOS.

In addition, you can use the command

docker inspect myubuntu to
view all the status of the container at this time, and you will see a long json output, similar to the following:

[
{
    "Id": "21d15713166ae83b022eea8806bd466da9917422e487e874cc098a0f1329dd48",
    "Created": "2016-01- 28T02:23:43.91086474Z",
    "Path": "/bin/bash",
    "

        "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": "",
        "User": "",
        "AttachStdin": true,
        "AttachStdout": true,
        "AttachStderr": true,
        "Tty": true,
        "OpenStdin": true,
        "StdinOnce": true,
        "Env": null,
        "Cmd": [
            "/bin/bash"
        ],
        "Image": "ubuntu",
        "Volumes": null,
        "WorkingDir": "",
        "Entrypoint": null,
        "OnBuild": null,
        "Labels": {},
        "StopSignal": "SIGTERM"
    },
    "NetworkSettings": {
        "Bridge": "",
        "SandboxID": "893c76e283a75e3eebb474bf1b5bce901a37778de3514b526312134fcc858d2c",
        "HairpinMode": false,
        "LinkLocalIPv6Address": "",
        "LinkLocalIPv6PrefixLen": 0,
        "Ports": {},
        "SandboxKey": "/var/run/docker/netns/893c76e283a7",
        "SecondaryIPAddresses": null,
        "SecondaryIPv6Addresses": null,
        "EndpointID": "a7fee41964177719fbd149df820bf66dbd976ebe7cea0b68497ae2fe4c06efc5",
        "Gateway": "172.17.0.1",
        "GlobalIPv6Address": "",
        "GlobalIPv6PrefixLen": 0,
        "IPAddress": "172.17.0.2",
        "IPPrefixLen": 16,
        "IPv6Gateway": "",
        "MacAddress": "02:42:ac:11:00:02",
        "Networks": {
            "bridge": {
                "EndpointID": "a7fee41964177719fbd149df820bf66dbd976ebe7cea0b68497ae2fe4c06efc5",
                "Gateway": "172.17.0.1",
                "IPAddress": "172.17.0.2",
                "IPPrefixLen": 16,
                "IPv6Gateway": "",
                "GlobalIPv6Address": "",
                "GlobalIPv6PrefixLen": 0,
                "MacAddress": "02:42:ac:11:00:02" The Mounts node in lines 90~97 describes the "volume" information mounted by the current container. ] }     }         }
            }






One last point: Currently, docker only supports using -v to create volumes when running (creating) a container. For an already started container, it is very difficult to dynamically add volumes. Although there are excellent people abroad who have realized the dynamic addition of volumes after the container is started, 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 volume

docker volume rm volume name
Note : When deleting a container, the volume associated with the container will not be deleted by default, so over time, the host may There will be a lot of "zombie" volumes that take up hard disk space. It is recommended to add the parameter -v every time you docker rm a container, so that the corresponding volume will be deleted when the container is deleted, but this will also have a side effect. If multiple containers are associated with the same volume at the same time, it may affect the other containers. Therefore, it is necessary to plan clearly when using volumes. It is best that one container corresponds to only one volume.

Tips: If you want to delete all volumes in batches, one by one rm is obviously too troublesome, you can quickly get it done in the following way:

a) Enter the docker virtual machine defaut

docker-machine ssh default
b) View the directory where the volume is located

docker volume inspect Volume name


c) Switch to sudo mode

sudo -i
d) Enter the root directory where the volume is located

cd /var/lib/docker/volumes/
  

The ls command in the above figure has already explained that the so-called data volumes are actually directories, which once again confirms the famous saying in linux that "everything is a file". The rest of the world knows everything, the evil

rm -rf *
, and 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 method, docker also allows to define a dedicated container, this Containers do nothing but store data. Such containers are called "data volume containers"

Example:

docker run -it -v /Users/yjmyzz/docker_volumn:/sites --name site_files kitematic/hello-world-nginx The command above echo 'only for nginx web files'
is exactly the same as the previous volume creation. Now we have a data volume container named site_files. Note: When creating a data volume container, the last command is usually a bit of soy sauce Echo, etc., is just a container for storing data anyway, no other commands need to be executed, and it does not even need to be in the startup state.

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 --volumes-from site_files above The key to using data volume containers is the same as before. Multiple containers can hang the same data volume container, and one container can also hang multiple data volume containers.

  

4. Network related

4.1 Port mapping

-p IP:host_port:container_port
The parameters above indicate that the hostport on the local 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:10080:80 --name my-nginx kitematic/hello-world-nginx sh /start.sh
This command is longer and combines all the previously learned parameters, Pay attention to the extra problem -p 0.0.0.0:10080:80, which means to map the local port 10080 to the container port 80 

Note : If you replace -p with an uppercase -P, the system will randomly map to a free port of the local machine No. 



4.2 Specify hostname

When a container is created by default, hostname is a unique random string, which is difficult to remember. It can be specified in docker run -h hostname name. This does not demonstrate



4.3 Network connection between containers

If there are two containers mysql , appserver, usually the appserver needs to access the database, so the appserver needs to be able to access mysql directly. The following shows how to achieve it:

a) First create the mysql container

docker run -it -h mysql --name mysql ubuntu /bin/bash
b) Then create appserver container  

docker run -it -h appserver --name appserver --link mysql:mysqlserver ubuntu /bin/bash
Note the --link mysql:mysqlserver, before the colon is the container name, after the colon is the container alias, in appserver after startup You can ping the mysql container directly, as shown in the figure below:


Note: This connection is one-way, that is, the appserver can ping the mysql container, but not vice versa. Moreover, when the latest version of docker is in ps, the Name column is no longer displayed in the format of A/B like the one mentioned on the Internet. To check whether a container is connected, the most direct way is to docker inspect the container name.

  

  

This article is Yunqi The original content of the community cannot be reproduced without permission. If you need to reprint, please send an email to [email protected]; if you find any content suspected of plagiarism in this community, please send an email to: [email protected]. com to report and provide relevant evidence. Once verified, this community will immediately delete the allegedly infringing content.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326100059&siteId=291194637