docker 基础进阶

.

一、Docker概述

1.Docker为什么会出现?
一款产品: 开发–上线 两套环境!应用环境,应用配置!
开发 — 运维。 问题:我在我的电脑上可以允许!版本更新,导致服务不可用!对于运维来说考验十分
大?
环境配置是十分的麻烦,每一个机器都要部署环境(集群Redis、ES、Hadoop…) !费事费力。
发布一个项目( jar + (Redis MySQL JDK ES) ),项目能不能带上环境安装打包!
之前在服务器配置一个应用的环境 Redis MySQL JDK ES Hadoop 配置超麻烦了,不能够跨平台。
开发环境Windows,最后发布到Linux!
传统:开发jar,运维来做!
现在:开发打包部署上线,一套流程做完!
安卓流程:java — apk —发布(应用商店)一 张三使用apk一安装即可用!
docker流程: java-jar(环境) — 打包项目帯上环境(镜像) — ( Docker仓库:商店)-----
Docker给以上的问题,提出了解决方案!
Docker的思想就来自于集装箱!
JRE – 多个应用(端口冲突) – 原来都是交叉的!
隔离:Docker核心思想!打包装箱!每个箱子是互相隔离的。
Docker通过隔离机制,可以将服务器利用到极致!
本质:所有的技术都是因为出现了一些问题,我们需要去解决,才去学习!
2.Dcoker的历史
2010年,几个的年轻人,就在美国成立了一家公司 dotcloud
做一些pass的云计算服务!LXC(Linux Container容器)有关的容器技术!
Linux Container容器是一种内核虚拟化技术,可以提供轻量级的虚拟化,以便隔离进程和资源。
他们将自己的技术(容器化技术)命名就是 Docker。
Docker刚刚延生的时候,没有引起行业的注意!dotCloud,就活不下去!
开源
2013年,Docker开源!
越来越多的人发现docker的优点!火了。Docker每个月都会更新一个版本!
2014年4月9日,Docker1.0发布!
docker为什么这么火?十分的轻巧!
在容器技术出来之前,我们都是使用虚拟机技术!
虚拟机:在window中装一个VMware,通过这个软件我们可以虚拟出来一台或者多台电脑!笨重!
虚拟机也属于虚拟化技术,Docker容器技术,也是一种虚拟化技术!
vm : linux centos 原生镜像(一个电脑!) 隔离、需要开启多个虚拟机! 几个G 几分钟
docker: 隔离,镜像(最核心的环境 4m + jdk + mysql)十分的小巧,运行镜像就可以了!小巧!
几个M 秒级启动!
Docker基于Go语言开发的!开源项目!
docker官网:https://www.docker.com/
文档:https://docs.docker.com/ Docker的文档是超级详细的!
仓库:https://hub.docker.com/
3.Docker能做什么?
比较Docker和虚拟机技术的不同:
传统虚拟机,虚拟出一条硬件,运行一个完整的操作系统,然后在这个系统上安装和运行软件
容器内的应用直接运行在宿主机的内容,容器是没有自己的内核的,也没有虚拟我们的硬件,所以
就轻便了
每个容器间是互相隔离,每个容器内都有一个属于自己的文件系统,互不影响
4.DevOps(开发、运维)
应用更快速的交付和部署
传统:一对帮助文档,安装程序。
Docker:打包镜像发布测试一键运行。
更便捷的升级和扩缩容
使用了 Docker之后,我们部署应用就和搭积木一样
项目打包为一个镜像,扩展服务器A!服务器B
更简单的系统运维
更高效的计算资源利用
Docker是内核级别的虚拟化,可以在一个物理机上可以运行很多的容器实例!服务器的性能可以被压榨
到极致。
二、Docker安装
1.Docker的基本组成

二、Docker安装

1.Docker的基本组成

image-20220829144805822

镜像(image):
docker镜像就好比是一个目标,可以通过这个目标来创建容器服务,tomcat镜像==>run==>容器(提
供服务器),通过这个镜像可以创建多个容器(最终服务运行或者项目运行就是在容器中的)。
容器(container):
Docker利用容器技术,独立运行一个或者一组应用,通过镜像来创建的.
启动,停止,删除,基本命令
目前就可以把这个容器理解为就是一个简易的 Linux系统。
仓库(repository):
仓库就是存放镜像的地方!
仓库分为公有仓库和私有仓库。(很类似git)
Docker Hub是国外的。
阿里云…都有容器服务器(配置镜像加速!)
2.安装Docker
环境准备
 Linux要求内核3.0以上
➜ ~ uname -r
4.15.0-96-generic # 要求3.0以上
➜ ~ cat /etc/os-release
NAME="Ubuntu"
VERSION="18.04.4 LTS (Bionic Beaver)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 18.04.4 LTS"
VERSION_ID="18.04"
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacypolicy"VERSION_CODENAME=bionic
UBUNTU_CODENAME=bionic

帮助文档:https://docs.docker.com/engine/install


#1.卸载旧版本
yum remove docker \
docker-client \
docker-client-latest \
docker-common \
docker-latest \
docker-latest-logrotate \
docker-logrotate \
docker-engine
#2.需要的安装包
yum install -y yum-utils
#3.设置镜像的仓库
yum-config-manager \
--add-repo \
https://download.docker.com/linux/centos/docker-ce.repo
#默认是从国外的,不推荐
#推荐使用国内的
yum-config-manager \
--add-repo \
https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
#更新yum软件包索引
yum makecache fast
#4.安装docker相关的 docker-ce 社区版 而ee是企业版
yum install docker-ce docker-ce-cli containerd.io
#6. 使用docker version查看是否按照成功
docker version
#7. 测试
docker run hello-world
#7. 测试
➜ ~ docker run hello-worl

