laitimes

Does a network engineer need to be familiar with Docker? I don't think you need to be proficient, but you need to know the basics

author:wljslmz

Hello, this is the Network Technology Alliance Station, and I'm Ruigo.

Docker is a word that everyone is familiar with, but as a network engineer, you may not usually come into contact with it, if the operation and maintenance personnel who are reading the article are more than 70% of the operation and maintenance personnel will deal with Docker. Even if you can't use it, as a very hot and popular technology, I hope you can insist on reading 50% of the articles and edify the technology.

Launched in 2013 by Solomon Hykes, Docker started as an open-source project to simplify the process of developers deploying applications in development, test, and production environments. Docker provides a lightweight virtualization solution through container technology that allows applications to run consistently in any environment. With the popularity of Docker, the way of working in DevOps and cloud computing has changed profoundly, and Docker has become an important tool for modern software development and deployment.

In modern software development, rapid iteration and continuous delivery have become critical. The advent of Docker makes it easy for developers to create, share, and run applications, improving development efficiency and reducing the problems caused by inconsistencies in the environment. In addition, the isolation feature of Docker enhances the security and stability of the system, making it widely used in microservice architecture and cloud-native applications.

Does a network engineer need to be familiar with Docker? I don't think you need to be proficient, but you need to know the basics
If you already have a Docker foundation, you can slide directly to the final summary to check and fill in the gaps!

Container technology

The difference between a container and a virtual machine

  • Virtual Machines (VMs)
  • VMs contain a complete operating system and run multiple operating system instances on top of the virtualization layer.
  • VMs require more system resources (CPU, memory, storage) to manage these OS instances.
  • 容器 (Container)
  • Containers share the kernel of the host operating system, with separate file systems, processes, and network spaces.
  • Containers are more lightweight, fast to start, and take up fewer resources.
Does a network engineer need to be familiar with Docker? I don't think you need to be proficient, but you need to know the basics
characteristic virtual machine container
Start-up time A few minutes A few seconds
Resource overhead High (including operating system kernel) Low (Shared Host OS Kernel)
performance medium High (closer to host performance)
Isolation level Strong (fully isolated) Weak (shared kernel)
Applicable scenarios Multiple operating systems and higher security isolation requirements Rapid deployment, microservices, dev testing, and more

Advantages of containerization

  • Fast start-up: Containers can be launched in seconds, improving development and deployment efficiency.
  • Lightweight: Containers share the kernel of the host operating system, which consumes fewer system resources.
  • Consistency: Ensure that applications behave consistently across development, test, and production environments, reducing "environmental issues."
  • Convenience: Containerized applications can be packaged into independent units for easy distribution, replication, and management.
  • Portability: Containerized applications can run on any platform that supports Docker without code modifications.

The basic concept of Docker

Does a network engineer need to be familiar with Docker? I don't think you need to be proficient, but you need to know the basics

镜像 (Image)

A Docker image is a lightweight, self-contained, executable package that contains everything you need to run an application, including code, runtime, libraries, environment variables, and configuration files. The image is read-only, and when the container starts, Docker adds a writable layer on top of the image.

容器 (Container)

A container is a running instance of an image that includes everything in the image and a writable layer. Containers are self-contained, portable units that can run on any platform that supports Docker.

仓库 (Repository)

A Docker repository is where images are stored and distributed. Docker Hub is an official public repository, and users can also build private repositories to store their own images. A repository can contain multiple images, each of which can have a different tag.

Docker引擎 (Docker Engine)

Docker Engine is a lightweight runtime and toolset for creating and managing containers. It includes the following components:

  • Docker守护进程 (Docker Daemon):负责管理容器的生命周期。
  • Docker CLI (Command Line Interface): A command-line tool for interacting with the Docker daemon.
  • Docker Registries (镜像仓库):存储和分发Docker镜像。

Docker architecture

Docker client and server

Docker uses a client-server architecture, and the client communicates with the server's Docker daemon through the Docker CLI. The Docker CLI sends commands to the Docker daemon, which is responsible for executing those commands (such as building, running, and distributing containers).

Docker components

  • Docker Daemon: A background process that manages Docker objects such as images, containers, networks, and volumes.
  • Docker CLI: A command-line tool through which users communicate with the Docker daemon.
  • Docker Registries:存储和分发Docker镜像的地方,包含公共的Docker Hub和私有的Docker Registry。

