Table of contents:
- What is a container?
- Container life case?
- Why do you need containers?
- Container life cycle
- Container OOM
- Container exits abnormally
- Container paused
- Container command list
- Detailed explanation of container commands
- docker create
- docker run
- docker ps
- docker logs
- docker attach
- docker exec
- docker start
- docker stop
- docker restart
- docker kill
- docker top
- docker stats
- docker container inspect
- docker port
- docker cp
- docker diff
- docker commit
- docker pause
- docker unpause
- docker rm
- docker export
- docker wait
- docker rename
- docker container prune
- docker update
- Container operation case
- Basic container operations
- Container state migration
- Container batch processing tips
- Container interaction mode
- attached mode
- detached mode
- interactive mode
- Container and host content replication
- Container automatically deleted
- Container automatically restarts
- Container environment variable settings
- View container details
- Container executes single line command
- Container image import and export
- View container logs
- Container resource view
- Comprehensive actual combat 1. Mysql containerized installation
- Comprehensive actual combat 2. Redis containerized installation
- The reason for the emergence of Redis
- What is Redis
- Redis application scenarios
- Redis life case
- Redis container creation
- Comprehensive practical practice three, C++ container production
- what is the source
- What is mirroring
- Mirror source
- Dayuan of Science and Technology of China
- Make a c++ container
- Comprehensive practical experience 4. SpringBoot container production
- Comprehensive actual combat 5. Container resource update
1. What is a container?
In layman's terms, a container is the running entity of an image. The image is a static read-only file, while the container has a writable file layer required at runtime, and the process in the container is in a running state. That is, the container runs the real application process. Containers have five states: initially created, running, stopped, paused, and deleted. Although the essence of a container is a process running on the host, the container has its own independent namespace isolation and resource limitations. In other words, inside the container, you cannot see the processes, environment variables, network and other information on the host. This is the essential difference between the container and the process running directly on the host. A container is a runnable instance created based on an image and exists independently. One image can create multiple containers. When running a containerized environment, a read-write copy of this file system is actually created inside the container. This will add a container layer that allows modification of the entire copy of the image
2. Container life cases?
Mirrors and containers are equivalent to rough houses provided by developers, but the decorations of the two families are completely different. Or we have all learned object-oriented languages such as Java or C++. It can be understood that the image is the basic class, and the container is an object instantiated. The content inside will be different unless the user needs it.
3. Why do we need containers?
The image is a static file and cannot provide services, just like I took a Linux or Windows CD. Only when it is installed on the host and run can it provide external services and we can use it. What benefits do containers bring? Please refer to our previous explanation of why virtualization and containerization are necessary.
4. Container life cycle
A container's lifecycle is the possible states the container may be in.
- 1created:Initially created state
- running: running status
- stopped: stopped state
- paused: paused state
- deleted: deleted status
The conversion relationship between each life cycle is shown in the figure:
- docker create: After creating the container, it does not start running immediately, and the container enters the initial construction state;
- docker run: Create a container, start running immediately, and enter the running state;
- docker start: Container changes to running state;
- docker stop: The container will enter the stopped state;
- docker kill: When the container fails (crash), execute kill (power off), and the container will enter the stopped state. This
- The operation is easy to lose data, so it is not recommended to use it unless necessary;
- docker restart: Restart the container and the container enters the running state;
- docker pause: The container enters the paused state;
- docker unpause: Cancel the pause state and the container enters the running state;
- docker rm: Delete the container and the container enters the deleted state.
- Killed by out-of-memory (terminated due to insufficient memory): The host memory is exhausted, also known as OOM: unplanned termination. At this time, the container that consumes the most memory needs to be killed.
- Container process exitde (abnormal termination): After the container is terminated, the Should restart? selection operation will be entered:
- yes needs to be restarted, and the container executes the start command to enter the running state.
- no does not require restarting, the container will enter the stopped state.
Container OOM
Docker is divided into three situations when handling OOM events
- An OOM event is triggered if an application in a container exhausts the memory quota allocated to the container by the host system. For example, in a container, a web service is deployed. Assume that the upper limit of memory allocated by the host to this container is 1G. When the memory requested by the script is greater than 1G, this container will trigger an OOM event. In this case, the container will be forced to close. However, it should be noted that it is not the Docker Daemon that closes the container at this time, but the host operating system. Because a container is actually a group of processes running in the host operating system. The host operating system sets resource limits for this group of processes through cgroups. When the resources requested by these processes reach the upper limit, the host operating system triggers Kernel OOM events, so it is ultimately the host kernel that shuts down these processes.
- If the user does not want to close the container, they can select --oom-kill-disable to disable OOM-Killer. When using this parameter, you still need to pay attention. If you use -m to set the memory upper limit of this container, then when the container reaches the upper limit of memory resources, the host will not shut down the container, but it will not continue to allocate resources to this container. At this time, the container will be in hung state. It is only necessary to contain the worst-case scenario within a certain range and prevent it from spreading.
- If the user uses --oom-kill-disable but does not use -m to set the upper limit, the container will use as much host memory resources as possible. In other words, the host will use as much memory as it has.
Container exits abnormally
There is an Init process inside each container, and all other processes in the container are children of this process. The running container is because the Init process is running. If a child process exits for some reason, its parent process will also exit synchronously until the Init process also exits. When the Init process exits, it means that the container is closed. Ocker currently has no way of knowing whether the process exit at this time is a normal exit or an abnormal exit. When a container is shut down, the Docker Daemon will try to change the container from the Stopped state to the Running state again. Only containers with the --restart parameter set will be attempted by Docker Daemon, otherwise the container will remain stopped.
Container paused
Docker "robbed" this container of CPU resources. Other resources, such as Memory resources, Network resources, etc., remain untouched. As a result, the process that has lost CPU resources will not be scheduled by the host kernel system, so the container is in a "frozen" state.
5. Container command list
6. Detailed explanation of container commands
docker create
Function
Create a new container but don't start it
grammar
docker create [OPTIONS] IMAGE [COMMAND] [ARG...]
Alias
docker container create
key parameter
- -i: Run the container in interactive mode, usually used together with -t;
- -P: Random port mapping, the container’s internal port is randomly mapped to the host’s port
- -p: Specify port mapping, the format is: host (host) port: container port
- -t: Reassign a pseudo input terminal to the container, usually used together with -i;
- --name="nginx-lb": Specify a name for the container;
- -h "mars": Specifies the hostname of the container;
- -e username="ritchie": Set environment variables;
- --cpuset-cpus="0-2" or --cpuset-cpus="0,1,2": Bind the container to the specified CPU to run;
- -m: Set the maximum memory used by the container;
- --network="bridge": Specifies the network connection type of the container;
- --link=[]: Add a link to another container;
- --volume, -v: Bind a volume
- --rm :shell automatically deletes the container when exiting
- --restart: Automatically restart
Sample
docker create --name mynginx nginx:latest
docker run
Function
Create a new container and run a command
grammar
docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
Alias
docker container run
key parameter
- -d: Run the container in the background and return the container ID; this parameter is more than create
- -i: Run the container in interactive mode, usually used together with -t;
- -P: Random port mapping, the container’s internal port is randomly mapped to the host’s port
- -p: Specify port mapping, the format is: host (host) port: container port
- -t: Reassign a pseudo input terminal to the container, usually used together with -i;
- --name="nginx-lb": Specify a name for the container;
- -h "mars": Specifies the hostname of the container;
- -e username="ritchie": Set environment variables;
- --cpuset-cpus="0-2" or --cpuset-cpus="0,1,2": Bind the container to the specified CPU to run;
- -m: Set the maximum memory used by the container;
- --network="bridge": Specifies the network connection type of the container;
- --link=[]: Add a link to another container;
- --volume, -v: Bind a volume
- --rm :shell automatically deletes the container when exiting
- --restart: Automatically restart
Sample
docker ps
Function
list containers
grammar
docker ps [OPTIONS]
Alias
docker container ls, docker container list, docker container ps
key parameter
- -a: Display all containers, including those that are not running.
- -f: Filter the displayed content based on conditions.
- --format: Specify the template file for the return value. Such as json or table
- -l: Display the latest container.
- -n: List the n most recently created containers.
- --no-trunc: Do not truncate output.
- -q: Silent mode, only the container number is displayed.
- -s: Display the total file size.
Sample
docker ps -a
docker logs
Function
View container logs
grammar
docker logs [OPTIONS] CONTAINER
Alias
docker container logs
key parameter
-f,--follow: Track log output
--since: Display all logs at a certain start time
-t,-- timestamps: display timestamps
-n, --tail: list only the latest N container logs
Sample
docker attach
Function
Connect to a running container.
grammar
docker attach [OPTIONS] CONTAINER
Alias
docker container attach
key parameter
--sig-proxy: Whether to proxy all signals. The default is true. If set to false, exiting will not affect the container. Otherwise, exiting will cause the container to exit.
Sample
The message is displayed as
- CONTAINER ID: Container ID.
- IMAGE: The image used.
- COMMAND: The command to run when starting the container.
- CREATED: The creation time of the container.
- STATUS: Container status.
- PORTS: The port information of the container and the connection type used (tcp\udp).
- NAMES: Automatically assigned container names.
docker exec
Function
Execute command in container
grammar
docker exec [OPTIONS] CONTAINER COMMAND [ARG...]
Alias
docker container exec
key parameter
- -d: Detached mode: run in the background
- -i : Keep STDIN open even if not attached
- -t: allocate a pseudo terminal
- -e: Set environment variables
- -u,--user: Specify user "<name|uid>[:<group|gid>]"
- -w,--workdir: Specify the working directory
Sample
#在容器 mynginx 中以交互模式执行 echo:
docker exec -it mynginx echo "Hello world"
#在容器 mynginx 中以交互模式打开 shell:
docker exec -it mynginx bash
#通过 id 进去, docker ps 可以看到容器 id
docker exec -it 5706674cc67e bash
docker start
Function
Start a stopped container
grammar
docker start [OPTIONS] CONTAINER [CONTAINER...]
Alias
docker container start
Sample
docker start mynginx
docker stop
Function
Stop a running container
grammar
docker stop [OPTIONS] CONTAINER [CONTAINER...]
Alias
docker container stop
key parameter
-s: signal sent
Sample
docker stop mynginx
docker restart
Function
Restart container
grammar
docker restart [OPTIONS] CONTAINER [CONTAINER...]
Alias
docker container restart
key parameter
-s: send signal
Sample
docker restart mynginx
docker kill
Function
Force quit container
grammar
docker kill [OPTIONS] CONTAINER [CONTAINER...]
Alias
docker container kill
key parameter
-s: signal sent
Precautions:
Docker stop sends the SIGTERM signal, and docker kill sends the SIGKILL signal.
Sample
docker kill mynginx
docker top
Function
View process information running in the container, supports ps command parameters.
grammar
docker top CONTAINER [ps OPTIONS]
Alias
docker container top
Precautions
There may not be a /bin/bash terminal to interactively execute the top command when the container is running, and the container may not have the top command. You can use docker top to view the processes running in the container.
Sample
#查看容器进程信息
docker top mynginx
docker stats
Function
Displays the usage of container resources, including: CPU, memory, network I/O, etc.
grammar
docker stats [OPTIONS] [CONTAINER...]
Alias
docker container stats
key parameter
- --all, -a: Display all containers, including those that are not running.
- --format: Specify the template file for the return value. Such as table, json
- --no-stream: Display the current status and exit directly, no longer updating in real time.
- --no-trunc: Do not truncate output.
Return message
- CONTAINER ID and NAME: Container ID and name.
- CPU % and MEM %: The percentage of CPU and memory used by the container.
- MEM USAGE / LIMIT: The total memory being used by the container, and the total amount of memory allowed to be used.
- NET I/O: The amount of data sent and received by a container through its network interface.
- BLOCK I/O: The amount of data the container reads and writes from block devices on the host.
- PIDs: The number of processes or threads created by the container.
Sample
docker container inspect
Function
View container details
grammar
docker container inspect [OPTIONS] CONTAINER [CONTAINER...]
key parameter
- -f: Specifies the template file for the return value. Such as table, json
- -s: Display the total file size.
Precautions:
- docker inspect will automatically check whether it is an image or a container and then display the trust information
Sample
docker container inspect mynginx
docker port
Function
Used to list port mappings for a specified container, or to find a PRIVATE_PORT NAT to a public-facing port.
grammar
docker port CONTAINER [PRIVATE_PORT[/PROTO]]
Alias
docker container port
Sample
docker port mynginx
docker cp
Function
Copy files between container and host
grammar
docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH|-
docker cp [OPTIONS] SRC_PATH|- CONTAINER:DEST_PATH
Alias
docker container cp
Sample
#将主机/www/目录拷贝到容器 mynginx 的/www 目录下。
docker cp /www/ mynginx:/www/
#将容器/www/目录拷贝到主机的/wwwbak 目录下。
docker cp mynginx:/www/ /wwwbak/
docker diff
Function
Check for changes to the file structure in the container.
grammar
docker diff CONTAINER
Sample
docker diff mynginx
docker commit
Function
Create a new image from the container.
grammar
docker commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]
parameter
- -a: The submitted image author;
- -c: Use Dockerfile instructions to create the image; you can modify the startup instructions
- -m: Description text when submitting;
- -p: Pause the container when committing.
Sample
docker commit c3f279d17e0a maxhou/mynginx:v01
docker pause
Function
Pause all processes in the container.
grammar
docker pause CONTAINER [CONTAINER...]
Alias
docker container pause
Sample
docker pause mynginx
docker unpause
Function
Restore all processes in the container
grammar
docker unpause CONTAINER [CONTAINER...]
Alias
docker container unpause
Sample
docker unpause mynginx
docker rm
Function
Remove stopped containers
grammar
docker rm [OPTIONS] CONTAINER [CONTAINER...]
Alias
docker container rm
key parameter
-f: Forcefully delete a running container through the SIGKILL signal
Sample
#删除 mynginx 容器
docker stop mynginx
docker rm mynginx
#删除所有停止的容器
docker rm $(docker ps -a -q)
docker export
Function
Export container contents as tar file
grammar
docker export [OPTIONS] CONTAINER
Alias
docker container export
key parameter
-o: Write to file.
Sample
#导出 nginx 为 tar
docker export -o mynginx202203.tar mynginx
docker wait
Function
Blocks the run until the container stops, then prints out its exit code.
grammar
docker wait CONTAINER [CONTAINER...]
Alias
docker container wait
Sample
docker wait mynginx
docker rename
Function
double naming container
grammar
docker rename CONTAINER NEW_NAME
Alias
docker container rename
Sample
docker rename mynginx myweb
docker container prune
Function
Remove all stopped containers
grammar
docker container prune [OPTIONS]
key parameter
-f, --force: Do not prompt for confirmation
Sample
docker container prune
docker update
Function
Update container configuration
grammar
docker update [OPTIONS] CONTAINER [CONTAINER...]
Alias
docker container update
key parameter
- --cpus: cpu number
- --cpuset-cpus : Which cpu to use
- --memory :memory limit
- --memory-swap: swap memory
- --cpu-period: is used to specify how long the container's use of the CPU should be reallocated.
- --cpu-quota: is used to specify the maximum amount of time that can be used to run this container during this cycle.
Sample
#更新内存
docker update -m 400m myweb
7. Container operation cases
Basic container operations
Create a container through nginx image file
List of containers (including running containers)
Stop the currently running container
List of containers (including running and exited containers)
Container deletion
Container state migration
First we create the container
Through docker ps we can see that the container status is created
Start the container through docker start
You can see that the container is running through docker ps
Containers can be stopped via docker stop
Start the container again and kill the container
Start the container, then pause the container
restore container
Restart the container and you can see that the startup time of the container has become shorter.
Containers can be deleted through docker rm
Container batch processing tips
- -a: Indicates printing all container information, including running and exited containers
- -q: indicates that only the container ID is returned
- -f: indicates filtering based on the given conditions. Equivalent to the --filter option.
Note: Other commands can also be compared when doing batch processing, such as batch stop docker containerstop $(docker container ps -aq)
Container interaction mode
attached mode
- -p 80:80 represents port mapping. The first port represents the port mapped to the host, and the second port represents the port mapped to the Docker container. This will be explained in detail in the network chapter.
- Creating a container through the above method is in attached mode, so that the container will run in the foreground.
- When accessing the server URL, the command window will print a log every time it is accessed. The logs of the Docker container will be displayed in the window in real time and occupy this port.
- If you are on a Linux server, pressing Ctrl+C will stop the Docker service. It is easy to misoperate, so we need a better and more stable mode, which corresponds to the detached mode.
- attached mode is only applicable to the debugging phase of containers and programs
- Let’s practice the usage of attached mode
- Step 1: Create a running container in attached mode and map it to port 80 of the host
- Step 2: Access port 80 of the server, use a browser to access the server IP or domain name, access port 80 by default
You can see that the nginx homepage has been displayed on the browser. When we refresh the access, we find that some relevant logs will be printed on the standard output.
Step 3: Type Ctrl + C
detached mode
- Add a -d or --detach option to the docker container run -p 80:80 nginx command to indicate detached mode, that is, execute in the background
- Runs in the background, only the container ID is displayed after startup, and any command can be entered
- Even if the window is closed, it will continue to run. To stop and delete the container, you need to use shell commands, which reduces a lot of misoperations.
- It is recommended to use attached mode instead of
- Let’s practice the usage of detached mode
- Step 1: Create a container in detached mode and map port 80
- Step 2: Visit the server URL with the browser and check the background log
- Refresh the browser and you can see that the relevant logs have been printed in the background.
Dynamic tracking log: The background log window will only print the log once. If you want to dynamically track the log, you can add the -f
option; if you want to turn off the log tracking mode, you can type Ctrl+C to end
Convert detached mode to attached mode
interactive mode
After we create a container, we may need to get some information or execute some commands inside the container, and we need to enter interactive mode. For example, after creating an Ubuntu container, if you need to enter various Shell commands into the system to interact with the system, you need to enter the interactive mode.
Create a running container and enter interactive mode
-i: Keep the container running. Usually used together with -t. After adding the two parameters it, the container will automatically enter the container after it is created. After exiting the container, the container will automatically close
-t: Reassign a pseudo input terminal to the container , usually used together with -i
to enter interactive mode for an already running container
Exit interactive mode: Enter exit in an interactive shell
Container and host content replication
We start an nginx service
Compile an index.html file on the host machine
Copy host files to the container
Enter the container to view
Container automatically deleted
To start an nginx, we specify the --rm option
Stop container
Check again whether the container exists and find that the container has been automatically deleted.
Container automatically restarts
Container restart options are as follows:
- docker run --restart=no [container name]: The default value is not to restart automatically
- docker run --restart=on-failure:3 [container name] : on-failure If the exit status of the container is not 0, then
- Docker automatically restarts the container, and you can also specify the number of restarts. If the container fails to start more than the specified number of times, it will give up.
- docker run --restart=always [container name] :always always restarts the container when it exits
- docker run --restart=unless-stopped [container name] unless-stopped The container always restarts when it exits.
- However, containers that have been stopped when the Docker daemon is started are not considered.
- If the –restart parameter is not set when the container is started, update it with the following command:
- docker update --restart=always [container name]
Start the nginx service and specify to always restart
Enter the nginx service and kill to start the process
Check the process status to see whether the process is still in startup status
free up space
Container environment variable settings
Start an nginx container, configure environment variables, TEST=1
Enter the container to view environment variables
clear space
Configure environment variables through the configuration file:
View container details
We can view the detailed information of a container, for example, we can view all set environment variables
Start container
View container information
Release resources
Container executes single line command
We can directly use the docker container environment to execute some commands. For example, when there is a certain command in the container but not on the host, we can use the container to complete certain tasks.
Container image import and export
We create a directory and edit a custom homepage
Enter the following content on the homepage
We run an nginx image and then modify the homepage through docker cp
What you see when you visit the homepage is as follows:
We save the image through docker export
We import the image through docker import
Stop our current container and restart the container
Start a new container using the exported image
If you use import to import the file generated by export, although the import will not prompt an error, it will prompt a failure when starting the container, and an error similar to "docker: Error response from daemon: Container command not found or does not exist" will appear. We have to specify the startup command. Because export loses metadata information.
View container logs
Start an nginx
View all logs
View logs in real time
Refresh the page visited several times
View logs in real time
View the latest 3 lines of logs
Stop the container to release resources
Container resource view
We run an nginx
We can use docker top to see which processes are in the container. By adding aux, we can see the occupied memory and CPU information.
You can see real-time resource usage changes through docker stats
Release resources
8. Comprehensive actual combat 1. Mysql containerized installation
Enter the mysql mirror website and find the mysql mirror
You can see that there are so many tags
We choose the most used version 5.7 to pull the image
We know that the default port of msyql is 3306 and has a password. Check the official website's startup case docker run --name some-mysql -e MYSQL_ROOT_PASSWORD=my-secret-pw -d mysql:tag specifies the password information of mysql
We enter the container login and we can see that we can log in to msyql normally.
If we open port 8200 to the outside world and there is no firewall, we can remotely log in to the interface through the GUI tool. Take mysql workbench as an example.
free up space
9. Comprehensive actual combat 2. Redis containerized installation
The reason for the emergence of Redis
In the early days of the development of Web applications, relational databases received widespread attention and application. The reason was that at that time, Web sites basically had low access and concurrency, and there were few interactions. Later, as the number of visits increased, Web sites using relational databases began to experience some bottlenecks in performance, and the source of the bottleneck was generally disk I/O. With the further development of Internet technology, various types of applications emerge in endlessly, which has led to more demand for performance in today's era of cloud computing and big data, which is mainly reflected in the following aspects:
1. Low-latency read and write speed: rapid application response can greatly improve user satisfaction
2. Support massive data and traffic: for large-scale applications such as search It requires the use of petabytes of data and the ability to handle millions of traffic
In order to overcome this problem, NoSQL came into being. It has the advantages of high performance, strong scalability, and high availability, and is favored by a wide range of developers and warehouse managers.
What is Redis
The full name of Redis is Remote Dictionary Server, and its Chinese name is Remote Dictionary Server.
Redis is one of the most popular NoSQL databases now. Redis is an open source, written in ANSI C, containing a variety of data structures, supporting network, memory-based, optional persistence key-value pair storage database. It has
the following characteristics:
Based on memory operation, high performance
Supports distribution, theoretically infinite expansion
key-value storage system
Open source is written in ANSI C language, complies with the BSD protocol, supports the network, can be memory-based and persistent log-type, Key-Value database, and provides APIs in multiple languages
Redis application scenarios
Almost all major manufacturers are using Redis. Redis provides a variety of data types, such as String type, hash type, list type, collection type and sequential collection type. With these types, various applications can be easily implemented, such as caching system ("hot" data: high-frequency reading, low-frequency write), counters, message queue systems, real-time leaderboards, social networks.
Redis life case
Redis is like a Xinhua dictionary, which can quickly find the corresponding word in the dictionary based on a certain character.
Redis container creation
Download redis image
Start the redis container
Enter the container and set a key
If the firewall is enabled, we can connect through the visual tool, the visual tool download address
AnotherRedisDesktopManager release version - Gitee.com
Configure link
View key
Exit the container and free up space
10. Comprehensive practical practice three, C++ container production
what is the source
The source is the source.
This is where the program gets the software package from when you install the software (the installation program is on your machine, but the things that need to be installed are on the software source server).
Source, under Ubuntu, it is equivalent to a software library. What software is needed? Just remember the correct software name and you can install it with the command:
In fact, you can Call it a software warehouse. When you install the software, you retrieve the data from the warehouse and put it on your machine.
sudo apt-get install software name
For example: if you want to install the gcc software, you can enter sudo apt-get install gcc in the terminal, which will help you install the gcc software. If the software is not in the source, this command cannot be completed.
What is mirroring
Mirroring is a form of file storage and a type of redundancy. The data on one disk has an identical copy on another disk, which is a mirror.
Common image file formats include ISO, BIN, IMG, TAO, DAO, CIF, and FCD.
The so-called image file is actually similar to a ZIP compressed package. It makes a specific series of files into a single file in a certain format to facilitate users to download and use, such as a test version of the operating system. , games, etc. (Those who have installed operating systems should be familiar with xxx.iso) Image files not only have the "synthesis" function of ZIP compressed packages, but their most important feature is that they can be recognized by specific software and can be burned directly to a disc.
Mirror source
The mirror source is to make a mirror of the official source. You can download the software here. For example, if the official source of Ubuntu is abroad, downloading the software may be very slow. In this case, you need to switch to a domestic mirror source. We make a C++ container based on ubuntu. When running the output, HelloWorld can use the image source as an agent. For example, when buying a car, I originally had to go to a car factory, but after setting up 4S stores, I can just go to the 4S store instead of going to the car factory.
Dayuan of Science and Technology of China
https://mirrors.ustc.edu.cn/help/
Make a c++ container
Download the Ubuntu image
Start container
Configure domestic image source acceleration
Install gcc vim
Edit code
Compile code
Run in container
Exit container
At this time, you can see that our container has exited. If we want to enter again, we can use docker restart to restore the container.
Clean up containers to free up space
11. Comprehensive practical experience 4. SpringBoot container production
Write a demo
Use Spring Boot to create a simple demo and output hello docker! in the browser.
Create a maven project and select the first release version 2.0.2.RELEASE of Spring Boot 2.x for explanation. Add the spring-boot dependency in pom.xml as follows
Write the main function to build the Spring container
Write a controller
Use maven packaging to generate jar packages
The generated jar package is located in the target directory under the project root path
Test whether the jar package is available
After starting the container, visit localhost:8080/hello to view the running results and confirm that the jar package is available.
Upload to Linux server for backup
Make a container
Download the Ubuntu image
Start container
Configure domestic image source acceleration
Install jdk
Open a new shell window and copy the jar into the container
View files in the container
Start java service
Access the page through a browser, making sure the firewall is turned on
ctrl+c exits the service, exit exits the container
Release resources
12. Comprehensive actual combat 5. Container resource update
We run an nginx
We can use docker top to see which processes are in the container. By adding aux, we can see the occupied memory and CPU information.
You can see the dynamic changes of resources through docker stats
We update the maximum memory of docker through docker update
We check again through docker stats and see that the memory has been limited to 300m.
We execute a command in the container to fill up the cpu
for i in `seq 1 $(cat /proc/cpuinfo |grep "physical id" |wc -l)`
do
dd if=/dev/zero of=/dev/null &
done
#说明:
#cat /proc/cpuinfo |grep “physical id” | wc -l 可以获得 CPU 的个数,
我们将其表示为 N
#seq 1 N 用来生成1到N之间的数字
#for i in seq 1 N; 就是循环执行命令,从1到N
#dd if=/dev/zero of=/dev/null 执行 dd 命令, 输出到/dev/null, 实际上
只占用 CPU, 没有 IO 操作
#由于连续执行N个(N是 CPU 个数)的 dd 命令, 且使用率为 100%, 这时调度器
会调度每个 dd 命令在不同的 CPU 上处理,最终就实现所有CPU占用率 100%
Executing command configuration can only use 10% of the cpu
You can see that the CPU has only reached about 10%.
Stop the container and release resources
13. Frequently Asked Questions
What is the difference between docker create, docker start and docker run?
The docker create command creates a brand new container from a Docker image. However, it won't run it immediately. The docker start command will start any stopped containers. If you created a container using the docker create command, you can use this command to start it.
The docker run command is a combination of create and start because it creates a new container and starts it immediately. In fact, if the docker run command cannot find the above image on your system, it can pull the image from Docker Hub.
What is the difference between docker import and docker load?
To understand the difference between docker load and docker import commands, you must also know docker save and docker export commands:
- docker images save_name: Export an image as a file, and then use the docker load command to import the file as an image. All historical records of the image will be saved. It is larger than the file exported by the docker export command and is easy to understand because all the history of the image will be saved.
- docker export container_id: Export a container as a file, and then use the dockerimport command to import the container into a new image. However, compared to the docker save command, the container file will lose all metadata and history, and only saves the current state of the container, which is quite for virtual machine snapshots. You can use the docker load command to import the image library storage file to the local image library, or you can use the docker import command to import a container snapshot into the local image library.
- The difference between the two is that container snapshots will discard all historical records and metadata information, while image storage files will save complete records and will be larger in size.
What is the difference between docker rm & docker rmi & docker prune?
- docker rm: delete one or more containers
- docker rmi: delete one or more images
- docker prune: used to delete docker objects that are no longer used