Hello from Docker!
This message shows that your installation appears to be working correctly.
To generate this message, Docker took the following steps:
1. The Docker client contacted the Docker daemon.
2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
(amd64)
3. The Docker daemon created a new container from that image which runs the
executable that produces the output you are currently reading.
4. The Docker daemon streamed that output to the Docker client, which sent it
to your terminal.
To try something more ambitious, you can run an Ubuntu container with:
$ docker run -it ubuntu bash
Share images, automate workflows, and more with a free Docker ID:
https://hub.docker.com/
For more examples and ideas, visit:
https://docs.docker.com/get-started/
#8.查看一下下载的镜像
➜ ~ docker images
REPOSITORY TAG IMAGE ID CREATED
SIZE
hello-world latest bf756fb1ae65 4 months ago
13.3kB



了解:卸载docker
阿里云镜像加速
 1、登录阿里云找到容器服务
 2、找到镜像加速器
 3、配置使用
#8.查看一下下载的镜像
➜ ~ docker images
REPOSITORY TAG IMAGE ID CREATED
SIZE
hello-world latest bf756fb1ae65 4 months ago
13.3kB
#1. 卸载依赖
yum remove docker-ce docker-ce-cli containerd.io
#2. 删除资源
rm -rf /var/lib/docker
# /var/lib/docker 是docker的默认工作路径!

image-20220829144945247

image-20220829144951564