Install Docker

Does a network engineer need to be familiar with Docker? I don't think you need to be proficient, but you need to know the basics
  • Windows
  • 下载并安装Docker Desktop for Windows。
  • Start Docker Desktop and do the basic configuration.
  • Verify the installation: Run docker --version in the command line.
  • macOS
  • 下载并安装Docker Desktop for Mac。
  • Start Docker Desktop and do the basic configuration.
  • Verify the installation: Run docker --version in the terminal.
  • Linux
  • Take Ubuntu as an example:
  • 更新APT包索引:sudo apt-get update
  • 安装必要的包:sudo apt-get install apt-transport-https ca-certificates curl gnupg-agent software-properties-common
  • 添加Docker的官方GPG密钥:curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
  • 设置Docker的稳定版仓库:sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
  • 安装Docker Engine:sudo apt-get update && sudo apt-get install docker-ce docker-ce-cli containerd.io
  • 验证安装:sudo docker --version

Docker image

Docker images are the foundation upon which containers are built, and they contain all the dependencies and configurations required for the application to run. Images are immutable, and a new container instance is generated each time the image is run.

Common Docker image sources include:

  • Docker Hub: The most widely used public image repository, containing a large number of official and community-maintained images.
  • Private image repository: You can build your own Docker registry to store and manage private images.

Basic operations on Docker images

拉取镜像 (docker pull)

The docker pull command is used to pull images from image repositories. The syntax is as follows:

docker pull <镜像名>:<标签>
           

For example, pull the official nginx image:

docker pull nginx:latest
           
Does a network engineer need to be familiar with Docker? I don't think you need to be proficient, but you need to know the basics

查看镜像 (docker images)

The docker images command is used to list all Docker images stored locally. The syntax is as follows:

docker images
           

Sample output:

Does a network engineer need to be familiar with Docker? I don't think you need to be proficient, but you need to know the basics

删除镜像 (Docker RMI)

The docker rmi command is used to delete a local Docker image. The syntax is as follows:

docker rmi <镜像ID或镜像名>:<标签>
           

For example, to delete an nginx image:

docker rmi nginx:latest
           

Build a Docker image

A Dockerfile is a text file that contains a series of instructions needed to build a Docker image. Each directive creates a layer of mirrors during the build process. Commonly used Dockerfile directives include:

  • FROM: specifies the base image
  • RUN: Executes the command in the image
  • COPY: Copies files from the host to the image
  • CMD: Specifies the command to be executed when the container starts

Dockerfile Directive

  • FROM
FROM ubuntu:20.04
           

Specify the base image as Ubuntu 20.04.

  • RUN
RUN apt-get update && apt-get install -y nginx
           

Run the command in the image to install nginx.

  • COPY
COPY . /app
           

Copy all files in the current directory to the /app directory in the image.

  • CMD
CMD ["nginx", "-g", "daemon off;"]
           

Specifies the command to be executed when the container starts.

构建镜像 (docker build)

The docker build command is used to build an image based on a Dockerfile. The syntax is as follows:

docker build -t <镜像名>:<标签> <Dockerfile路径>
           

For example, build an image named mynginx:

docker build -t mynginx:latest .
           

Optimized Docker images

Multi-stage builds

Multi-stage builds can use multiple FROM directives in a single Dockerfile, reducing the size of the final image. For example:

# 第一阶段:构建应用程序
FROM golang:1.16 as builder
WORKDIR /app
COPY . .
RUN go build -o myapp

# 第二阶段:创建最终镜像
FROM alpine:latest
WORKDIR /app
COPY --from=builder /app/myapp .
CMD ["./myapp"]
           

Mirror slimming tips

  • Use a lightweight base image, such as Alpine Linux.
  • Reduce the number of image layers: Merge multiple RUN commands.
  • Clean up unnecessary files: Delete temporary files in the Dockerfile.

Manage images

Tags are used to identify different versions of an image. Tags allow users to easily manage and pull images of specific versions. For example:

docker tag nginx:latest mynginx:v1.0
           
Does a network engineer need to be familiar with Docker? I don't think you need to be proficient, but you need to know the basics

By judiciously using tags and version control systems such as Git, you can effectively manage different versions of an image and ensure consistency across environments.

Docker containers

A Docker container is an independent runtime environment that runs on the Docker engine. Each container is started from an image, with a writable layer added to the image. Containers provide an isolated environment for your application, encapsulating all the dependencies and configurations it needs to run.

