Table of contents
1. Docker concept
- 1. Docker is a tool for packaging, distributing and deploying applications
- 2、
镜像Image、容器Container、仓库Repository
- Mirror image: It can be understood as a software installation package, which can be easily spread and installed.
- Container: The state after the software is installed, each software operating environment is independent and isolated, called a container
- Warehouse: mirrors are easy to spread, and the warehouse is a place dedicated to spreading these mirrors. It is somewhat similar to Github, or you can think of it as a mirror store that stores various mirrors
- 3、
打包、分发、部署
- Packaging: It is to package the dependencies, third-party libraries, and software required for your software to run into an installation package
- Distribution: You can upload your packaged "installation package" to a mirror warehouse, and others can obtain and install it very conveniently
- Deployment: With the "installation package", you can run your application with one command, and automatically simulate the exact same operating environment, whether it is on Windows/Mac/Linux
- 4、
Docker部署的优势
- Conventional application development and deployment method: develop and test on Windows --> deploy to the Linux server to configure the operating environment, the problem
我机器上跑都没问题,怎么到服务器就各种问题了
- Use Docker to develop and deploy the process: develop and test on Windows --> package it as a Docker image (which can be understood as a software installation package) --> deploy on various servers with only one command,
确保了不同机器上跑都是一致的运行环境,不会出现我机器上跑正常,你机器跑就有问题的情况
- Conventional application development and deployment method: develop and test on Windows --> deploy to the Linux server to configure the operating environment, the problem
- 5. A brief introduction to using docker:
- Your project only needs three steps,
在当前目录下再加一个dockerfile文件 》》docker build创建镜像 》》docker run运行容器命令后,你的项目就可以运行跑起来了,此时就形成的容器
- But every time you deploy, you always have to execute docker build to create a mirror "" docker run to run the container will be very troublesome, so you can specify it in the dockerfile file, so that it can take effect in time and at the same time,
挂载目录
saving the previous two commands - One project, one container, two projects, two containers, how the two containers communicate with each other, such as front-end and back-end services, at this point we can, at this time, the
创建虚拟网络docker network create test-net
two containers specify the same virtual network test when executing docker run -net can communicate with each other - Two containers: Web project + Redis, if the project relies on more third-party software, we need to manage more containers, each must be configured separately to run docker build+docker run, specifying the network, which is more troublesome, the
而docker-compose
project Multiple services of multiple services are gathered together and run with one click, which saves the need to configure a virtual network. All services in docker-compose automatically use the same network, and docker-compose only needs to create another yml file. 总结下来:创建一个dockerfile文件+一个yml文件+执行docker-compose up -d 命令即可实现多个容器通信
- Your project only needs three steps,
- 6. Introduction to docker commands:
2. Download and install
-
1. Download address , refer to document 1 , refer to document 2 , and refer to video
-
2. After the installation is complete, the startup error is as follows:
WSL 2 installation is incomplete.
Solution reference
-
Solution step 1: Control Panel->Programs->Programs and Features, open the following check box, if there are still problems, see step 2
-
Solution step 2: Download the new version of wsl2 , install the new version of wsl2, if there are still problems, see step 3
-
Solution step 3: execute cmd
netsh winsock reset
, and then restart the computer to solve the problem
-
-
3. After the installation of Docker is completed, it will be automatically started every time it is turned on by default. Execute
docker -v
-
4. Mirror accelerator download source setting address, add a line
"registry-mirrors":["https://mirror.ccs.tencentyun.com","https://registry.docker-cn.com"],
-
5. Other mirror addresses
mirror accelerator | Mirror accelerator address |
---|---|
Docker China official image | https://registry.docker-cn.com |
DaoCloud mirror site | http://f1361db2.m.daocloud.io |
Azure China Mirror | https://dockerhub.azk8s.cn |
HKUST Mirror Station | https://docker.mirrors.ustc.edu.cn |
Ali Cloud | https://<your_code>.mirror.aliyuncs.com |
Qiniu Yun | https://reg-mirror.qiniu.com |
NetEase Cloud | https://hub-mirror.c.163.com |
Tencent Cloud | https://mirror.ccs.tencentyun.com |
3. Docker image installation and operation
-
1. View the currently owned image:
docker image ls
ordocker images
-
2. Delete the image:
docker image rm 镜像名或镜像ID 或 docker rmi 镜像名或镜像ID
, the premise of deleting the image is that there is no container using this image. If there is a need to delete the container first, otherwise an error will be reported
-
3. Install mirroring:
docker pull [名称]:[版本]
, go to the common search address for docker installation mirroringdocker pull python:3.7 docker pull mongo docker pull redis docker pull mysql docker pull nginx docker pull node docker pull centos
-
4. Run the container:
docker run [可选参数] 镜像名 [向启动容器中传入的命令]
, if there is no image, it will download the image first
Commonly used optional parameters-d
: A daemon container will be created to run in the background, so that the container will not be automatically logged in after the container is created-p
: Indicates port mapping, that is, host port: port in the container. For example: -p 8080:80 is to map port 80 in the container to port 8080 in the host–name
: Name the created container. (The name will be given randomly by default, Chinese characters are not supported!!!)-v
: Indicates the directory mapping relationship, that is, host directory: directory in the container. Note: It is best to do directory mapping, modify it on the host, and then share it to the container–network=host
: Indicates that the network environment of the host is mapped to the container, so that the network of the container is the same as that of the host. Each Docker container has its own networking space connected to the virtual LAN. Using this command will allow the container and the host to share a network space-i
: means to run the container in "interactive mode"-t
: Indicates that the container will enter its command line after it starts. After adding these two parameters, the container can be created and logged in. That is, allocate a pseudo-terminal.
-
5. Load redis: Execute in the cmd window
docker run -d -p 6379:6379 --name redis redis:latest
, and at this time, the running container redis will be applied on the desktop
-
6. The use process of desktop container redis
4. Make your own python mirror container
-
1. Create a folder docker_all and a docker_test.py file. First export the dependent package and execute
pip freeze > requirements.txt
import sys print(sys.version) print("Hello, World!")
-
2. Write a dockerfile, specify the image that your project depends on, and which directory folder it is in as follows
# syntax=docker/dockerfile:1 # 第一行是解析器指令,始终用版本1语法的最新版本 # 指定基础镜像 FROM python:3.7-slim-buster # 设置工作目录文件夹 WORKDIR ./docker_all # 复制依赖文件 COPY requirements.txt requirements.txt # 安装依赖 RUN pip install -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/ # 复制其他的脚本文件 COPY . . #当启动容器时候,执行程序 CMD ["python", "./docker_test.py"]
-
3. Create a mirror,
-t
: set the mirror name and version number,docker build -f [dockerfile文件路径名] -t [创建的镜像名]:[tag] .
pay attention to one.
, the time to create a mirror for the first time is a bit long and wait for a whiledocker build -f E:\docker_all\dockerfile -t demo_1:v0 .
-
4. View the currently owned image:
docker image ls
, as shown in the figure, the image has been successfully created
-
5. Start the container:
docker run --name c_test demo_1:v0
-
6. Save the image:
docker save -o demo.tar demo_1:v0
-
7. Delete the image:
docker rmi 镜像id
, or go to the desktop version to delete the image
-
8. Load the packaged jar package:
docker load -i demo.tar
5. Directory mount
-
1、
使用 Docker 运行后,我们改了项目代码不会立刻生效,如下每次都需要重新build和run,很麻烦
# build:docker build -f E:\docker_all\dockerfile -t demo_1:v0 . # 未挂载:docker run --name c_test demo_1:v0 # 挂载:docker run --name a_test -v E:\docker_all:/docker_all -d demo_1:v0
-
2. Three common mounting methods:
bind mount 方式用绝对路径 -v E:\docker_all:/docker_all
: Directly map the host directory to the container, suitable for hanging code directories and configuration files. Can be hung on multiple containers;volume 方式,只需要一个名字 -v db-data:/app
: Created and managed by the container, created on the host machine, so deleting the container will not lose it, officially recommended, more efficient, Linux file system, suitable for storing database data. Can be hung on multiple containers- tmpfs mount is suitable for storing temporary files in the host memory. Cannot be shared by multiple containers.
-
3. Execute the command to mount, or according to the previous case,
docker run --name a_test -v E:\docker_all:/docker_all -d demo_1:v0
and then open the desktop docker container and click to view the Mounts in Inspect. The path is mounted successfully. At this time, you modify your local code, and the code of the container will follow at the same time. Revise
-
4. Restart the container, try to run the container, and find that the result has changed, indicating that the mount is successful
6. Multi-container communication
- 1.
创建虚拟网络
: To communicate between multiple containers, to access the Redis container from the Web container, we only need to put them in the same network# 创建一个名为test-net的网络 docker network create test-net # 运行 Redis 在 test-net 网络中,别名redis docker run -d --name redis --network test-net --network-alias redis redis:latest # 修改python的redis连接地址 r = StrictRedis(host='redis', port=6379, db=0, password=None) # 运行 Web 项目,使用同个网络 docker run -p 8011:8011 --name test -v E:\docker_all:/docker_all --network test-net -d demo_1:v0
- 2. Try a new image container without connecting to redis first, then set up a redis connection test later
- 2.1, python file
# -*- coding: utf-8 -*- """ @Time : 2022/12/4 @Author: Shirmay @Blog: https://blog.csdn.net/weixin_43411585/ @公众号: 逆向OneByOne uvicorn docker_web:app --reload --host 127.0.0.1 --port 8011 """ import uvicorn from fastapi import FastAPI from redis import StrictRedis app = FastAPI() @app.get("/{_word}") def index(_word): """http://127.0.0.1:8011/user""" print("web_return", _word) # r = StrictRedis(host='redis', port=6379, db=0, password=None) # r.rpush('web_name', _word) # print("redis_llen:", r.llen('web_name')) return _word if __name__ == '__main__': uvicorn.run("docker_web:app", host='0.0.0.0', port=8011, reload=True)
- 2.2, dockerfile file
# syntax=docker/dockerfile:1 # 第一行是解析器指令,始终用版本1语法的最新版本 # 基础镜像 FROM python:3.7-slim-buster # 设置工作目录文件夹 WORKDIR ./docker_all # 复制依赖文件 COPY requirements.txt requirements.txt # 安装依赖 RUN /usr/local/bin/python -m pip install --upgrade pip -i https://mirrors.aliyun.com/pypi/simple/ RUN pip install uvicorn -i https://mirrors.aliyun.com/pypi/simple/ RUN pip install fastapi -i https://mirrors.aliyun.com/pypi/simple/ RUN pip install redis -i https://mirrors.aliyun.com/pypi/simple/ # RUN pip install -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/ # 复制其他的脚本文件 COPY . . #当启动容器时候,执行程序 CMD ["python", "./docker_web.py"]
- 3. Execute the build and run commands, then open http://localhost:8011/aa and find that it can be accessed normally
# 1、构建镜像并挂载 docker build -f E:\docker_all\dockerfile -t demo_2:v0 . docker run --name d_test -p 8011:8011 -v E:\docker_all:/docker_all -d demo_2:v0 # 2、然后可以浏览器打开 http://localhost:8011/aa 测试看看 # 3、下载redis docker pull redis # 4、设置网络 docker network create test-net docker run -d --name redis_net --network test-net --network-alias redis redis:latest # 5、修改python代码以及redis连接地址 @app.get("/{_word}") def index(_word): """http://127.0.0.1:8011/user""" print("web_return", _word) r = StrictRedis(host='redis_net', port=6379, db=0, password=None) r.rpush('web_name', _word) print("redis_llen:", r.llen('web_name')) return f"{r.llen('web_name')}_{_word}" # 6、运行 Web 项目,使用同个网络 docker run -p 8012:8011 --name test2 -v E:\docker_all:/docker_all --network test-net -d demo_2:v0 # 7、再次浏览器打开 http://localhost:8011/aa 测试看看
7. Docker-Compose manages multiple container operations
-
1. In directory six, we run two containers: Web project + Redis, if the project relies on more third-party software,
我们需要管理的容器就更加多,每个都要单独配置运行,指定网络,这样比较麻烦
, anddocker-compose 把项目的多个服务集合到一起,一键运行
-
2. If the desktop version is installed, docker-compose is already included, otherwise it needs to be installed separately and execute docker-compose
-
3. Write a
docker-compose.yml
file to describe which services are depended on. Two services are marked here, one is the service of app, and the other is the service of redis;在docker-compose.yml 文件所在目录,执行:docker-compose up -d就可以跑起来了
version: "3.7" services: # app服务和redis服务 app: # 服务名字app build: ./ # 直接从当前目录build ports: - 9011:8011 volumes: - ./:/docker_all # 挂载目录,把当前目录挂载到/docker_all这个目录下 environment: - TZ=Asia/Shanghai redis: # 服务名字redis image: redis:5.0.13 volumes: - redis:/data environment: - TZ=Asia/Shanghai volumes: redis:
-
4、
docker-compose其它命令
在后台运行只需要加一个 -d 参数
:docker-compose up -d查看当前多个服务运行状态
:docker-compose ps停止运行
:docker-compose stop重启
:docker-compose restart重启单个服务
:docker-compose restart service-name进入容器命令行
:docker-compose exec service-name sh查看容器运行log
:docker-compose logs [service-name]
8. Release and deployment
- The mirror warehouse is used to store the "installation package" we built. Docker officially provides a mirror warehouse , which contains a large number of mirrors. Basically, all kinds of software require dependencies. If you want anything, go directly to search
- reference documents
- Register the official docker image account and log in , then choose to create a warehouse, and then the image we built can be uploaded to this warehouse
- Then go to the command line and execute as follows
docker build -f E:\docker_all\dockerfile -t test:v1 . docker login -u shirmay1 docker tag test:v1 shirmay1/test:v1 docker push shirmay1/test:v1 docker run -dp 8011:8011 shirmay1/test:v1 然后打开http://localhost:8011/bb 正常返回
阿里云容器托管 docker 官方的镜像托管有时候上传和下载都太慢了,如果你想要更快的速度,可以使用阿里云的免费镜像托管登录 阿里云
Alibaba Cloud , and then search for containers to create warehouses to use