![](C:\Users\Administrator\Desktop\我的文档\CSDN\Docker\Docker3.png)
**docker run 流程图**
![](C:\Users\Administrator\Desktop\我的文档\CSDN\Docker\Docker4.png
3.底层原理
Docker是怎么工作的?
Docker是一个Client-Server结构的系统,Docker的守护进程运行在主机上。通过Socket从客户端访
问!
Docker-Server接收到Docker-Client的指令,就会执行这个命令!

image-20220829145013875

为什么Docker比Vm快
1、docker有着比虚拟机更少的抽象层。由于docker不需要Hypervisor实现硬件资源虚拟化,运行在
docker容器上的程序直接使用的都是实际物理机的硬件资源。因此在CPU、内存利用率上docker将会在
效率上有明显优势。
2、docker利用的是宿主机的内核,而不需要Guest OS。
GuestOS: VM(虚拟机)里的的系统(OS);
HostOS:物理机里的系统(OS);

image-20220829145025788

因此,当新建一个 容器时,docker不需要和虚拟机一样重新加载一个操作系统内核。然而避免引导、加
载操作系统内核是个比较费时费资源的过程,当新建一个虚拟机时,虚拟机软件需要加载GuestOS,返
个新建过程是分钟级别的。而docker由于直接利用宿主机的操作系统,则省略了这个复杂的过程,因此
新建一个docker容器只需要几秒钟。

Docker的常用命令

1.帮助命令
2.镜像命令
docker images 查看所有本地的主机上的镜像
docker version #显示docker的版本信息。
docker info #显示docker的系统信息,包括镜像和容器的数量
docker 命令 --help #帮助命令
#帮助文档的地址:https://docs.docker.com/engine/reference/commandline/build/
docker images #查看所有本地主机上的镜像 可以使用docker image ls代替
docker search 搜索镜像
docker pull 下载镜像 docker image pull
docker rmi 删除镜像 docker image rm
➜ ~ docker images
REPOSITORY TAG IMAGE ID CREATED
SIZE
mysql 5.7 e73346bdf465 24 hours ago
448MB
# 解释
#REPOSITORY # 镜像的仓库源
#TAG # 镜像的标签
#IMAGE ID # 镜像的id
#CREATED # 镜像的创建时间
#SIZE # 镜像的大小
# 可选项
Options:
-a, --all Show all images (default hides intermediate images) #列出
所有镜像
-q, --quiet Only show numeric IDs # 只显示镜像的id
➜ ~ docker images -aq #显示所有镜像的id
e73346bdf465
d03312117bb0
d03312117bb0
602e111c06b6
2869fc110bf7
470671670cac
bf756fb1ae65
5acf0e8da90b
# 下载镜像 docker pull 镜像名[:tag]
➜ ~ docker pull tomcat:8
8: Pulling from library/tomcat #如果不写tag,默认就是latest
90fe46dd8199: Already exists #分层下载: docker image 的核心 联合文件系统
35a4f1977689: Already exists
bbc37f14aded: Already exists
74e27dc593d4: Already exists
93a01fbfad7f: Already exists
1478df405869: Pull complete
64f0dd11682b: Pull complete
68ff4e050d11: Pull complete
f576086003cf: Pull complete
3b72593ce10e: Pull complete
Digest: sha256:0c6234e7ec9d10ab32c06423ab829b32e3183ba5bf2620ee66de866df640a027
# 签名 防伪
Status: Downloaded newer image for tomcat:8
docker.io/library/tomcat:8 #真实地址
#等价于

docker rmi 删除镜像
docker pull tomcat:8
docker pull docker.io/library/tomcat:8
➜ ~ docker rmi -f 镜像id #删除指定的镜像
➜ ~ docker rmi -f 镜像id 镜像id 镜像id 镜像id#删除指定的镜像
➜ ~ docker rmi -f $(docker images -aq) #删除全部的镜像
容器命令
docker run 镜像id 新建容器并启动
docker ps 列出所有运行的容器 docker container list
docker rm 容器id 删除指定容器
docker start 容器id #启动容器
docker restart容器id #重启容器
docker stop 容器id #停止当前正在运行的容器
docker kill 容器id #强制停止当前容器
说明:我们有了镜像才可以创建容器,Linux,下载centos镜像来学习
➜ ~ docker container
Usage: docker container COMMAND
Manage containers
Commands:
attach Attach local standard input, output, and error streams to a
running container
commit Create a new image from a container's changes
cp Copy files/folders between a container and the local filesystem
create Create a new container
diff Inspect changes to files or directories on a container's
filesystem
exec Run a command in a running container
export Export a container's filesystem as a tar archive
inspect Display detailed information on one or more containers
kill Kill one or more running containers
logs Fetch the logs of a container
ls List containers
pause Pause all processes within one or more containers
port List port mappings or a specific mapping for the container
prune Remove all stopped containers
rename Rename a container
restart Restart one or more containers
rm Remove one or more containers
run Run a command in a new container
start Start one or more stopped containers
stats Display a live stream of container(s) resource usage statistics
stop Stop one or more running containers
top Display the running processes of a container
unpause Unpause all processes within one or more containers
update Update configuration of one or more containers
wait Block until one or more containers stop, then print their exit
codes
Run 'docker container COMMAND --help' for more information on a command.


docker run [可选参数] image | docker container run [可选参数] image
#参书说明
--name="Name" 容器名字 tomcat01 tomcat02 用来区分容器
-d 后台方式运行
-it 使用交互方式运行,进入容器查看内容
-p 指定容器的端口 -p 8080(宿主机):8080(容器)
-p ip:主机端口:容器端口
-p 主机端口:容器端口(常用)
-p 容器端口
容器端口
-P(大写) 随机指定端口
# 测试、启动并进入容器
➜ ~ docker run -it centos /bin/bash
Unable to find image 'centos:latest' locally
latest: Pulling from library/centos
8a29a15cefae: Already exists
Digest: sha256:fe8d824220415eed5477b63addf40fb06c3b049404242b31982106ac204f6700
Status: Downloaded newer image for centos:latest
[root@95039813da8d /]# ls
bin dev etc home lib lib64 lost+found media mnt opt proc root run
sbin srv sys tmp usr var
[root@95039813da8d /]# exit #从容器退回主机
exit
➜ ~ ls
shell user.txt

#docker ps命令 #列出当前正在运行的容器
-a, --all Show all containers (default shows just running)
-n, --last int Show n last created containers (includes all states)
(default -1)
-q, --quiet Only display numeric IDs
➜ ~ docker ps
CONTAINER ID IMAGE COMMAND CREATED
STATUS PORTS NAMES
68729e9654d4 portainer/portainer "/portainer" 14 hours ago
Up About a minute 0.0.0.0:8088->9000/tcp funny_curie
d506a017e951 nginx "nginx -g 'daemon of…" 15 hours ago
Up 15 hours 0.0.0.0:3344->80/tcp nginx01
➜ ~ docker ps -a
CONTAINER ID IMAGE COMMAND CREATED
STATUS PORTS NAMES
95039813da8d centos "/bin/bash" 3 minutes ago
Exited (0) 2 minutes ago condescending_pike
1e46a426a5ba tomcat "catalina.sh run" 11 minutes
ago Exited (130) 9 minutes ago sweet_gould
14bc9334d1b2 bf756fb1ae65 "/hello" 3 hours ago
Exited (0) 3 hours ago amazing_stonebraker
f10d60f473f5 bf756fb1ae65 "/hello" 3 hours ago
Exited (0) 3 hours ago dreamy_germain
68729e9654d4 portainer/portainer "/portainer" 14 hours ago
Up About a minute 0.0.0.0:8088->9000/tcp funny_curie
677cde5e4f1d elasticsearch "/docker-entrypoint.…" 15 hours ago
Exited (143) 8 minutes ago elasticsearch
33eb3f70b4db tomcat "catalina.sh run" 15 hours ago
Exited (143) 8 minutes ago tomcat01
d506a017e951 nginx "nginx -g 'daemon of…" 15 hours ago
Up 15 hours 0.0.0.0:3344->80/tcp nginx01
24ce2db02e45 centos "/bin/bash" 16 hours ago
Exited (0) 15 hours ago hopeful_faraday
42267d1ad80b bf756fb1ae65 "/hello" 16 hours ago
Exited (0) 16 hours ago ecstatic_sutherland
➜ ~ docker ps -aq
95039813da8d
1e46a426a5ba
14bc9334d1b2
f10d60f473f5
68729e9654d4
677cde5e4f1d
33eb3f70b4db
d506a017e951
24ce2db02e45
42267d1ad80b

退出容器
exit #容器直接退出
ctrl +P +Q #容器不停止退出

删除容器
docker rm 容器id #删除指定的容器,不能删除正在运行的容器,如果要强制删除 rm -rf
docker rm -f $(docker ps -aq) #删除指定的容器
docker ps -a -q|xargs docker rm #删除所有的容器

启动和停止容器的操作
docker start 容器id #启动容器
docker restart 容器id #重启容器
docker stop 容器id #停止当前正在运行的容器
docker kill 容器id #强制停止当前容器
4.常用其他命令
后台启动命令

# 命令 docker run -d 镜像名
➜ ~ docker run -d centos
a8f922c255859622ac45ce3a535b7a0e8253329be4756ed6e32265d2dd2fac6c
➜ ~ docker ps
CONTAINER ID IMAGE COMMAND CREATED
STATUS PORTS NAMES
# 问题docker ps. 发现centos 停止了
# 常见的坑,docker容器使用后台运行,就必须要有要一个前台进程,docker发现没有应用,就会自动停止
# nginx,容器启动后,发现自己没有提供服务,就会立刻停止,就是没有程序了

查看日志
docker logs --help
Options:
--details Show extra details provided to logs
* -f, --follow Follow log output
--since string Show logs since timestamp (e.g. 2013-01-02T13:23:37) or
relative (e.g. 42m for 42 minutes)
* --tail string Number of lines to show from the end of the logs
(default "all")
* -t, --timestamps Show timestamps
--until string Show logs before a timestamp (e.g. 2013-01-02T13:23:37)
or relative (e.g. 42m for 42 minutes)
➜ ~ docker run -d centos /bin/sh -c "while true;do echo 6666;sleep 1;done" #模
拟日志
#显示日志
-tf #显示日志信息(一直更新)
--tail number #需要显示日志条数
docker logs -t --tail n 容器id #查看n行日志
docker logs -ft 容器id #跟着日志

查看容器中进程信息 ps
docker top 容器id
查看镜像的元数据
# 命令
docker inspect 容器id
#测试
➜ ~ docker inspect 55321bcae33d
[
{
"Id":
"55321bcae33d15da8280bcac1d2bc1141d213bcc8f8e792edfd832ff61ae5066",
"Created": "2020-05-15T05:22:05.515909071Z",
"Path": "/bin/sh",
...
}
]
➜ ~

进入当前正在运行的容器

# 我们通常容器都是使用后台方式运行的,需要进入容器,修改一些配置
# 命令
docker exec -it 容器id bashshell
#测试
➜ ~ docker ps
CONTAINER ID IMAGE COMMAND CREATED
STATUS PORTS NAMES
55321bcae33d centos "/bin/sh -c 'while t…" 10 minutes ago
Up 10 minutes bold_bell
a7215824a4db centos "/bin/sh -c 'while t…" 13 minutes ago
Up 13 minutes zen_kepler
55a31b3f8613 centos "/bin/bash" 15 minutes ago
Up 15 minutes lucid_clarke
➜ ~ docker exec -it 55321bcae33d /bin/bash
[root@55321bcae33d /]#
# 方式二
docker attach 容器id
#测试
docker attach 55321bcae33d
正在执行当前的代码...
区别
#docker exec #进入当前容器后开启一个新的终端,可以在里面操作。(常用)
#docker attach # 进入容器正在执行的终端

从容器内拷贝到主机上

docker cp 容器id:容器内路径 主机目的路径
#进入docker容器内部
➜ ~ docker exec -it 55321bcae33d /bin/bash
[root@55321bcae33d /]# ls
bin etc lib lost+found mnt proc run srv tmp var
dev home lib64 media opt root sbin sys usr
#新建一个文件
[root@55321bcae33d /]# echo "hello" > java.java
[root@55321bcae33d /]# cat java.java
hello
[root@55321bcae33d /]# exit
exit
➜ ~ docker cp 55321bcae33d:/java.java / #拷贝
➜ ~ cd /
➜ / ls #可以看见java.java存在
bin home lib mnt run sys vmlinuz
boot initrd.img lib64 opt sbin tmp vmlinuz.old
dev initrd.img.old lost+found proc srv usr wget-log
etc java.java media root swapfile var

Docker Compose
8.1 简介
Docker

DockerFile build run 手动操作,单个容器

微服务,100个微服务,依赖关系

Docker Compose来轻松高效的管理容器,定义运行多个容器

官方介绍

定义、运行多个容器

YAML file配置文件

single command,命令有哪些?

Compose is a tool for defining and running multi-container Docker applications. With Compose, you use a YAML file to configure your application’s services. Then, with a single command, you create and start all the services from your configuration. To learn more about all the features of Compose, see the list of features.

Compose works in all environments: production, staging, development, testing, as well as CI workflows. You can learn more about each case in Common Use Cases.

Using Compose is basically a three-step process:

Define your app’s environment with a Dockerfile so it can be reproduced anywhere.
Dockerfile保证我们的项目在任何地方都可以运行
Define the services that make up your app in docker-compose.yml so they can be run together in an isolated environment.
services什么是服务
docker-compose.yml这个文件怎么写
Run docker compose up and the Docker compose command starts and runs your entire app. You can alternatively run docker-compose up using the docker-compose binary.
启动项目
作用:批量容器编排。

Compose是Docker官方的开源项目,需要安装

Dockerfile让程序在任何地方运行,web服务,redis、mysql、nginx…多个容器

Compose

version: "3.9"  # optional since v1.27.0
services:
  web:
    build: .
    ports:
      - "5000:5000"
    volumes:
      - .:/code
      - logvolume01:/var/log
    links:
      - redis
  redis:
    image: redis
volumes:
  logvolume01: {}

ocker compose up 100个服务

Compose:重要的概念。

  • 服务services,容器,应用(web、redis、mysql)
  • 项目project,一组关联的容器。

.2 安装

  1. 下载
sudo curl -L "https://github.com/docker/compose/releases/download/1.29.1/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose

# 这个可能快点
curl -L https://get.daocloud.io/docker/compose/releases/download/1.29.1/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose

授权

sudo chmod +x /usr/local/bin/docker-compose

image-20210509201441920

8.3 体验

官网地址

python应用,计数器,redis

1、应用app.py

- 为项目创建文件夹
mkdir composetest
cd composetest

创建app.py

import time

import redis
from flask import Flask

app = Flask(__name__)
cache = redis.Redis(host='redis', port=6379)

def get_hit_count():
    retries = 5
    while True:
        try:
            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)

  • 创建requirements.txt文件