An image is a static combination of file system and application configuration, while a container is a running instance of an image. When we start a container, Docker creates a writable layer on top of the image, making the container operational. Images can be used multiple times to create multiple containers.

Basic operations on Docker containers

Create and start a container (docker run)

The docker run command is used to create and start a container. The syntax is as follows:

docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
           

For example, run an nginx container:

docker run -d -p 80:80 nginx
           

This command downloads the nginx image (if it is not available locally) and then runs an nginx container in the background and maps port 80 of the host to port 80 of the container.

停止与重启容器 (docker stop, docker start)

  • Stop vessel
docker stop <容器ID或容器名>
           

For example, stop a container named mynginx:

docker stop mynginx
           
  • Restart the container
docker start <容器ID或容器名>
           

For example, restart the mynginx container:

docker start mynginx
           

进入容器 (docker exec, docker attach)

  • Use docker exec to get into the container

The docker exec command is used to execute the command inside the running container. The syntax is as follows:

docker exec -it <容器ID或容器名> <命令>
           

For example, to enter the bash environment of a running container:

docker exec -it mynginx /bin/bash
           
  • Use docker attach to connect to the container

The docker attach command is used to connect to a running container. The syntax is as follows:

docker attach <容器ID或容器名>
           

For example, connecting to a mynginx container:

docker attach mynginx
           

Lifecycle management of containers

State management of containers

  • View containers in action
docker ps
           
Does a network engineer need to be familiar with Docker? I don't think you need to be proficient, but you need to know the basics

This command lists all running containers.

  • View all containers (including stopped)
docker ps -a
           
Does a network engineer need to be familiar with Docker? I don't think you need to be proficient, but you need to know the basics
  • Delete the container
docker rm <容器ID或容器名>
           

For example, delete the mynginx container:

docker rm mynginx
           

持久化存储 (Volumes)

The data in a Docker container is temporary by default, and when the container is deleted, the data is deleted with it. To persist data, we can use Volumes.

  • Create a volume
docker volume create <卷名>
           

For example, create a volume named myvolume:

docker volume create myvolume
           
  • Use volumes

To mount a volume while running a container:

docker run -d -p 80:80 -v myvolume:/data nginx
           

This command mounts myvolume to the /data directory in the container.

  • View the volume
docker volume ls
           
Does a network engineer need to be familiar with Docker? I don't think you need to be proficient, but you need to know the basics
  • Delete the volume
docker volume rm <卷名>
           

Container networking

Docker's network mode

Docker provides several networking modes for configuring communication between containers.

  • 桥接网络 (Bridge Network)

Default network mode. Each container is connected to a bridged network and can communicate via the container IP.

docker run --network bridge <镜像>
           
  • 主机网络 (Host Network)

Containers share the network stack with the host.

docker run --network host <镜像>
           
  • 无网络 (None Network)

The container is not connected to any network.

docker run --network none <镜像>
           

Customize your network

  • Create a custom bridge network
docker network create <网络名>
           

For example, create a custom bridge network called mynetwork:

docker network create mynetwork
           
  • Connect the container to a custom network
docker run --network mynetwork <镜像>
           

Container-to-container communication

With a custom network, you can communicate directly using the container name. For example, if you run two containers in mynetwork, one container can communicate by the name of the other container:

docker run -d --network mynetwork --name container1 nginx
docker run -d --network mynetwork --name container2 nginx
           

In this case, container2 can communicate with container1 by ping container1.

Container logs and debugging

容器日志查看 (docker logs)

The docker logs command is used to view the logs of a container. The syntax is as follows:

docker logs <容器ID或容器名>
           

For example, to view the logs of the mynginx container:

docker logs mynginx
           

Container debugging tips

  • View processes within the container
docker top <容器ID或容器名>
           
  • Check the resource usage of the container
docker stats <容器ID或容器名>
           
  • Export the container's metadata
docker inspect <容器ID或容器名>
           

Docker仓库与Docker Hub

Docker repositories are used to store and distribute Docker images, making it easy for development teams to share applications. Docker repositories are divided into public repositories and private repositories. Public repositories, such as Docker Hub, provide a large number of open-source image resources. Private warehouses are used to store proprietary images within the enterprise to ensure security and compliance.

Docker Hub is the most widely used Docker public repository, providing a large number of official and community images. Users can pull and push images from Docker Hub, and use Docker Hub's CI/CD integration features.

