An overview,
-
Docker’s official website is www.docker.com/
-
Docker docs: docs.docker.com/get-docker/, Docker docs are super detailed.
-
The Docker repository is located at Hub.docker.com/. Similar to Github, images can be posted to the repository or available to others
1. What is Docker
Docker is an open source application container engine, which is developed based on go language and follows the apache2.0 protocol.
Docker allows developers to package their applications and dependencies into a lightweight, portable container that can then be published to any popular Linux server, and can also be virtualized.
The containers are completely sandboked, there is no interface to each other (iPhone-like apps), and the container overhead is extremely low.
2. Differences between container technology and VM technology
-
A virtual machine is one solution for installation with an environment.
It can run one operating system on top of another, such as Running Linux on top of Windows. The application is oblivious to this because the virtual machine looks exactly like the real system, but to the underlying system, the virtual machine is just a file that can be deleted without affecting the rest of the system. This type of virtual machine runs another system perfectly, keeping the logic between the application, the operating system, and the hardware unchanged.
Disadvantages of VMS: High resource usage, many redundant steps, and slow startup.
-
Because of these shortcomings of the previous virtual machines, Linux has developed another virtualization technique: Linux Containers (abbreviated LXC).
Instead of emulating a complete operating system, the Linux container == isolates processes ==. With a container, you can package all the resources that your software needs to run into an isolated container. Containers, unlike virtual machines, don’t need to bundle a full operating system, just the library resources and Settings the software needs to work. This makes the system efficient and lightweight and ensures that software consistently runs in any environment it is deployed in.
Compare the differences between container technology and virtual machine technology:
-
Traditional virtual machine technology, virtualizing a set of hardware, running a complete operating system on it, and running the required application processes on the system.
-
The application processes in the container run directly in the host kernel. The container does not have its own kernel, and there is no hardware virtualization. Containers are therefore more portable than traditional virtual machines.
-
Each container has its own file system. Processes in each container do not affect each other and computing resources can be separated.
3. Docker’s advantages
Official words:
- Flexibility: Even the most complex applications can be containerized.
- Lightweight: The container utilizes and shares the host kernel.
- Interchangeable: You can deploy updates and upgrades instantly.
- Portable: You can build locally, deploy to the cloud, and run anywhere.
- Extensibility: You can add and automatically distribute container copies.
- Stackable: You can stack services vertically and instantly.
4. Docker architecture
-
Client: Interacts with the Docker server through commands such as Docker build: builds a container; Docker pull: fetch a container; Docker run: Runs a container
-
Docker_host (server) : Docker’s operations are performed here
-
Docker daemon: The main part of the Docker architecture
-
Provide Server functionality to accept Docker Client requests
-
When a container image is needed, the image is downloaded from Registry
-
-
Images: A Docker image is like a template that can be used to create container services. Multiple containers can be created using this image (the final service or project runs in the container).
-
Containers: Docker uses container technology to create an image that runs one or a group of applications independently. (Beginners can think of this container as a simple Linux for a while.)
A mirror can be thought of as a Class in Java, and a container as an object instance in Java. A class can have multiple object instances
-
-
Register (remote warehouse) : A place where images are stored. There are public and private warehouses
Install Docker
This part can refer to the official document: docs.docker.com/get-docker/, according to your own system to install, I use the system is Centos 7
Installed on Centos system Docker, this part of the position in the official documentation (also in the other Linux distributions install method) : docs.docker.com/engine/inst…
1. The server has a network
-
Uninstalling an old version
yum remove docker \ docker-client \ docker-client-latest \ docker-common \ docker-latest \ docker-latest-logrotate \ docker-logrotate \ docker-engine Copy the code
-
Required installation packages
yum install -y yum-utils Copy the code
-
Setting up the repository
# Official code, the repository is foreign, download slow yum-config-manager \ --add-repo \ https://download.docker.com/linux/centos/docker-ce.repo It is recommended to use the image warehouse of Aliyun yum-config-manager \ --add-repo \ http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo Copy the code
-
Install the Docker engine
Docker-ce: ce for community edition and ee for enterprise edition bash # Update the package index before installation (not required)
# install the latest Docker engine, including Docker community edition, Docker community edition client, etc. Yum install docker-ce docker-ce-cli containerd. IOCopy the code
-
Start the Docker
systemctl start docker Copy the code
-
Test for successful Docker installation
# Check Docker version number docker version Copy the code
If the following diagram appears, the installation is successful:
-
Test downloading the Hello-World image
docker run hello-world Copy the code
-
View the downloaded Hello-World image
docker images Copy the code
-
Uninstall the Docker
Uninstall Docker Engine, CLI, etc yum remove docker-ce docker-ce-cli containerd.io # Images, containers, and other files on the host will not be automatically deleted, you need to manually delete # /var/lib/docker Default working path for docker rm -rf /var/lib/docker Copy the code
2. Configure Ali Cloud image acceleration
- Log in to Aliyun (www.aliyun.com/) to find the container image service:
- If not opened, follow the steps of Ali Cloud opened.
- Find the mirror accelerator at the bottom, select your system, and follow the steps step by step
3. The server has no network
For this part, see the official documentation: Installing Docker Engine from binaries
The following installation process was performed on the RHEL7.3 system
-
Install dependency packages:
yum install -y yum-utils device-mapper-persistent-data lvm2 Copy the code
-
To see the architecture of your server:
uname -a Copy the code
Mine is x86 64-bit:
-
And then to download a good docker binary installer package, address: download.docker.com/linux/stati…
According to the architecture found in the second step, select the compression package under the corresponding architecture and choose the version by yourself. What I download here is x86_64/docker-19.03.9.tgz
-
Copy the compressed package to the machine and decompress it:
The tar XZVF docker - 19.03.9. TGZCopy the code
-
Copy the decompressed file to the /usr/bin/directory:
cp docker/* /usr/bin/ Copy the code
-
Start the Docker daemon:
dockerd & Copy the code
-
Test whether docker is installed successfully: Docker version
The installation is successful if:
4. Configure daemon.json
By default, there is no daemon.json configuration file after docker is installed. You need to create it manually. The default path for configuration files is /etc/docker/daemon.json
The official configuration address: docs.docker.com/engine/refe… This blog explains some of the configurations: The docker configuration file docker-daemon.json is detailed
Some of the configurations I used:
{
"registry-mirrors": ["http://harbor.test.com"If the container logs are stored in /var/log/containers, you can search for them using EFK"exec-opts": ["native.cgroupdriver=systemd"], # Centos defaults to two, using systemd"log-driver": "json-file", # Specifies the type of log to store"log-opts": {
"max-size": "100m"Limit log size},"insecure-registries": ["https://hub.zyx.com"] # Configure private repository addressCopy the code
After the modification, perform the following two steps to make the new configuration take effect
# reload configuration file
systemctl daemon-reload
# restart docker
systemctl restart docker
Copy the code
Docker common commands
All official documents: Docker command: docs.docker.com/reference/
1. View information
1. Docker –help
The command | instructions |
---|---|
docker --help |
Viewing All Commands |
Docker -- help command |
View the help information about a command |
2. Docker Info
The command | instructions |
---|---|
docker info |
Display Docker system information, including the number of images and containers |
### 3. Docker version | |
The command | instructions |
— | — |
docker version |
Prints the docker version information |
2. Mirror command
1. Docker images
-
Docker images [OPTIONS] [REPOSITORY[:TAG]]
-
Common options:
Name, shorthand The default describe --all
,-a
List all images (hides middle images by default) --quiet
,-q
Only the ID of the mirror is displayed -
Example:
[root@localhost ~]# docker images REPOSITORY TAG IMAGE ID CREATED SIZE hello-world latest bf756fb1ae65 5 months ago 13.3kB Copy the code
- explain
REPOSITORY
: Mirrored warehouse source (name)TAG
: Mirror label (version)IMAGE ID
: Indicates the ID of the mirrorCREATED
: Time when the image is createdSIZE
: Indicates the size of the mirror
- explain
2. Docker Search (searching for images in repositories)
-
Docker search [OPTIONS] TERM
-
Common options:
Name, shorthand The default describe --filter
,-f
Filters the output based on the conditions provided in the format key=value
right
If there are multiple filters, multiple flags are passed
(e.g.--filter is-automated=true --filter stars=3
) -
Example:
docker search --filter stars=3 busybox NAME DESCRIPTION STARS OFFICIAL AUTOMATED busybox Busybox base image. 325 [OK] Copy the code
3. Docker pull (download image)
-
Command: docker pull [OPTIONS] NAME [: TAG | @ DIGEST] if you don’t write the TAG (version), the default is the latest
-
Example:
Docker pull mysql:latest docker pull mysql Pull the specified version. Make sure that the version exists in the repositoryDocker pull mysql: 5.7Copy the code
4. Docker RMI
-
Docker rmi [OPTIONS] IMAGE [IMAGE… You can delete one or more images by name or ID
-
Common options:
Name, shorthand The default describe --force
,-f
Forcibly delete image -
Example:
# Delete the specified mirror docker rmi -f e73346bdf465 # Delete all images docker rmi -f $(docker images -aq) Copy the code
5. Docker Commit (image generation via container)
-
Docker commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]
-
Common options:
Name, shorthand The default describe -m
Specifies the description for submission -a
Specify updated user information -
Example:
# Tomcat container modified (app added to webapps file), where 7e119B82CFF6 represents a container docker commit -a "xiaoMaNong" -m "add webapps app" 7e119b82cff6 tomcat:v01 # Then check the local mirror, you can see the mirror just submitted docker images REPOSITORY TAG IMAGE ID CREATED SIZE tomcat v01 37af1236adef 15 seconds ago 652 MB Copy the code
Docker Save/Load (image packaging and loading)
-
Docker Save: Save one or more images to a tar archive (streamed to STDOUT by default)
-
Docker save [OPTIONS] IMAGE [IMAGE…
-
Common options:
Name, shorthand The default describe --output
,-o
Write to file, not STDOUT -
-
Docker Load: Loads images from the tar archive or STDIN
-
Docker load [OPTIONS] docker load [OPTIONS]
-
Common options:
Name, shorthand The default describe --input
,-i
Read from a tar archive file instead of STDIN -
-
Example:
Save the image to a local tar fileDocker save -o mysql5.7 mysql:5.7# There is no extranet on the other server, send the saved tar packet to the server, and then load itSudo docker load -i mysql5.7Copy the code
3. Container commands
Note: You need an image to create a container
1. Docker run (new container and start)
-
Docker run [OPTIONS] IMAGE [COMMAND] [ARG…
-
Common options:
Name, shorthand The default describe --name="Name"
Assign a name to the container. The name is unique and can be used to identify the container --detach
,-d
Background operation -it
Run it interactively, entering the container to view the content --rm
The container is automatically deleted upon exit --publish
,-p
To publish a container port to a host, run the following command: -p IP: host port: container port
-p Host port: indicates the container port
(common)-p Indicates the container port
The container port
--publish-all
,-P
The ports of the container are randomly allocated to free ports on the host docker ps -a
To view--volume
.-v
To bind a mount directory, use the following method: -v/Local directory: indicates the container directory
Anonymous mount:-v Specifies the container directory
Named mount:-v Specifies the volume name: the container directory
(See Iv. Container Data Volume for details)--net
bridge Connect the container to a network without specifying that it will be bridged to Docker0 –restart=always Set the container to start automatically, and the container will restart after the docker service restarts -
Example:
Set the container to start automatically
When running the Docker container, you can add the following parameters to ensure that the container restarts automatically every time the Docker service restarts:
docker run --restart=always
Copy the code
If the container is already started, use the following command:
docker update --restart=always <CONTAINER ID>
Copy the code
Background start container pit
When you start a container in the background, then use the docker ps command to find that the container is not running
[root@localhost ~]# docker run --name="centos_test" -d centos
1f38528aade344433c9d9c0b35125e3ea8007380e599c7b4a875944599481d30
[root@localhost ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
Copy the code
- Cause: Docker container uses background running, must have a foreground process, if docker found no application, will automatically stop.
- Solution:
docker run -dit centos /bin/bash
- add
-it
Parameter interactive running - add
-d
Parameter background running - This enables you to start a Centos that has been running in the background
- Note: The method to enter the container is to use
exec
, do not useattach
Command,attach
The command is to use the existing terminal, if you want to exit the container operation, thenbash
When it’s done, the container exits
- add
2. Docker Ps (listing containers)
-
Docker ps [OPTIONS] without any arguments defaults to the running container
-
Common options:
Name, shorthand The default describe --all
,-a
Display all containers --last
,-n=?
– 1 Display n last created containers (including all states) --quiet
,-q
Only digital ids are displayed -
Example:
[root@localhost /]# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 6097bc8e3852 centos "/bin/bash" 10 minutes ago Exited (0) 9 minutes ago sad_lamport ea55e44464ae bf756fb1ae65 "/hello" 3 hours ago Exited (0) 3 hours ago unruffled_chandrasekhar Copy the code
- Explanation:
CONTAINER ID
: the container idIMAGE
Mirror:COMMAND
: Quote commandCREATED
: Time when the container is createdSTATUS
: Container statePORTS
: Indicates the exposed portNAMES
: Container name
- Explanation:
3. Exit /Ctrl + P + Q (exit container)
Docker run-it name After entering the container, run the following command to exit the container: exit: Container stops and exits Ctrl + P + Q: == Container does not stop == exit
4. Docker rm (delete container)
-
Docker rm [OPTIONS] CONTAINER [CONTAINER…] The CONTAINER command uses the id/name of the CONTAINER
-
Common options:
Name, shorthand The default describe --force
,-f
Force a running container to be removed (using SIGKILL) -
Example:
Delete all containers docker rm -f $(docker ps -aq) docker ps -aq | xargs docker rm -f Copy the code
Docker start/stop
Docker Start Container ID /name# Start containerDocker restart Container ID /name# Restart containerDocker stop Container ID /name# Stop the current running container
docker killThe container id/name# Force containers to stop running
Copy the code
6. Docker exec (enter the currently running container (open new terminal))
-
Docker exec [OPTIONS] CONTAINER COMMAND [ARG…
-
Common options:
Name, shorthand The default describe -it
Run in interactive mode -
Example:
docker exec -it centos1 /bin/bash Copy the code
Docker Attach (enter the terminal of the container start command, no new thread will start)
- Command:
docker attach [OPTIONS] CONTAINER
8. Docker cp (copies files/folders between the container and the local file system)
-
Command:
Execute on the local system Copy the files in the container to the local file system docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH Copy the local system files to the container docker cp [OPTIONS] SRC_PATH CONTAINER:DEST_PATH Copy the code
9. Docker Top (view process information in container)
# is similar to the top command in Linux
docker top CONTAINER
Copy the code
10. Docker logs
-
Command: docker logs [OPTIONS] CONTAINER
-
Common options:
Name, shorthand The default describe --follow
,-f
Trace Log Output --tail
all Number of lines to be displayed from the end of the log --timestamps
,-t
Display timestamp -
Example:
# Display all logs
docker logs -ft centos_test
# Display 10 logs
docker logs -ft --tail 10 centos_test
Copy the code
11. Docker Inspect (returns container details)
docker inspect CONTAINER
Copy the code
Examples (with commonly used information marked) :
[root@localhost ~]# docker inspect c2b030acf83a
[
{
"Id": "c2b030acf83a23b33471b28d58e20d96f9eb22fceab5ffb9b0a848841a3045b6".// The id of the container, usually the first 12 bits
"Created": "The 2020-06-07 T15:04:33. 788916436 z".// Container creation time
"Path": "/bin/bash".// Default console
"Args": [].// The parameter passed
"State": { // The state of the container
"Status": "running".// Running indicates running
"Running": true."Paused": false."Restarting": false."OOMKilled": false."Dead": false."Pid": 101264./ / process id
"ExitCode": 0."Error": ""."StartedAt": "The 2020-06-07 T15:04:35. 115091831 z"."FinishedAt": "0001-01-01T00:00:00Z"
},
"Image": "sha256:470671670cac686c7cf0081e0b37da2e9f4f768ddc5f6a26102ccd1c6954c1ee".// Id of the mirror
"ResolvConfPath": "/var/lib/docker/containers/c2b030acf83a23b33471b28d58e20d96f9eb22fceab5ffb9b0a848841a3045b6/resolv.conf"."HostnamePath": "/var/lib/docker/containers/c2b030acf83a23b33471b28d58e20d96f9eb22fceab5ffb9b0a848841a3045b6/hostname"."HostsPath": "/var/lib/docker/containers/c2b030acf83a23b33471b28d58e20d96f9eb22fceab5ffb9b0a848841a3045b6/hosts"."LogPath": "/var/lib/docker/containers/c2b030acf83a23b33471b28d58e20d96f9eb22fceab5ffb9b0a848841a3045b6/c2b030acf83a23b33471b28d58e 20d96f9eb22fceab5ffb9b0a848841a3045b6-json.log"."Name": "/zyx"."RestartCount": 0."Driver": "overlay2"."Platform": "linux"."MountLabel": ""."ProcessLabel": ""."AppArmorProfile": ""."ExecIDs": null."HostConfig": { // Host configuration
"Binds": null."ContainerIDFile": ""."LogConfig": {
"Type": "json-file"."Config": {}},"NetworkMode": "default"."PortBindings": {},
"RestartPolicy": {
"Name": "no"."MaximumRetryCount": 0
},
"AutoRemove": false."VolumeDriver": ""."VolumesFrom": null."CapAdd": null."CapDrop": null."Capabilities": null."Dns": []."DnsOptions": []."DnsSearch": []."ExtraHosts": null."GroupAdd": null."IpcMode": "private"."Cgroup": ""."Links": null."OomScoreAdj": 0."PidMode": ""."Privileged": false."PublishAllPorts": false."ReadonlyRootfs": false."SecurityOpt": null."UTSMode": ""."UsernsMode": ""."ShmSize": 67108864."Runtime": "runc"."ConsoleSize": [
0.0]."Isolation": ""."CpuShares": 0."Memory": 0."NanoCpus": 0."CgroupParent": ""."BlkioWeight": 0."BlkioWeightDevice": []."BlkioDeviceReadBps": null."BlkioDeviceWriteBps": null."BlkioDeviceReadIOps": null."BlkioDeviceWriteIOps": null."CpuPeriod": 0."CpuQuota": 0."CpuRealtimePeriod": 0."CpuRealtimeRuntime": 0."CpusetCpus": ""."CpusetMems": ""."Devices": []."DeviceCgroupRules": null."DeviceRequests": null."KernelMemory": 0."KernelMemoryTCP": 0."MemoryReservation": 0."MemorySwap": 0."MemorySwappiness": null."OomKillDisable": false."PidsLimit": null."Ulimits": null."CpuCount": 0."CpuPercent": 0."IOMaximumIOps": 0."IOMaximumBandwidth": 0."MaskedPaths": [
"/proc/asound"."/proc/acpi"."/proc/kcore"."/proc/keys"."/proc/latency_stats"."/proc/timer_list"."/proc/timer_stats"."/proc/sched_debug"."/proc/scsi"."/sys/firmware"]."ReadonlyPaths": [
"/proc/bus"."/proc/fs"."/proc/irq"."/proc/sys"."/proc/sysrq-trigger"]},"GraphDriver": {
"Data": {
"LowerDir": "/var/lib/docker/overlay2/bbe44f663e7c732f43fa3a35633008e8d7027fed9d41400a1aa970d5bdf45c90-init/diff:/var/lib/docker/ove rlay2/02399b4c6980e3092721d60619f83c651885c0b0eb1241a6417f0bddb44b5463/diff"."MergedDir": "/var/lib/docker/overlay2/bbe44f663e7c732f43fa3a35633008e8d7027fed9d41400a1aa970d5bdf45c90/merged"."UpperDir": "/var/lib/docker/overlay2/bbe44f663e7c732f43fa3a35633008e8d7027fed9d41400a1aa970d5bdf45c90/diff"."WorkDir": "/var/lib/docker/overlay2/bbe44f663e7c732f43fa3a35633008e8d7027fed9d41400a1aa970d5bdf45c90/work"
},
"Name": "overlay2"
},
"Mounts": [].// Mount the data volume
"Config": { // Basic configuration
"Hostname": "c2b030acf83a".// The name of the container
"Domainname": ""."User": ""."AttachStdin": false."AttachStdout": false."AttachStderr": false."Tty": true."OpenStdin": true."StdinOnce": false."Env": [ // Basic environment variables
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"]."Cmd": [
"/bin/bash"]."Image": "centos"."Volumes": null."WorkingDir": ""."Entrypoint": null."OnBuild": null."Labels": {
"org.label-schema.build-date": "20200114"."org.label-schema.license": "GPLv2"."org.label-schema.name": "CentOS Base Image"."org.label-schema.schema-version": "1.0"."org.label-schema.vendor": "CentOS"."org.opencontainers.image.created": "The 2020-01-14 00:00:00-08:00"."org.opencontainers.image.licenses": "The GPL - 2.0 - the only"."org.opencontainers.image.title": "CentOS Base Image"."org.opencontainers.image.vendor": "CentOS"}},"NetworkSettings": { // Some Settings for the network
"Bridge": ""."SandboxID": "70097fb845389da1a20faf75eabb2f84866ba4b38ea8388397a840b9a344aa85"."HairpinMode": false."LinkLocalIPv6Address": ""."LinkLocalIPv6PrefixLen": 0."Ports": {},
"SandboxKey": "/var/run/docker/netns/70097fb84538"."SecondaryIPAddresses": null."SecondaryIPv6Addresses": null."EndpointID": "cb235799991b3c585bf97ea5fcdfc7a069aa13554a5f84ea35e6172c9cad2ed5"."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": { / / bridge
"IPAMConfig": null."Links": null."Aliases": null."NetworkID": "020a4fab0d00a01941b764d9f16740807b2c2673b8138d7e1ece968086b5475b"."EndpointID": "cb235799991b3c585bf97ea5fcdfc7a069aa13554a5f84ea35e6172c9cad2ed5"."Gateway": "172.17.0.1"."IPAddress": "172.17.0.2"."IPPrefixLen": 16."IPv6Gateway": ""."GlobalIPv6Address": ""."GlobalIPv6PrefixLen": 0."MacAddress": "02:42:ac:11:00:02"."DriverOpts": null}}}}]Copy the code
12. Docker Stats (monitor container resource consumption)
- Command:
docker stats [OPTIONS] [CONTAINER...]
- Common options:
Name, shorthand The default describe --all
.-a
By default, only running containers are displayed Display all containers --format string
Formatted output --no-stream
Returns only the current status
Example:
# View all currently running container resources
> docker stats
CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
fdedc094cd26 dockercompose_nginx_1 0.00% 2.148MiB / 3.696GiB 0.06% 4.86MB / 4.78MB 0B / 0B 3
68189b6d290f dockercompose_kibana_1 0.00% 413.7MiB / 3.696GiB 10.93% 125MB / 96.4MB 263MB / 113MB 22
22ed88ee3afa dockercompose_elasticsearch_1 0.39% 524.9MiB / 3.696GiB 13.87% 133MB / 252MB 72.4MB / 2.85MB 62
# Format as JSON
> docker stats --no-stream --format "{\"container\":\"{{ .Container }}\",\"memory\":{\"raw\":\"{{ .MemUsage }}\",\"percent\":\"{{ .MemPerc }}\"},\"cpu\":\"{{ .CPUPerc }}\"}"
{"container":"fdedc094cd26"."memory": {"raw":"2.148 MiB / 3.696 GiB"."percent":"0.06%"},"cpu":"0.00%"}
{"container":"68189b6d290f"."memory": {"raw":"413.8 MiB / 3.696 GiB"."percent":"10.93%"},"cpu":"0.45%"}
{"container":"22ed88ee3afa"."memory": {"raw":"525.1 MiB / 3.696 GiB"."percent":"13.87%"},"cpu":"0.94%"}
Copy the code
Results:
By default, the STATS command refreshes the output every second until you press CTRL + C. Here is the main output:
field | instructions |
---|---|
CONTAINER | Displays the container ID in a short format. |
CPU % | CPU usage. |
MEM USAGE / LIMIT | The memory currently in use and the maximum available memory. |
MEM % | Displays memory usage as a percentage. |
NET I/O | Network I/O data. |
BLOCK I/O | Disk I/O data. |
PIDS | The PID number. |
All placeholders that can be used in a custom format:
Point operator | instructions |
---|---|
.Container | Displays the name or ID of the container based on the name specified by the user |
.Name | Container name |
.ID | The container ID |
.CPUPerc | CPU utilization |
.MemUsage | Memory usage |
.NetIO | Network I/O |
.BlockIO | Disk I/O |
.MemPerc | Memory usage |
.PIDs | PID, |
Iv. Data volume
Data Volumes: Data in a container is directly mapped to a specified file directory on the local host environment, which can be interpreted as a virtual Data volume mounted by a container and mapped to a host directory
In Docker, in order to achieve data persistence (the so-called Docker data persistence means that data does not end with the end of the container), data needs to be mounted from the host to the container.
1. Mount type
(1) Volume (most common)
There are anonymous mounts and named mounts:
-
Anonymous mount: -v Path in the container
docker run -v /ect/nginx nginx Copy the code
-
Named mount: -v Volume name: path in the container
docker run -v nginxConfig:/ect/nginx nginx Copy the code
Can be achieved byDocker inspect Container name
orDocker Volume Inspect Specifies the name of the volume
To view the mount information:
"Mounts": [{"Type": "volume".// Mount type
"Name": "nginxConfig".// The name of the volume
"Source": "/var/lib/docker/volumes/nginxConfig/_data".// The volume is in the local directory. By default, the volume is in the /var/lib/docker/volumes/_data directory.
"Destination": "/ect/nginx".// Inside the container directory
"Driver": "local"."Mode": "z"."RW": true.// Supports read and write
"Propagation": ""}].Copy the code
(2) bind
Usage: -v/Local directory: container directory
docker run -v /home/test:/home centos
Copy the code
Docker is automatically created when the local /home/test directory does not exist
You can view the mount information by using the docker inspect container name:
"Mounts": [{"Type": "bind".// Mount type
"Source": "/home/test".// Local directory
"Destination": "/home".// Inside the container directory
"Mode": ""."RW": true."Propagation": "rprivate"}].Copy the code
However, bind is not portable across host systems. For example, the directory structure of Windows and Linux is different, and the host directory to which bind points cannot be the same. This is why bind cannot appear in a Dockerfile, because the Dockerfile is not portable.
2. Docker Volume
# docker volume volume_name // Create a custom container volume
# docker volume ls # Docker volume ls
# docker volume inspect volume_name
Docker volume rm volume_name docker volume rm volume_name
Copy the code
3. The permissions
-
Ro: readonly: indicates that the path is read-only. It indicates that the path can only be accessed locally and cannot be accessed inside the container
docker run -d -P --name nginx01 -v /ect/nginx:ro nginx Copy the code
-
Rw: readWrite, which indicates both read and write. Default.
docker run -d -P --name nginx01 -v /ect/nginx:rw nginx Copy the code
4. Data volume container (–volumes-from)
Data Volume Containers: A special container to mount Data volumes, and other Containers to mount the parent container to achieve Data sharing, this container is the Data Volume container, the simple summary is that there is a container to manage Data persistence and Data sharing between Containers
If we often need to share data between multiple containers, we need to use the “–volumes-from” command.
Specific examples:
-
Let’s pull a centos container image from the repository
docker pull centos Copy the code
-
Then run the image, create the mycentos container, and mount a data volume to/myData
docker run -it -v /mydata --name mycentos centos Copy the code
-
Run two more containers using –volumes-from to inherit the data volumes in the Mycentos container
docker run -it --volumes-from mycentos --name soncentos1 centos docker run -it --volumes-from mycentos --name soncentos2 centosCopy the code
At this point, both soncentos1 and soncentos2 mount the same data volume to the same /mydata directory. If one of the three containers writes to that directory, the other containers can see it.
The following container (mycentos) is the data volume container. It is possible to create multiple subcontainers (soncentoS1, soncentos2) from a data volume container. Even if you delete mycentos1 from the original data volume container or delete other containers, the data in the data volume container will not be lost as long as it is being used by another container. (Unless no container is using them)
Five, the network
1. docker0
As you can see from the IP addr command, Docker generates a network card docker0Every time a Docker container is started, Docker assigns an IP address to the container. By default, the bridge mode is usedveth-pair
Start a Redis container, you can see that there is an extra NIC on the host, which corresponds to the nic in the container:Host NIC:
A veTH-pair is a pair of virtual device interfaces. They come in pairs, with one end connected to the protocol and the other end connected to each other. Because of this feature, an EVTH-pair acts as a bridge between virtual network devices
Different containers can access each other, and Docker0 can be understood as a router
If the container is deleted, the corresponding network adapter is also deleted
2. docker network
Ls: View the network
Docker has three networks by default:
Create: Creates a network
If the type is not specified, the default network type is Bridge
- Command:
docker network create [OPTIONS] NETWORK
Name, shorthand | The default | describe |
---|---|---|
-d, –driver | bridge | Specifying a network type |
–subnet | Indicates the SUBNET in CIDR format of the network segment | |
–gateway | The gateway |
- Example:
-
Creating a custom network
Docker network create -d bridge --subnet 192.168.0.0/16 --gateway 192.168.0.1 mynetCopy the code
-
Start the container and join the network using –net
docker run -d -P --name redis-net-01 --net mynet redis:alpine docker run -d -P --name redis-net-02 --net mynet redis:alpine Copy the code
Using Docker Network Inspect Mynet, you can see that two containers have joined the network:In the Mynet network, == containers can be accessed by the container name == :
-
Other commands
You can see the details with –help (for example, docker network disconnect –help)
The command | instructions |
---|---|
connect | Add the container to the network |
disconnect | The container is disconnected from the network |
inspect | View network details |
prune | Delete all unused networks |
rm | Remove the network |
3. Network isolation
The networks in Docker are isolated from each other. The advantage of this is that different clusters use different networks to ensure the security and health of the clusters.
Containers in the two networks are separated and cannot access each other. Containers in network A can join network B through Docker Network Connect, so as to realize the access of containers in network A to network B. Principle: Add an IP address of network B to a container, that is, add multiple IP addresses to a container
Six, DockerFile
1. Basics
Docker Study Notes (5) — Dockerfile
-
Every reserved keyword (instruction) must be in capital letters
-
The Dockerfile file is executed from top to bottom
-
# for comments
-
Each directive creates and commits a new mirror layer and commits
-
Docker images are made by superimposing special file systems; The bottom is bootFS and uses the host’s bootFS. An image can be placed on top of another image. The image at the bottom is called the parent image, and the image at the bottom becomes the base image. When starting a container from an image, Docker loads a read/write file system at the top as the container. The following figure
2. Basic commands
The keyword | role | note |
---|---|---|
FROM |
Specifying the base mirror | Specify that dockerfile is built on that image and everything starts there |
MAINTAINER |
The author information | Use this to identify who wrote the dockerfile, usually: name + email |
LABEL | The label | Maintainer: The Label used to Maintainer a Dockerfile can be used in the basic information of the Docker image |
RUN |
Execute the command | Execute a sequence of commands. The default is/bin/sh Format:RUN command orRUN ["command" , "param1","param2"] |
CMD |
Container start command | Provides default commands for starting containers, andENTRYPOINT Use together. formatCMD command param1 param2 orCMD ["command", "param1", "param2"] . You can use&& Concatenate multiple commands in a single CMD |
ENTRYPOINT |
The entrance | The format is usually used when making containers that are executed and closedENTRYPOINT ["command", "param1", "param2"] |
COPY |
Copy the file | build Copy the file toimage In the |
ADD |
Add files | build When adding files toimage Is not limited to the presentbuild Context, can be from a remote service, == if it is a compressed file, it will automatically extract == |
ENV |
The environment variable | build Environment variables can be set when the container is started-e Coverage. formatENV name=value |
ARG | Build parameters | Build parameters Parameters that are used only at build time if ENV is used then the value of ENV with the same name always overrides the arG parameter |
VOLUME |
Define data volumes that can be mounted externally | The specifiedbuild theimage Which directories can be mounted to the file system at startup time. Used when starting the container-v Binding format VOLUME [” directory “] |
EXPOSE |
Exposure to port | Defines the port on which the container will listen when it runs and starts using the container-p To bind exposed ports. Format:EXPOSE 8080 orEXPOSE 8080/udp |
WORKDIR |
Working directory | Specifies the working directory inside the container, which is automatically created if it is not created/ The absolute address is used; If it is not/ So the beginning is in the last oneworkdir Relative to the path of |
USER | Specify execution user | Specifies the user at build or startup when the RUN CMD ENTRYPONT is executed |
HEALTHCHECK | Health check | The command specifying the health monitoring that monitors the current container is basically useless because many times the application has its own health monitoring mechanism |
ONBUILD |
The trigger | When there isONBUILD The keyword of the image is inherited when executedFROM When it’s done, it executesONBUILD But does not affect the current mirror |
STOPSIGNAL | Sends the semaphore to the host | The STOPSIGNAL directive sets the system call signal to be sent to the container to exit. |
SHELL | Specifies the shell to execute the script | RUN CMD ENTRYPOINT Specifies the shell used to execute the command |
3. Docker build
First write the Dockerfile file and then use the docker build command to build the image
-
Docker build [OPTIONS] PATH
-
Common options:
Name, shorthand The default describe -f
Specify the Dockerfile path to use. If the file is in the current directory Dockerfile
This is the name of the file-f
The specified--tag
.-t
Mirror name and tag, usually name:tag
orname
Format; You can set more than one label for a single image in a single build. -
For example, modify the official centos (add vim and Net-Tools) to build your own centos:
-
Write the Dockerfile first: 99% of the images in Docker Hub start FROM scratch (FROM Scratch) base images, and then configure the required software and some configuration to build. Mydockerfile -centos
FROM centos MAINTAINER xiaomanong<zyx1260168395> ENV MYPATH /usr/local WORKDIR $MYPATH RUN yum -y install vim RUN yum -y install net-tools EXPOSE 80 CMD echo $MYPATH CMD echo "---end---" CMD /bin/bash Copy the code
-
Build the image using the docker build command
#Don't forget the last point'. ', indicates the current pathDocker build -f mydockerfile-centos -t mycentos:0.1Copy the code
-
You can then use Docker Images to view your own image
-
4. Docker History
-
Docker history [OPTIONS] IMAGE
-
Common options:
Name, shorthand The default describe -H
true
Prints the image size and date in a readable format -
Example: check mycentos created in 5.3:
# The build process shown is bottom-up
[root@localhost zyx]# docker history mycentos
IMAGE CREATED CREATED BY SIZE COMMENT
f006331eed43 4 minutes ago /bin/sh -c #(nop) CMD ["/bin/sh" "-c" "/bin... 0B
844dae209483 4 minutes ago /bin/sh -c #(nop) CMD ["/bin/sh" "-c" "echo... 0B
9047ac00cd0f 4 minutes ago /bin/sh -c #(nop) CMD ["/bin/sh" "-c" "echo... 0B
9052f658149b 4 minutes ago /bin/sh -c #(nop) EXPOSE 80 0B216accbf3204 4 minutes ago /bin/sh -c yum -y install net-tools 22.8MB f036dff75a56 4 minutes ago /bin/sh -c yum -y install net-tools 22.8MB f036dff75a56 4 minutes ago /bin/sh -c yum -y Install vim 57.2MB 86e8dcdb7221 5 minutes ago /bin/sh -c#(nop) WORKDIR /usr/local 0B
58fa1de6f554 5 minutes ago /bin/sh -c #(nop) ENV MYPATH=/usr/local 0B
613d715c859b 5 minutes ago /bin/sh -c # (nop) MAINTAINER xiaomanong < zyx... 0B
470671670cac 5 months ago /bin/sh -c #(nop) CMD ["/bin/bash"] 0B
<missing> 5 months ago /bin/sh -c # (nop) LABEL org. LABEL - schema. Sc... 0B
<missing> 5 months ago /bin/sh -c # (nop) ADD file: aa54047c80ba30064... 237MB
Copy the code
5. The difference between CMD and ENTRYPOINT
CMD
: specifies the command to be run when the container starts. Only the last command takes effect and can be replacedENTRYPOINT
: Specifies the command to run when the container starts. You can append commands
First, there are two images built from dockerfiles:
-
Mirror cmdtest:
FROM centos CMD ["ls"."-a"] Copy the code
-
Mirror enttest:
FROM centos ENTRYPOINT ["ls"."-a"] Copy the code
Then use the docker run command to create containers for each image:
-
To test the mirror cmdTest:
# 1. Run the CMD command in the dockerfile without a command [root@localhost zyx]# docker run --rm cmdtest.# 2. Adding the command replaces the default CMD command in the dockerfile [root@localhost zyx]# docker run --rm cmdtest ls -al total 56 drwxr-xr-x. 1 root root 4096 Jun 16 14:30 . drwxr-xr-x. 1 root root 4096 Jun 16 14:30 .. # 3. If you are adding arguments to CMD, an error is reported [root@localhost zyx]# docker run --rm cmdtest -l docker: Error response from daemon: OCI runtime create failed: container_linux.go:349: starting container process caused "exec: \"-l\": executable file not found in $PATH": unknown. Copy the code
-
To test the mirror entTest:
The ENTRYPOINT command in the dockerfile is executed without the command, which has the same effect as CMD [root@localhost zyx]# docker run --rm enttest.# 2. The ENTRYPOINT command is an append command, and the actual command is ls -a ls -al, so an error is reported [root@localhost zyx]# docker run --rm enttest ls -al ls: cannot access 'ls': No such file or directory # 3. The actual command to start the container: ls -a -l [root@localhost zyx]# docker run --rm enttest -l total 56 drwxr-xr-x. 1 root root 4096 Jun 16 14:28 . drwxr-xr-x. 1 root root 4096 Jun 16 14:28 .. Copy the code
6. Actual: Use your own Tomcat compression package to make Tomcat image
Here you use your own Tomcat compression package and JDK8 compression package to create Tomcat images
-
First send the two compressed packages to the server, and then write the Dockerfile file in the same directory:
FROM centos MAINTAINER xiaomanong<zyx1260168395> ADD jdk-8u121-linux-x64.tar.gz /usr/local/ ADD apache tomcat - 9.0.0. M26. Tar. Gz/usr /local/ RUN yum -y install vim ENV MYPATH /usr/local WORKDIR $MYPATH ENV JAVA_HOME /usr/local/ jdk1.8.0 _121 ENV CLASSPATH$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar ENV CATALINA_HOME /usr/local. / apache tomcat - 9.0.0 M26 ENV CATALINA_BASH/usr /local. / apache tomcat - 9.0.0 M26 ENV PATH$PATH:$JAVA_HOME/bin:$CATALINA_HOME/lib:$CATALINA_HOME/bin EXPOSE 8080 CMD /usr/local/ apache-tomcat-9.0.0.m26 /bin/startup.sh && tail -f /usr/local. / apache tomcat - 9.0.0 M26 / logs/catalina. OutCopy the code
-
Build an image:
docker build -f Dockerfile -t mytomcat . Copy the code
-
Start a container of the image, using -v to mount the directory:
docker run -d -p 8080:8080 -v /home/test/mytomcat/webapps:/usr/local. / apache tomcat - 9.0.0 M26 / webapps - v/home /test/mytomcat/logs:/usr/local. / apache tomcat - 9.0.0 M26 / logs - name mytomcat mytomcatCopy the code
Publish the image to Docker Hub
(1) Log in to Ducker Hub
Sign up for your ducker Hub account and log in to Docker Hub via the command line
- Command:
docker login [OPTIONS] [SERVER]
- Common options:
Name, shorthand The default describe --password
,-p
password --username
,-u
The user name
(2) Docker tag image
- Command:
docker tag SOURCE_IMAGE[:TAG] TARGET_IMAGE[:TAG]
== Note == :TARGET_IMAGE
Format, as shown below (use your owndocker hub
User name, otherwise error will be reported) :
-
Mark the mytomcat image you just created:
Docker tag mytomcat 1260168395 / mytomcat: 1.0Copy the code
(3) Publish images to Docker Hub:
-
Docker push [OPTIONS] NAME[:TAG] docker push [OPTIONS] NAME[:TAG]
-
Send myTomcat image to Docker Hub:
Docker 1260168395 / push mytomcat: 1.0Copy the code
(4) Logout of the docker logout session
- Command:
docker logout [SERVER]
8. Publish images to Alibaba Cloud container service
-
Log in to Aliyun (www.aliyun.com/) and find the container and image service (if you cannot find it, see 2.2 Configuring Aliyun Image Acceleration).
-
Creating a namespace
-
Creating an image Repository
- I’m gonna go create Image
- Fill in warehouse information
- Select the code source. In this case, the local repository is used:
-
Release the mirror
Click the newly created mirror warehouse, view the detailed information of the mirror warehouse, the warehouse will be how to submit the mirror to the warehouse instructions and commands, you can refer to their own.
! [insert picture description here] (HTTP: / / https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/c8f0cdc98339493ea23c4660b3c65767~tplv-k3u1fbpfcp-zoom-1.im age)Copy the code
Seven, Docker Compose
Docker Compose official document: docs.docker.com/compose/
1. Introduction
- Earlier we used
Docker
The definitionDockerfile
File and then usedocker build
,docker run
And so on. However, the application system of microservice architecture generally contains several microservices, and each microservice will generally deploy multiple instances. If each microservice has to be manually started and stopped, the efficiency will be low and the maintenance amount will be large - use
Docker Compose
To easily and efficiently manage multiple containers, it is a tool for defining and running multiple containersDocker
Application tools
Using Compose is basically a three-step process:
-
Start by defining your own environment with dockerFiles so that you can copy anywhere.
-
Define the services that make up the application in the docker-compose. Yml file so that they can run together in an isolated environment.
-
Run the docker-compose up command to get the entire application up and running.
A docker-compose. Yml looks like this:
version: "3.8"
services:
web:
build: . # Build web image using Dockerfile in current directory
ports: # Expose port
- "5000:5000"
volumes: Volume # mount
- .:/code
- logvolume01:/var/log
links: Connect to the Redis service (container) defined below
- redis
redis:
image: redis # Use the Redis image
volumes:
logvolume01: {} # Define the volume name
Copy the code
2. Install
The official document, there are various system installation method: docs.docker.com/compose/ins…
Linux (Centos7) installation
- download
= = = = = = = = = = = = = = = = = = = = = = = = = = -s)-$(uname -m)” -o /usr/local/bin/docker-compose
https://get.daocloud.io/docker/compose/releases/download/1.27.4/docker-compose- # here is the address DaoCloud curl - L ` uname -s`-`uname -m` > /usr/local/bin/docker-compose ```Copy the code
-
Apply executable permissions to binary files
sudo chmod +x /usr/local/bin/docker-compose Copy the code
-
Run the docker-compose version command to check whether the docker-compose version is successfully installed
3. Get started
This is from a small example: an introduction to the club’s official website docs.docker.com/compose/get…
I’ve changed the example on the website a little bit to make it more concise
-
Create a directory for the project:
mkdir composetest cd composetest Copy the code
-
Create a file called app.py in the project directory you just created and paste the following code:
import time import redis from flask import Flask app = Flask(__name__) When accessing Redis, host is not the IP address, but the domain name (service name) redis cache = redis.Redis(host='redis', port=6379) def get_hit_count() : retries = 5 while True: try: Redis incremented by 1 per visit return cache.incr('hits') except redis.exceptions.ConnectionError as exc: if retries == 0: raise exc retries -= 1 time.sleep(0.5) @app.route('/') def hello() : count = get_hit_count() return 'Hello World! I have been seen {} times.\n'.format(count) if __name__ == "__main__": app.run(host="0.0.0.0", debug=True) Copy the code
-
Create another file called requirements. TXT in the project directory and paste the following code:
flask redis Copy the code
-
In the project directory, create a file named Dockerfile and paste the following:
FROM python:3.7-alpine ADD . /code WORKDIR /code RUN pip install -r requirements.txt CMD ["python"."app.py"] Copy the code
-
Create a file called docker-compose. Yml in your project directory and paste the following:
version: "3.8" services: web: build: . ports: - "5000:5000" redis: image: "redis:alpine" Copy the code
-
In the project directory, launch the application by running docker-compose up.
-
Type it in your browser
http://localhost:5000
To see the application in action. -
As you can see, two services are started:
Default container name:
File name _ Service name _ Number of copies
-
Check the network
Docker Compose automatically generates a network where all the services that are started are in the network, so services can be accessed via a domain name (the service name)
- Other commands
-
The background
docker-compose up -d Copy the code
-
View the currently running services
docker-compose ps Copy the code
-
If it is running in the background, use the following command to stop it
Note: Execute in the same directory as at startup
docker-compose stop Copy the code
-
4. Yaml configuration file
The official document: docs.docker.com/compose/com… Novice tutorial: www.runoob.com/docker/dock…
Version: version
Specifies which version of the YML compliant compose is specified. Backwards compatible, the latest is 3.8
Services: collections of multiple containers
Build: Specify Dockerfile
Specifies the context path to Dockerfile or an object that can specify parameters to Dockerfile:
version: "3.7"
services:
webapp:
build: ./dir
webapp2:
build:
context: ./dir # context path
dockerfile: Dockerfile-alternate # Specifies the name of the Dockerfile to build the image
args: Add build parameters, which are environment variables that can only be accessed during the build process
buildno: 1
labels: # Set the tag to build the mirror
- "com.example.description=Accounting webapp"
- "com.example.department=Finance"
- "com.example.label-with-empty-value"
target: prod # Multilayer build. You can specify which layer to build
Copy the code
Command: overrides the default command executed after the container is started
command: ["bundle"."exec"."thin"."-p"."3000"]
Copy the code
Container_name: specifies the name of the generated container
Custom generated container name, rather than the default generated name
container_name: my-web-container
Copy the code
Depends_on: Sets the dependency
version: "3.8"
services:
web:
build: .
depends_on:
- db
- redis
redis:
image: redis
db:
image: postgres
Copy the code
Note: Web services do not wait for redis DB to be fully started before starting.
Docker-compose up: Starts a service in dependency order. In the example, db and Redis are started before the Web is started. Docker-compose up SERVICE: automatically includes dependencies for a SERVICE. In the example, docker-compose up Web will also create and start db and Redis. Docker-compose stop: stop service in dependency order. In the example, the Web stops before DB and Redis.
DNS: Configure the DNS server
Configure the DNS server, which can be a value or a list
dns: 8.88.8.
dns:
- 8.88.8.
- 9.99.9.
Copy the code
Dns_search: configures the DNS search domain
Configure the DNS search domain, which can be a value or a list
dns_search: example.com
dns_search:
- dc1.example.com
- dc2.example.com
Copy the code
Env_file: obtains environment variables from the file
Environment variables are obtained from a file by specifying a file path or a list of paths that have a lower priority than the environment variable specified by environment. Can be a single value or multiple values of a list.
env_file: .env
env_file:
- ./common.env
Copy the code
Environment: Environment variable configuration
To add an environment variable configuration, you can use an array or dictionary, any Boolean value, which needs to be enclosed in quotes to ensure that the YML parser does not convert it to True or False.
environment:
RACK_ENV: development
SHOW: 'ture'
Copy the code
Entrypoint: command executed after the container is started
This overwrites the container’s default entryPoint or dockerFile CMD command.
entrypoint: /code/entrypoint.sh
Copy the code
It can also be in the following format:
entrypoint:
- php
- -d
- zend_extension=/usr/local/lib/php/extensions/no-debug-non-zts-20100525/xdebug.so
- -d
- memory_limit=-1
- vendor/bin/phpunit
Copy the code
Expose: Exposes the port
To expose a port, you can only expose the port to the connected service, but not to the host. You can only specify an internal port as a parameter
expose:
- "3000"
- "8000"
Copy the code
Extra_hosts: Adds a host name mapping
Add host name mapping, similar to docker client –add-host.
extra_hosts:
- "Somehost: 162.242.195.82"
- "Otherhost: 50.31.209.229"
Copy the code
This will create a mapping between the IP address and host name in the internal container of the service /etc/hosts:
162.242195.82. somehost
50.31209.229. otherhost
Copy the code
Image: Specifies the image used by the service
image: java
image: a4bc65fd Id # image
Copy the code
Links: Links to a container in another service
Link to a container in another service. Specify the SERVICE name and the link ALIAS (“SERVICE:ALIAS”), or just the SERVICE name.
The container for the linked service can be accessed using the same host name as the alias, or the service name if the alias is not specified.
version: "3"
services:
web:
links:
- "db"
- "db:database"
db:
image: postgres
Copy the code
Logging: indicates the logging configuration of the service
Driver: specifies the logging driver of the service container. The default value is json-file. There are three options
driver: "json-file"
driver: "syslog"
driver: "none"
Copy the code
-
Only under the json-file driver, you can use the following parameters to limit the number and size of logs.
logging: driver: json-file options: max-size: "200k" Single file size: 200K max-file: "10" # Up to 10 files Copy the code
When the number of files reaches the upper limit, the system automatically deletes old files.
-
In the syslog driver, you can use syslog-address to specify the address for receiving logs.
logging: driver: syslog options: syslog-address: "TCP: / / 192.168.0.42:123" Copy the code
Network_mode: set the network mode
Use the same value as the Docker client–network parameter, and the special form service:[service name]
network_mode: "bridge"
network_mode: "host"
network_mode: "none"
network_mode: "service:[service name]"
network_mode: "container:[container name/id]"
Copy the code
Networks: configures the network that the container connects to
Configure the network to which the container connects, referencing the entry under top-level networks.
services:
some-service:
networks:
some-network:
aliases:
- alias1
other-network:
aliases: Other containers on the same network can use the service name or this alias to connect to the services of the corresponding container.
- alias2
networks:
some-network:
# Use a custom driver
driver: custom-driver-1
other-network:
# Use a custom driver which takes special options
driver: custom-driver-2
Copy the code
Ports: Indicates the port definition that is exposed and corresponds to expose
ports: Expose port information - "Host port: container expose port"
- "5000:5000"
- "8763:8763"
Copy the code
Volumes: directory for mounting volumes
Mount data volumes or files on the host to the container. How to use: host path or volume name: container path (define volume name in top level volumes)
version: "3.8"
services:
db:
image: postgres:latest
volumes:
- "/localhost/postgres.sock:/var/run/postgres/postgres.sock"
- "dbdata:/var/lib/postgresql/data"
volumes:
dbdata:
Copy the code
Restart: always: sets the container to automatically start
version: "3.8"Services: mysql: image: mysql:5.7 volumes: -"/mydata/mysql/log:/var/log/mysql"
- "/mydata/mysql/data:/var/lib/mysql"
- "/mydata/mysql/conf:/etc/mysql"
ports:
- "3306:3306"
environment:
MYSQL_ROOT_PASSWORD: "root"
restart: always
redis:
image: redis
volumes:
- "/mydata/redis/data:/data"
- "/mydata/redis/conf/redis.conf:/etc/redis/redis.conf"
ports:
- "6379:6379"
entrypoint: ["redis-server"."/etc/redis/redis.conf"]
restart: always
Copy the code
5. Common commands
The official document: docs.docker.com/compose/ref…
The command | instructions | For example, |
---|---|---|
ps |
List all running containers | docker-compose ps |
logs | View service log output | docker-compose logs |
port | Print the public ports that are bound. The following command displays the public ports that are bound to eureka service port 8761 | docker-compose port eureka 8761 |
build | Build or rebuild the service | docker-compose build |
start | Starts an existing container for the specified service | docker-compose start eureka |
stop |
Stop the container of the running service | docker-compose stop eureka |
rm | Deletes the container for the specified service | docker-compose rm eureka |
up |
Build and start the container | docker-compose up Build the image before opening the container: docker-compose up –build Background run: docker-compose up -d |
kill | Stop the container of the specified service by sending the SIGKILL signal | docker-compose kill eureka |
pull | Downloading the Service Image | |
scale | Set the number of containers for the specified service to run. The value is specified in the service=num format | docker-compose scale user=3 movie=3 |
run | Execute a command on a service | docker-compose run web bash |
Viii. Visualization
1. portainer
Documents: www.portainer.io/documentati…
Just follow the document. Here is a note of what I did
- The installation
docker volume create portainer_data docker run -d -p 9000:9000 --name portainer --restart always -v /var/run/docker.sock:/var/run/docker.sock -v portainer_data:/data portainer/portainer Copy the code
- Browser access
9000
Port is ok.
Nine, the sample
1. The deployment of Mysql
-
The server can connect to the Internet and pull images directly from the repository
Docker pull mysql: 5.7Copy the code
-
If the server can not connect to the Internet, download the mysql image from a computer with network, and then save the image to the local, and then send the image to the server without network, and finally load the image through Docker:
-
Save the image to a local file
Docker save -o mysql5.7 mysql:5.7Copy the code
-
Copy the image to a computer without network, and then load the image through Docker.
Sudo docker load -i mysql5.7Copy the code
-
-
Start mysql container
docker run -dit -p 3306:3306 -v /home/mysql/conf:/etc/mysql/conf.d -v /home/mysql/data:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=123 --name="mysql01"Mysql: 5.7Copy the code
2. Deployed Nginx
-
Search image, you can use
docker search
I prefer to go to Docker Hub (hub.docker.com/Docker Hub Docker Hub Docker Hub Docker Hub Docker Hub Docker Hub Docker Hub Docker HubWhen you click on it, you will find the version information, the use (configuration) of the image, and so on. -
Pull the mirror. If no network is available, the process is the same as that of Mysql mirror
docker pull nginx Copy the code
-
Start the temporary container and get the nginx configuration file
# Start a random Nginx container
docker run --name nginx-tmp -d -p 80:80 nginx
# copy the nginx directory from the nginx container to the local /mydata/nginx/conf directory
docker container cp nginx:/etc/nginx /mydata/nginx/conf
Move all files from the nginx directory to the conf directory
mv /mydata/nginx/conf/nginx/* /mydata/nginx/conf/
# Remove the redundant /mydata/nginx/conf/nginx directory
rm -rf /mydata/nginx/conf/nginx
Stop running the nginx container
docker stop nginx-tmp
Delete the nginx container
docker rm nginx-tmp
Copy the code
- Start the Nginx container
docker run -p 80:80 --name nginx \
-v /mydata/nginx/html:/usr/share/nginx/html \
-v /mydata/nginx/logs:/var/log/nginx \
-v /mydata/nginx/conf/:/etc/nginx \
-d nginx:1.10
--restart=always
Copy the code
- Test nginx
echo '< h1 > < a target = "_blank" href = "https://github.com/zsy0216/guli-mall" > nginx configuration success < / a > < / h1 >' \
>/mydata/nginx/html/index.html
Copy the code
If the browser accesses IP :80 and the index. HTML page is displayed, nginx is successfully started
3. Deploy Tomcat
-
Similarly, first search for Tomcat on Docker Hub, and then find the corresponding version for pull.
Docker pull tomcat: 9.0Copy the code
-
Start a Tomcat container
docker run -d -p 8080:8080 --name tomcat01 tomcat Copy the code
-
Some configuration of the Tomcat container
Tomcat
In the container, Tomcat is located at/usr/local/tomcat
, among them,webapps
The contents of the folder are empty. The original contents are all in the folderwebapps.dist
Folder.- The configuration file is located
/usr/local/tomcat/conf/
-
After the contents are in the WebApps folder, access the web browser to check whether Tomcat is configured successfully
4. Use case for Docker-compose
== Notice == : Nginx must first start a temporary container, obtain the configuration file, and put it into the directory to be mounted. Then start the official Nginx
version: "3.8"Services: mysql: image: mysql:5.7 volumes: -"/mydata/mysql/log:/var/log/mysql"
- "/mydata/mysql/data:/var/lib/mysql"
- "/mydata/mysql/conf:/etc/mysql"
ports:
- "3306:3306"
environment:
MYSQL_ROOT_PASSWORD: "root"
restart: always
redis:
image: redis
volumes:
- "/mydata/redis/data:/data"
- "/mydata/redis/conf/redis.conf:/etc/redis/redis.conf"
ports:
- "6379:6379"
entrypoint: ["redis-server"."/etc/redis/redis.conf"]
restart: always
nacos:
image: nacos/nacos-server:2.0.1
ports:
- "8848:8848"
environment:
MODE: "standalone"Restart: always nginx: image: nginx:1.18.0 ports: -"80:80"
volumes:
- "/mydata/nginx/conf:/etc/nginx"
- "/mydata/nginx/html:/usr/share/nginx/html"
- "/mydata/nginx/logs:/var/log/nginx"Restart: Always ElasticSearch: Image: ElasticSearch :7.4.2 Ports: -"9200:9200"
- "9300:9300"
environment:
discovery.type: "single-node"
ES_JAVA_OPTS: "-Xms64m -Xmx512m"
volumes:
- "/mydata/elasticsearch/config/elasticsearch.yml:/usr/share/elasticsearch/config/elasticsearch.yml"
- "/mydata/elasticsearch/data:/usr/share/elasticsearch/data"
- "/mydata/elasticsearch/plugins:/usr/share/elasticsearch/plugins"Restart: always Kibana: image: Kibana :7.4.2 ports: -"5601:5601"
environment:
ELASTICSEARCH_HOSTS: "http://10.211.55.12:9200"
restart: always
Copy the code