flask
redis

2、Dockerfile应用打包为镜像

创建Dockerfile文件

# syntax=docker/dockerfile:1
FROM python:3.7-alpine
WORKDIR /code
ENV FLASK_APP=app.py
ENV FLASK_RUN_HOST=0.0.0.0
RUN apk add --no-cache gcc musl-dev linux-headers
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
EXPOSE 5000
COPY . .
CMD ["flask", "run"]

3、Docker-compose yaml文件(定义整个服务于,需要的环境,web、redis)

version: "3.9"
services:
  web:
    build: .
    ports:
      - "5000:5000"
  redis:
    image: "redis:alpine"

4、启动compose

docker-compose up

docker-compose up的执行流程

1、创建网络

2、执行Docker-compose yaml

3、启动服务

Creating composetest_web_1 … done

Creating composetest_redis_1 … done

image-20210509210414361

image-20210509210649773

docker images

image-20210509210748560

1、文件名 composetest

2、服务

默认的服务名 文件名_num

多个服务器,集群 A B_num 副本数量

服务redis服务=>4个副本

集群状态,服务都不可能只有一个运行实例。弹性、10 HA 高并发

3、网络规则


image-20210509211949998

10个服务=>项目(项目中的内容都在同一个网络下,域名访问)

image-20210509212211005