Use Docker Hub

Create a Docker Hub account

  1. 访问 Docker Hub https://hub.docker.com。
Does a network engineer need to be familiar with Docker? I don't think you need to be proficient, but you need to know the basics
  1. Click the "Sign Up" button to register.
  2. Fill in the relevant information and complete the account registration.

Log in to Docker Hub

Use the docker login command on the command line to log in to Docker Hub:

docker login
           
Does a network engineer need to be familiar with Docker? I don't think you need to be proficient, but you need to know the basics

Enter your username and password for Docker Hub to complete the login.

拉取镜像 (docker pull)

Pulling an image from Docker Hub is very simple, using the docker pull command:

docker pull <镜像名>:<标签>
           

For example, pull the official Python image:

docker pull python:3.9
           
Does a network engineer need to be familiar with Docker? I don't think you need to be proficient, but you need to know the basics

推送镜像 (docker push)

To push an image to Docker Hub, you first need to label the image and then push:

  1. Label the image:
docker tag <本地镜像ID或名称>:<标签> <Docker Hub用户名>/<镜像名>:<标签>
           

For example, mark the local image myapp as myapp of Docker Hub:

docker tag myapp:latest myusername/myapp:latest
           
  1. Push image:
docker push <Docker Hub用户名>/<镜像名>:<标签>
           

For example, to push a myapp image:

docker push myusername/myapp:latest
           

Manage the image gallery

On the Docker Hub website, you can manage your own image repository, including creating new repositories, setting the visibility of repositories (public or private), viewing image details and the number of downloads, etc.

Private Docker repositories

Set up a private repository

Docker officially provides an open-source private repository implementation - Docker Registry. You can use the official registry image to quickly set up a private repository.

  1. Pull the registry image:
docker pull registry:2
           
  1. Run the Registry container:
docker run -d -p 5000:5000 --name myregistry registry:2
           

At this point, the private repository will run on port 5000 of the localhost.

Push and pull images from private repositories

  1. Label the image:
docker tag <本地镜像ID或名称>:<标签> localhost:5000/<镜像名>:<标签>
           

For example, if you label a local image myapp as a myapp in a private repository:

docker tag myapp:latest localhost:5000/myapp:latest
           
  1. Push image:
docker push localhost:5000/myapp:latest
           
  1. Pull the image:
docker pull localhost:5000/myapp:latest
           

Security configuration

To improve the security of private repositories, SSL/TLS and basic authentication can be enabled.

  • Enable SSL/TLS

You need to generate a self-signed certificate or obtain a certificate from a CA and configure the Registry container to use these certificates.

To generate a self-signed certificate:

mkdir -p certs
openssl req -newkey rsa:4096 -nodes -sha256 -keyout certs/domain.key -x509 -days 365 -out certs/domain.crt
           

Mount the certificate when starting the Registry container:

docker run -d -p 5000:5000 --name myregistry \
  -v $(pwd)/certs:/certs \
  -e REGISTRY_HTTP_TLS_CERTIFICATE=/certs/domain.crt \
  -e REGISTRY_HTTP_TLS_KEY=/certs/domain.key \
  registry:2
           
  • Enable Basic Authentication

You need to create an htpasswd file containing the username and password, and configure the Registry container to use this file.

Install the htpasswd tool:

sudo apt-get install apache2-utils
           
Does a network engineer need to be familiar with Docker? I don't think you need to be proficient, but you need to know the basics

Create an htpasswd file:

mkdir -p auth
htpasswd -Bc auth/htpasswd myusername
           

Mount the htpasswd file when starting the Registry container:

docker run -d -p 5000:5000 --name myregistry \
  -v $(pwd)/auth:/auth \
  -e "REGISTRY_AUTH=htpasswd" \
  -e "REGISTRY_AUTH_HTPASSWD_REALM=Registry Realm" \
  -e "REGISTRY_AUTH_HTPASSWD_PATH=/auth/htpasswd" \
  registry:2
           

Advanced features of Docker repositories

Automatically built

Docker Hub provides an auto-build feature that can be integrated with GitHub or Bitbucket to automatically build and push images when there are new commits to the codebase.

  • Set up automatic builds
  • Create a new repository on Docker Hub and select Auto-Build.
  • Connect to GitHub or Bitbucket and select your repository and branch.
  • Configure the path and build rules of the Dockerfile.

Webhooks

Webhooks allow Docker Hub to send HTTP requests to a specified URL after the image is built, which is used to trigger subsequent CI/CD processes.

  • Configure webhooks
  • On the Settings page of the Docker Hub repository, find Webhooks.
  • Add a new webhook and enter the destination URL.

Mirror scanning

Docker Hub provides an image scanning feature that scans images for known vulnerabilities to help improve application security.

  • Enable Image Scan On the Settings page of the Docker Hub repository, enable the image scanning feature. Each time a new image is pushed, Docker Hub will automatically perform a security scan and provide a scan report.

Docker Compose

Docker Compose is a tool for defining and running multi-container Docker applications. With a simple YAML file, users can configure all the services that the application needs and start and stop them with a single command. Compose is a powerful tool for developing, testing, and deploying applications with a microservices architecture.

Docker Compose is usually installed with Docker, but it can also be installed separately. Here are the installation steps on different platforms:

  • Linux:
sudo curl -L "https://github.com/docker/compose/releases/download/v2.2.3/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose
           
Does a network engineer need to be familiar with Docker? I don't think you need to be proficient, but you need to know the basics
Does a network engineer need to be familiar with Docker? I don't think you need to be proficient, but you need to know the basics
  • MacOS: 使用 Homebrew 安装
brew install docker-compose
           
  • Windows: Docker Desktop 自带Docker Compose,安装 Docker Desktop 即可。

Docker Compose的基本概念

服务(Services)

In Docker Compose, a service defines the configuration of a container. A service can be a database, a web server, etc. The Compose file defines multiple services by the services keyword, and each service corresponds to a container.

Networks

Compose allows the definition of multiple networks to which services can connect to communicate. By default, Compose creates a default network for all services.

卷(Volumes)

Volumes are used for persistent storage. Compose allows you to define a volume and mount it into a container for a service.

Docker Compose文件格式

一个简单的docker-compose.yml文件示例如下:

version: '3'
services:
  web:
    image: nginx
    ports:
      - "80:80"
  db:
    image: mysql:5.7
    environment:
      MYSQL_ROOT_PASSWORD: example
           

版本(Version)

The version of the Compose file defines the format of the syntax, and the features supported by different versions are different. It is recommended to use the latest version (e.g. 3 or 3.8).

version: '3.8'
           

Detailed explanation of service configuration

  • image: 指定使用的镜像
  • build: 指定构建镜像的上下文路径和Dockerfile
  • ports: Port mapping
  • environment: 环境变量
  • volumes: 卷的挂载
services:
  web:
    image: nginx
    ports:
      - "80:80"
    volumes:
      - ./html:/usr/share/nginx/html
  db:
    image: mysql:5.7
    environment:
      MYSQL_ROOT_PASSWORD: example
    volumes:
      - db_data:/var/lib/mysql
           

Network configuration

By default, all services are connected to a network called default. Custom networks can be defined:

networks:
  frontend:
  backend:
           

and connect services to these networks:

services:
  web:
    networks:
      - frontend
  db:
    networks:
      - backend
           

Volume configuration

Volumes can be defined in the Compose file:

volumes:
  db_data:
           

and mount it into the service's container:

services:
  db:
    volumes:
      - db_data:/var/lib/mysql
           

Docker Compose的基本操作

启动和停止服务 (docker-compose up, docker-compose down)

  • Start the service:
docker-compose up
           

The command will start all the services defined in the Compose file and output the logs in the console.

  • Background Running Services:
docker-compose up -d
           
  • Discontinuation of Service:
docker-compose down
           

查看服务状态 (docker-compose ps)

The docker-compose ps command is used to view the status of the currently running service:

docker-compose ps
           

重启服务 (docker-compose restart)

docker-compose restart命令用于重启服务:

docker-compose restart <服务名>
           

查看服务日志 (docker-compose logs)

docker-compose logs命令用于查看服务的日志:

docker-compose logs <服务名>
           

Docker Compose的高级功能

Multi-environment configuration

By using multiple Compose files, different configurations can be defined for different environments (e.g., development, test, production).

  • 基础Compose文件 (docker-compose.yml):
version: '3.8'
services:
  web:
    image: nginx
    ports:
      - "80:80"
           
  • 覆盖Compose文件 (docker-compose.override.yml):