如果在同一个网络下,我们可以通过域名进行访问

停止命令

docker-compose down
Ctrl+C

image-20210509212854704

docker-compose

以前都是单个docker run启动容器

docker-compose通过docker-compose编写yaml配置文件、可以通过compose一键启动所有服务,停止

Docker小结:

1、Docker镜像,run=>容器

2、DockerFile构建镜像(服务打包)

3、docker-compose启动项目(编排、多个微服务/环境)

4、Docker网络

8.4 yaml 规则
docker-compose.yaml 核心

# 3层

version: '' # 版本
services: # 服务
	服务1: web
		# 服务配置
		images
		build
		network
		......
	服务2: redis
		.....
	服务3: mysql
		.....
# 其他配置 网络/卷 全局规则
volumes:
networks:
configs

ymal 规则

Compose配置(yaml)编写规则

docker-compose.yaml 核心

# 有且只有3层
# 版本、服务、其他配置
version:'' # 版本
services:
	服务1: web # 服务
		#服务配置
		images
		build
		network
		...
	服务2: redis

# 其他配置:网络、卷、全局规则
volumes:
networks:
configs:

部分服务配置选项

depends_on:依赖(启动顺序)

image-20210216180852515

deploy:部署,集群相关。

image-20210216181109650

expose:暴露端口

image-20210216181253793

image:镜像

image-20210216181424924

使用Compose一键部署WP博客

定义项目

创建一个文件夹

PS C:\workspace\Docker> mkdir my_wordpress
PS C:\workspace\Docker> cd my_wordpress

创建docker-compose.yml

可以使用.yml和.yaml作为扩展名,都可用。

粘贴以下内容:

version: '3.3' # 版本

services: # 两个服务,wordpress和db
   db:
     image: mysql:5.7
     volumes: # 挂载卷
       - db_data:/var/lib/mysql
     restart: always # 总是重启(?)
     environment: # 环境变量
       MYSQL_ROOT_PASSWORD: somewordpress
       MYSQL_DATABASE: wordpress
       MYSQL_USER: wordpress
       MYSQL_PASSWORD: wordpress

   wordpress:
     depends_on: # 先启动db,再启动wordpress
       - db
     image: wordpress:latest
     ports:
       - "8000:80"
     restart: always
     environment:
       WORDPRESS_DB_HOST: db:3306
       WORDPRESS_DB_USER: wordpress
       WORDPRESS_DB_PASSWORD: wordpress
       WORDPRESS_DB_NAME: wordpress
volumes:
    db_data: {}

建立项目

启动:

docker-compose up
PS C:\workspace\Docker\my_wordpress> docker-compose up
my_wordpress_db_1 is up-to-date
Recreating my_wordpress_wordpress_1 ... done
Attaching to my_wordpress_db_1, my_wordpress_wordpress_1
wordpress_1  | WordPress not found in /var/www/html - copying now...
db_1         | 2021-02-16 10:26:19+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.33-1debian10 started.
db_1         | 2021-02-16 10:26:19+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
db_1         | 2021-02-16 10:26:19+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.33-1debian10 started.
db_1         | 2021-02-16 10:26:19+00:00 [Note] [Entrypoint]: Initializing database files
db_1         | 2021-02-16T10:26:19.182967Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
db_1         | 2021-02-16T10:26:19.360897Z 0 [Warning] InnoDB: New log files created, LSN=45790
db_1         | 2021-02-16T10:26:19.411452Z 0 [Warning] InnoDB: Creating foreign key constraint system tables.
db_1         | 2021-02-16T10:26:19.424573Z 0 [Warning] No existing UUID has been found, so we assume that this is the first time that this server has been started. Generating a new UUID: 688de008-7041-11eb-8641-0242ac130002.
db_1         | 2021-02-16T10:26:19.428337Z 0 [Warning] Gtid table is not ready to be used. Table 'mysql.gtid_executed' cannot be opened.
db_1         | 2021-02-16T10:26:20.385482Z 0 [Warning] CA certificate ca.pem is self signed.
db_1         | 2021-02-16T10:26:20.607625Z 1 [Warning] root@localhost is created with an empty password ! Please consider switching off the --initialize-insecure option.
db_1         | 2021-02-16 10:26:24+00:00 [Note] [Entrypoint]: Database files initialized
db_1         | 2021-02-16 10:26:24+00:00 [Note] [Entrypoint]: Starting temporary server
db_1         | 2021-02-16 10:26:24+00:00 [Note] [Entrypoint]: Waiting for server startup
db_1         | 2021-02-16T10:26:24.371446Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
db_1         | 2021-02-16T10:26:24.372434Z 0 [Note] mysqld (mysqld 5.7.33) starting as process 78 ...
db_1         | 2021-02-16T10:26:24.376067Z 0 [Note] InnoDB: PUNCH HOLE support available
db_1         | 2021-02-16T10:26:24.376098Z 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
db_1         | 2021-02-16T10:26:24.376102Z 0 [Note] InnoDB: Uses event mutexes
db_1         | 2021-02-16T10:26:24.376105Z 0 [Note] InnoDB: GCC builtin __atomic_thread_fence() is used for memory barrier
db_1         | 2021-02-16T10:26:24.376107Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.11
db_1         | 2021-02-16T10:26:24.376109Z 0 [Note] InnoDB: Using Linux native AIO
db_1         | 2021-02-16T10:26:24.376304Z 0 [Note] InnoDB: Number of pools: 1
db_1         | 2021-02-16T10:26:24.376372Z 0 [Note] InnoDB: Using CPU crc32 instructions
db_1         | 2021-02-16T10:26:24.378183Z 0 [Note] InnoDB: Initializing buffer pool, total size = 128M, instances = 1, chunk size = 128M
db_1         | 2021-02-16T10:26:24.388068Z 0 [Note] InnoDB: Completed initialization of buffer pool
db_1         | 2021-02-16T10:26:24.391007Z 0 [Note] InnoDB: If the mysqld execution user is authorized, page cleaner thread priority can be changed. See the man page of setpriority().
db_1         | 2021-02-16T10:26:24.403193Z 0 [Note] InnoDB: Highest supported file format is Barracuda.
db_1         | 2021-02-16T10:26:24.418151Z 0 [Note] InnoDB: Creating shared tablespace for temporary tables
db_1         | 2021-02-16T10:26:24.418240Z 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...
db_1         | 2021-02-16T10:26:24.433871Z 0 [Note] InnoDB: File './ibtmp1' size is now 12 MB.
db_1         | 2021-02-16T10:26:24.434343Z 0 [Note] InnoDB: 96 redo rollback segment(s) found. 96 redo rollback segment(s) are active.
db_1         | 2021-02-16T10:26:24.434368Z 0 [Note] InnoDB: 32 non-redo rollback segment(s) are active.
db_1         | 2021-02-16T10:26:24.435624Z 0 [Note] InnoDB: 5.7.33 started; log sequence number 2746831
db_1         | 2021-02-16T10:26:24.436742Z 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool
db_1         | 2021-02-16T10:26:24.436787Z 0 [Note] Plugin 'FEDERATED' is disabled.
db_1         | 2021-02-16T10:26:24.438249Z 0 [Note] InnoDB: Buffer pool(s) load completed at 210216 10:26:24
db_1         | 2021-02-16T10:26:24.443738Z 0 [Note] Found ca.pem, server-cert.pem and server-key.pem in data directory. Trying to enable SSL support using them.
db_1         | 2021-02-16T10:26:24.443773Z 0 [Note] Skipping generation of SSL certificates as certificate files are present in data directory.
db_1         | 2021-02-16T10:26:24.444238Z 0 [Warning] CA certificate ca.pem is self signed.
db_1         | 2021-02-16T10:26:24.444276Z 0 [Note] Skipping generation of RSA key pair as key files are present in data directory.
db_1         | 2021-02-16T10:26:24.448269Z 0 [Warning] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory.
db_1         | 2021-02-16T10:26:24.455171Z 0 [Note] Event Scheduler: Loaded 0 events
db_1         | 2021-02-16T10:26:24.455425Z 0 [Note] mysqld: ready for connections.
db_1         | Version: '5.7.33'  socket: '/var/run/mysqld/mysqld.sock'  port: 0  MySQL Community Server (GPL)
db_1         | 2021-02-16 10:26:25+00:00 [Note] [Entrypoint]: Temporary server started.
db_1         | Warning: Unable to load '/usr/share/zoneinfo/iso3166.tab' as time zone. Skipping it.
db_1         | Warning: Unable to load '/usr/share/zoneinfo/leap-seconds.list' as time zone. Skipping it.
db_1         | Warning: Unable to load '/usr/share/zoneinfo/zone.tab' as time zone. Skipping it.
db_1         | Warning: Unable to load '/usr/share/zoneinfo/zone1970.tab' as time zone. Skipping it.
db_1         | 2021-02-16 10:26:27+00:00 [Note] [Entrypoint]: Creating database wordpress
db_1         | 2021-02-16 10:26:27+00:00 [Note] [Entrypoint]: Creating user wordpress
db_1         | 2021-02-16 10:26:27+00:00 [Note] [Entrypoint]: Giving user wordpress access to schema wordpress
db_1         |
db_1         | 2021-02-16 10:26:27+00:00 [Note] [Entrypoint]: Stopping temporary server
db_1         | 2021-02-16T10:26:27.857110Z 0 [Note] Giving 0 client threads a chance to die gracefully
db_1         | 2021-02-16T10:26:27.857156Z 0 [Note] Shutting down slave threads
db_1         | 2021-02-16T10:26:27.857162Z 0 [Note] Forcefully disconnecting 0 remaining clients
db_1         | 2021-02-16T10:26:27.857168Z 0 [Note] Event Scheduler: Purging the queue. 0 events
db_1         | 2021-02-16T10:26:27.857234Z 0 [Note] Binlog end
db_1         | 2021-02-16T10:26:27.857713Z 0 [Note] Shutting down plugin 'ngram'
db_1         | 2021-02-16T10:26:27.857745Z 0 [Note] Shutting down plugin 'partition'
db_1         | 2021-02-16T10:26:27.857751Z 0 [Note] Shutting down plugin 'BLACKHOLE'
db_1         | 2021-02-16T10:26:27.857755Z 0 [Note] Shutting down plugin 'ARCHIVE'
db_1         | 2021-02-16T10:26:27.857757Z 0 [Note] Shutting down plugin 'PERFORMANCE_SCHEMA'
db_1         | 2021-02-16T10:26:27.857780Z 0 [Note] Shutting down plugin 'MRG_MYISAM'
db_1         | 2021-02-16T10:26:27.857783Z 0 [Note] Shutting down plugin 'MyISAM'
db_1         | 2021-02-16T10:26:27.857790Z 0 [Note] Shutting down plugin 'INNODB_SYS_VIRTUAL'
db_1         | 2021-02-16T10:26:27.857793Z 0 [Note] Shutting down plugin 'INNODB_SYS_DATAFILES'
db_1         | 2021-02-16T10:26:27.857796Z 0 [Note] Shutting down plugin 'INNODB_SYS_TABLESPACES'
db_1         | 2021-02-16T10:26:27.857798Z 0 [Note] Shutting down plugin 'INNODB_SYS_FOREIGN_COLS'
db_1         | 2021-02-16T10:26:27.857800Z 0 [Note] Shutting down plugin 'INNODB_SYS_FOREIGN'
db_1         | 2021-02-16T10:26:27.857802Z 0 [Note] Shutting down plugin 'INNODB_SYS_FIELDS'
db_1         | 2021-02-16T10:26:27.857804Z 0 [Note] Shutting down plugin 'INNODB_SYS_COLUMNS'
db_1         | 2021-02-16T10:26:27.857807Z 0 [Note] Shutting down plugin 'INNODB_SYS_INDEXES'
db_1         | 2021-02-16T10:26:27.857809Z 0 [Note] Shutting down plugin 'INNODB_SYS_TABLESTATS'
db_1         | 2021-02-16T10:26:27.857811Z 0 [Note] Shutting down plugin 'INNODB_SYS_TABLES'
db_1         | 2021-02-16T10:26:27.857813Z 0 [Note] Shutting down plugin 'INNODB_FT_INDEX_TABLE'
db_1         | 2021-02-16T10:26:27.857816Z 0 [Note] Shutting down plugin 'INNODB_FT_INDEX_CACHE'
db_1         | 2021-02-16T10:26:27.857818Z 0 [Note] Shutting down plugin 'INNODB_FT_CONFIG'
db_1         | 2021-02-16T10:26:27.857820Z 0 [Note] Shutting down plugin 'INNODB_FT_BEING_DELETED'
db_1         | 2021-02-16T10:26:27.857823Z 0 [Note] Shutting down plugin 'INNODB_FT_DELETED'
db_1         | 2021-02-16T10:26:27.857825Z 0 [Note] Shutting down plugin 'INNODB_FT_DEFAULT_STOPWORD'
db_1         | 2021-02-16T10:26:27.857827Z 0 [Note] Shutting down plugin 'INNODB_METRICS'
db_1         | 2021-02-16T10:26:27.857829Z 0 [Note] Shutting down plugin 'INNODB_TEMP_TABLE_INFO'
db_1         | 2021-02-16T10:26:27.857832Z 0 [Note] Shutting down plugin 'INNODB_BUFFER_POOL_STATS'
db_1         | 2021-02-16T10:26:27.857834Z 0 [Note] Shutting down plugin 'INNODB_BUFFER_PAGE_LRU'
db_1         | 2021-02-16T10:26:27.857836Z 0 [Note] Shutting down plugin 'INNODB_BUFFER_PAGE'
db_1         | 2021-02-16T10:26:27.857839Z 0 [Note] Shutting down plugin 'INNODB_CMP_PER_INDEX_RESET'
db_1         | 2021-02-16T10:26:27.857841Z 0 [Note] Shutting down plugin 'INNODB_CMP_PER_INDEX'
db_1         | 2021-02-16T10:26:27.857843Z 0 [Note] Shutting down plugin 'INNODB_CMPMEM_RESET'
db_1         | 2021-02-16T10:26:27.857846Z 0 [Note] Shutting down plugin 'INNODB_CMPMEM'
db_1         | 2021-02-16T10:26:27.857848Z 0 [Note] Shutting down plugin 'INNODB_CMP_RESET'
db_1         | 2021-02-16T10:26:27.857850Z 0 [Note] Shutting down plugin 'INNODB_CMP'
db_1         | 2021-02-16T10:26:27.857853Z 0 [Note] Shutting down plugin 'INNODB_LOCK_WAITS'
db_1         | 2021-02-16T10:26:27.857855Z 0 [Note] Shutting down plugin 'INNODB_LOCKS'
db_1         | 2021-02-16T10:26:27.857858Z 0 [Note] Shutting down plugin 'INNODB_TRX'
db_1         | 2021-02-16T10:26:27.857860Z 0 [Note] Shutting down plugin 'InnoDB'
db_1         | 2021-02-16T10:26:27.857996Z 0 [Note] InnoDB: FTS optimize thread exiting.
db_1         | 2021-02-16T10:26:27.858230Z 0 [Note] InnoDB: Starting shutdown...
db_1         | 2021-02-16T10:26:27.958547Z 0 [Note] InnoDB: Dumping buffer pool(s) to /var/lib/mysql/ib_buffer_pool
db_1         | 2021-02-16T10:26:27.958831Z 0 [Note] InnoDB: Buffer pool(s) dump completed at 210216 10:26:27
db_1         | 2021-02-16T10:26:29.485919Z 0 [Note] InnoDB: Shutdown completed; log sequence number 12664279
db_1         | 2021-02-16T10:26:29.486978Z 0 [Note] InnoDB: Removed temporary tablespace data file: "ibtmp1"
db_1         | 2021-02-16T10:26:29.487025Z 0 [Note] Shutting down plugin 'MEMORY'
db_1         | 2021-02-16T10:26:29.487030Z 0 [Note] Shutting down plugin 'CSV'
db_1         | 2021-02-16T10:26:29.487034Z 0 [Note] Shutting down plugin 'sha256_password'
db_1         | 2021-02-16T10:26:29.487036Z 0 [Note] Shutting down plugin 'mysql_native_password'
db_1         | 2021-02-16T10:26:29.487125Z 0 [Note] Shutting down plugin 'binlog'
db_1         | 2021-02-16T10:26:29.487509Z 0 [Note] mysqld: Shutdown complete
db_1         |
db_1         | 2021-02-16 10:26:29+00:00 [Note] [Entrypoint]: Temporary server stopped
db_1         |
db_1         | 2021-02-16 10:26:29+00:00 [Note] [Entrypoint]: MySQL init process done. Ready for start up.
db_1         |
db_1         | 2021-02-16T10:26:30.017996Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
db_1         | 2021-02-16T10:26:30.019197Z 0 [Note] mysqld (mysqld 5.7.33) starting as process 1 ...
db_1         | 2021-02-16T10:26:30.022105Z 0 [Note] InnoDB: PUNCH HOLE support available
db_1         | 2021-02-16T10:26:30.022140Z 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
db_1         | 2021-02-16T10:26:30.022145Z 0 [Note] InnoDB: Uses event mutexes
db_1         | 2021-02-16T10:26:30.022148Z 0 [Note] InnoDB: GCC builtin __atomic_thread_fence() is used for memory barrier
db_1         | 2021-02-16T10:26:30.022150Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.11
db_1         | 2021-02-16T10:26:30.022152Z 0 [Note] InnoDB: Using Linux native AIO
db_1         | 2021-02-16T10:26:30.022354Z 0 [Note] InnoDB: Number of pools: 1
db_1         | 2021-02-16T10:26:30.022459Z 0 [Note] InnoDB: Using CPU crc32 instructions
db_1         | 2021-02-16T10:26:30.023679Z 0 [Note] InnoDB: Initializing buffer pool, total size = 128M, instances = 1, chunk size = 128M
db_1         | 2021-02-16T10:26:30.031595Z 0 [Note] InnoDB: Completed initialization of buffer pool
db_1         | 2021-02-16T10:26:30.033460Z 0 [Note] InnoDB: If the mysqld execution user is authorized, page cleaner thread priority can be changed. See the man page of setpriority().
db_1         | 2021-02-16T10:26:30.044681Z 0 [Note] InnoDB: Highest supported file format is Barracuda.
db_1         | 2021-02-16T10:26:30.056575Z 0 [Note] InnoDB: Creating shared tablespace for temporary tables
db_1         | 2021-02-16T10:26:30.056649Z 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...
db_1         | 2021-02-16T10:26:30.068761Z 0 [Note] InnoDB: File './ibtmp1' size is now 12 MB.
db_1         | 2021-02-16T10:26:30.069356Z 0 [Note] InnoDB: 96 redo rollback segment(s) found. 96 redo rollback segment(s) are active.
db_1         | 2021-02-16T10:26:30.069387Z 0 [Note] InnoDB: 32 non-redo rollback segment(s) are active.
db_1         | 2021-02-16T10:26:30.069963Z 0 [Note] InnoDB: 5.7.33 started; log sequence number 12664279
db_1         | 2021-02-16T10:26:30.070278Z 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool
db_1         | 2021-02-16T10:26:30.070421Z 0 [Note] Plugin 'FEDERATED' is disabled.
db_1         | 2021-02-16T10:26:30.072460Z 0 [Note] InnoDB: Buffer pool(s) load completed at 210216 10:26:30
db_1         | 2021-02-16T10:26:30.074498Z 0 [Note] Found ca.pem, server-cert.pem and server-key.pem in data directory. Trying to enable SSL support using them.
db_1         | 2021-02-16T10:26:30.074536Z 0 [Note] Skipping generation of SSL certificates as certificate files are present in data directory.
db_1         | 2021-02-16T10:26:30.075061Z 0 [Warning] CA certificate ca.pem is self signed.
db_1         | 2021-02-16T10:26:30.075101Z 0 [Note] Skipping generation of RSA key pair as key files are present in data directory.
db_1         | 2021-02-16T10:26:30.075588Z 0 [Note] Server hostname (bind-address): '*'; port: 3306
db_1         | 2021-02-16T10:26:30.075645Z 0 [Note] IPv6 is available.
db_1         | 2021-02-16T10:26:30.075654Z 0 [Note]   - '::' resolves to '::';
db_1         | 2021-02-16T10:26:30.075666Z 0 [Note] Server socket created on IP: '::'.
db_1         | 2021-02-16T10:26:30.079265Z 0 [Warning] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory.
db_1         | 2021-02-16T10:26:30.088971Z 0 [Note] Event Scheduler: Loaded 0 events
db_1         | 2021-02-16T10:26:30.089239Z 0 [Note] mysqld: ready for connections.
db_1         | Version: '5.7.33'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  MySQL Community Server (GPL)
wordpress_1  | Complete! WordPress has been successfully copied to /var/www/html
wordpress_1  | AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 172.19.0.3. Set the 'ServerName' directive globally to suppress this message
wordpress_1  | AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 172.19.0.3. Set the 'ServerName' directive globally to suppress this message
wordpress_1  | [Tue Feb 16 10:36:41.428025 2021] [mpm_prefork:notice] [pid 1] AH00163: Apache/2.4.38 (Debian) PHP/7.4.15 configured -- resuming normal operations
wordpress_1  | [Tue Feb 16 10:36:41.428083 2021] [core:notice] [pid 1] AH00094: Command line: 'apache2 -D FOREGROUND'

后台启动:

docker-compose up -d
PS C:\workspace\Docker\my_wordpress> docker-compose up -d
Starting my_wordpress_db_1 ... done
Starting my_wordpress_wordpress_1 ... done

image-20210216184451724

总结

  1. 下载项目(docker-compose.yml
  2. 如果需要文件,dockerfile。
  3. 文件准备齐全,一键启动项目。

一切都很简单

实战

需要有Java和spring boot基础

docker-swarm

image-20220829133503535

搭建集群

image-20220829133613361

posted @ 2021-12-02 14:34  #卧龙先生#  阅读(68)  评论(0编辑  收藏  举报