version: '3.8'
services:
  web:
    environment:
      - NGINX_ENV=development
           
  • When you start the service, the overwrite file is automatically applied:
docker-compose up
           
  • Custom Environment Compose file:

例如,为生产环境创建docker-compose.prod.yml:

version: '3.8'
services:
  web:
    environment:
      - NGINX_ENV=production
           

Specify the environment file at startup:

docker-compose -f docker-compose.yml -f docker-compose.prod.yml up -d
           

Expand services

The scale option allows you to scale the number of replicas of a service for load balancing and high availability.

  • Extended Service Replica:
docker-compose up -d --scale web=3
           

The above command will start 3 copies of the web service.

Dependency management

You can manage service-initiated dependencies through depends_on options. For example, the web service depends on the DB service:

services:
  web:
    image: nginx
    depends_on:
      - db
  db:
    image: mysql:5.7
    environment:
      MYSQL_ROOT_PASSWORD: example
           

Let's say we want to build a simple web application that includes a front-end service (using nginx), a back-end service (using Node.js), and a database service (using MySQL).

Create a docker-compose.yml file that defines the front-end, back-end, and database services:

version: '3.8'
services:
  frontend:
    image: nginx:latest
    ports:
      - "80:80"
    volumes:
      - ./frontend:/usr/share/nginx/html
    networks:
      - app-network

  backend:
    build:
      context: ./backend
      dockerfile: Dockerfile
    ports:
      - "3000:3000"
    networks:
      - app-network

  db:
    image: mysql:5.7
    environment:
      MYSQL_ROOT_PASSWORD: example
      MYSQL_DATABASE: appdb
    volumes:
      - db_data:/var/lib/mysql
    networks:
      - app-network

networks:
  app-network:

volumes:
  db_data:
           

Create the necessary directories and files:

  • Front-end directory structure:
frontend/
└── index.html
           
  • Backend directory structure:
backend/
├── Dockerfile
└── app.js
           

编写前端的index.html:

<!DOCTYPE html>
<html>
<head>
    <title>My App</title>
</head>
<body>
    <h1>Hello from Nginx</h1>
</body>
</html>
           

编写后端的Dockerfile:

FROM node:14
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["node", "app.js"]
           

Write the app.js for the backend:

const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
  res.send('Hello from Node.js');
});

app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});
           

Launch the app:

docker-compose up -d
           

In this case, the front-end services of the application are accessed through the http://localhost, and the back-end services are accessed through the http://localhost:3000.

Docker Swarm

Docker Swarm is a Docker-native container orchestration tool for managing and orchestrating Docker containers on multiple hosts. Swarm clusters are made up of multiple Docker engines that provide features such as high availability, scalability, and load balancing. With Swarm, developers can manage multiple nodes and containers across a cluster in the same way they manage a single Docker instance.

Docker Swarm and Kubernetes are the two main container orchestration tools. Swarm is integrated in Docker, which is simple to use and suitable for small and medium-sized projects; Kubernetes is powerful and suitable for large-scale and complex applications. Choosing the right orchestration tool based on project requirements is the key to improving development and O&M efficiency.

Does a network engineer need to be familiar with Docker? I don't think you need to be proficient, but you need to know the basics

Docker Swarm的基本概念

Nodes

A Swarm cluster consists of multiple nodes. Each node is a host running Docker, which is divided into a manager node and a worker node. The management node is responsible for cluster management and task scheduling, and the worker node is responsible for running the container.

服务(Services)

Services are the basic unit of Swarm management. The service defines the container images, running parameters, and number of applications for which they operate. Swarm deploys and manages containers in a cluster based on service definitions.

Tasks

A task is a concrete instance of a service. Each task corresponds to a running container, and Swarm is responsible for scheduling and managing tasks to ensure high availability and load balancing of services.

堆栈(Stacks)

A stack is an application that is made up of multiple services. Using the stack, developers can define and manage services, networks, and volumes across the application. The stack file is similar to the Compose file but works with Swarm clusters.

Set up and manage a Docker Swarm cluster

Initialize the Swarm cluster

To initialize the Swarm cluster on the host, use the docker swarm init command:

docker swarm init --advertise-addr <管理节点IP>
           

After the initialization is successful, the command line outputs the command and token to join the Swarm cluster.

Joining and leaving a Swarm cluster

On the worker node, run the docker swarm join command to join the cluster:

docker swarm join --token <worker-token> <管理节点IP>:2377
           

Use the docker swarm leave command to leave the cluster:

docker swarm leave
           

在管理节点上使用docker swarm leave --force命令强制离开并停止集群:

docker swarm leave --force
           

Manage nodes and roles

  • To view the list of nodes:
docker node ls
           
  • The promoted node is the management node:
docker node promote <节点ID>
           
  • To demote a management node to a worker node:
docker node demote <节点ID>
           

Create and manage Swarm services

Create a service

使用docker service create命令创建服务:

docker service create --name <服务名> --replicas <副本数量> <镜像>
           

For example, create a service that runs nginx:

docker service create --name web --replicas 3 -p 80:80 nginx
           

Update the service

使用docker service update命令更新服务:

docker service update --replicas <新的副本数量> <服务名>
           

For example, update the number of replicas of a web service to 5:

docker service update --replicas 5 web
           

Delete the service

Use the docker service rm command to delete a service:

docker service rm <服务名>
           

For example, to delete a web service:

docker service rm web
           

View the status of your service

使用Docker Service LS命令查看服务列表:

docker service ls
           

Run the docker service ps command to view the task status of the service:

docker service ps <服务名>
           

Swarm supports rolling updates to the service, ensuring that applications remain highly available during the update process. Use the docker service update command and specify the update parameters:

docker service update --image <新镜像> <服务名>
           

For example, to update the image of a web service:

docker service update --image nginx:latest web
           

If there is a problem with the service update, you can use the docker service rollback command to roll back to the previous version:

docker service rollback <服务名>
           

Swarm supports the creation of overlay networks that allow containers to communicate across hosts. Use the docker network create command to create an overlay network:

docker network create --driver overlay <网络名>
           

Then specify the network when the service is created:

docker service create --name <服务名> --network <网络名> <镜像>
           

Swarm supports configuration and key management to ensure that sensitive information is securely passed to the service. Use the docker config and docker secret commands to manage configurations and keys.

For example, create a configuration:

echo "my-config-data" | docker config create my-config -
           

Use the configuration at service creation time:

docker service create --name <服务名> --config source=my-config,target=/path/in/container <镜像>
           

⏰ Write at the end

Docker, at the heart of modern containerization technology, has dramatically changed the way software is developed, tested, and deployed.

Finally, let's make a simple summary, so that you can quickly grasp the content of this article, and you can see the last warrior, and you can remember the summary part.

Does a network engineer need to be familiar with Docker? I don't think you need to be proficient, but you need to know the basics

The basic concept of Docker

  • Container: A lightweight, self-contained executable package that includes an application and all of its dependencies.
  • Image: An immutable container template used to create containers.
  • Docker引擎(Docker Engine):运行Docker容器的核心引擎。
  • Dockerfile: a script that describes the process of building a Docker image.

Basic operations with Docker

  • Mirroring Operations:
  • docker pull:从Docker Hub拉取镜像。
  • docker build:根据Dockerfile构建镜像。
  • docker push:将镜像推送到Docker Hub。
  • Container Operations:
  • docker run:启动容器。
  • docker stop:停止容器。
  • docker rm:删除容器。
  • docker exec: executes commands in a running container.

Data Management & Networking

  • Volume: Persistent storage, independent of the container lifecycle.
  • 创建和管理卷:docker volume create、docker volume ls、docker volume rm。
  • Volume mounting: Use the -v option in the docker run command.
  • Network: A bridge for communication between containers.
  • 创建和管理网络:docker network create、docker network ls、docker network rm。
  • 网络模式:Bridge、Host、Overlay等。

Docker Compose

  • To define and run a multi-container app:
  • Use YAML files to define services, networks, and volumes.
  • 启动和管理服务:docker-compose up、docker-compose down、docker-compose ps。
  • Advanced features:
  • Multi-environment configuration: Multiple Compose files support different environment configurations.
  • Scaling a service: Use docker-compose scale to scale a replica of a service.

Docker Swarm

  • Cluster Management and Orchestration:
  • 初始化Swarm集群:docker swarm init。
  • 加入和离开集群:docker swarm join、docker swarm leave。
  • 管理节点和服务:Docker Node、Docker Service。
  • Advanced features:
  • 服务滚动更新和回滚:docker service update、docker service rollback。
  • 配置和密钥管理:Docker Config、Docker Secret。
  • Multi-host network: Cross-host communication is implemented through an overlay network.

End of this article!

Read on